🗄️ Databases

Neon

Serverless PostgreSQL

A serverless PostgreSQL platform: cloud-native PostgreSQL that branches databases like Git, automatically scales to zero when not in use, and scales up automatically when needed.

📖 Detailed Explanation

Neon is a serverless PostgreSQL platform built by a startup founded in 2021 by core PostgreSQL developers. Unlike conventional AWS RDS or Cloud SQL, compute and storage are separated, providing a true serverless model that costs 0 when there is no traffic and scales automatically when traffic surges.

Key Feature: Database Branching

Like Git branches, it clones the DB to instantly create development/staging environments. With Copy-on-Write, branches can be created without copying all of the production data.

Neon Key Features

🌿
Database Branching
Create DB branches like Git
📉
Scale to Zero
Automatic shutdown when not in use
📈
Auto-scaling
Automatic scaling with traffic
⏪
Point-in-Time Recovery
Point-in-time recovery
🐘
100% PostgreSQL
Full PG compatibility
🔌
Serverless Driver
Optimized for Edge/Serverless

💻 Code Example

1. Neon Serverless Driver (Edge Environment)

TypeScript (Vercel Edge Functions)
import { neon } from '@neondatabase/serverless'; // Neon Serverless Driver - HTTP 기반, 웹소켓 불필요 const sql = neon(process.env.DATABASE_URL!); export const config = { runtime: 'edge' }; export default async function handler(req: Request) { // 단일 쿼리 (HTTP fetch 기반) const posts = await sql` SELECT id, title, created_at FROM posts WHERE published = true ORDER BY created_at DESC LIMIT 10 `; // 파라미터화된 쿼리 (SQL Injection 방지) const userId = 123; const userPosts = await sql` SELECT * FROM posts WHERE author_id = ${userId} AND published = true `; return Response.json({ posts, userPosts }); } // 트랜잭션이 필요한 경우 (HTTP Transaction) async function transferCredits(fromId: number, toId: number, amount: number) { const sql = neon(process.env.DATABASE_URL!, { fetchOptions: { cache: 'no-store' } }); // BEGIN/COMMIT/ROLLBACK 대신 단일 요청으로 처리 const result = await sql.transaction([ sql`UPDATE users SET credits = credits - ${amount} WHERE id = ${fromId}`, sql`UPDATE users SET credits = credits + ${amount} WHERE id = ${toId}`, sql`INSERT INTO transfers (from_id, to_id, amount) VALUES (${fromId}, ${toId}, ${amount})`, ]); return result; }

2. Node.js Environment (Compatible with the Existing pg Driver)

TypeScript
import { Pool } from '@neondatabase/serverless'; import { drizzle } from 'drizzle-orm/neon-serverless'; import ws from 'ws'; // 웹소켓 설정 (Node.js 환경) import { neonConfig } from '@neondatabase/serverless'; neonConfig.webSocketConstructor = ws; // Connection Pool 사용 (기존 pg와 동일한 API) const pool = new Pool({ connectionString: process.env.DATABASE_URL }); // Drizzle ORM과 통합 const db = drizzle(pool); async function getUsers() { const client = await pool.connect(); try { await client.query('BEGIN'); const { rows: users } = await client.query(` SELECT u.*, COUNT(p.id) as post_count FROM users u LEFT JOIN posts p ON u.id = p.author_id GROUP BY u.id `); await client.query('COMMIT'); return users; } catch (e) { await client.query('ROLLBACK'); throw e; } finally { client.release(); } }

3. Database Branching (CLI)

Neon CLI
# Install Neon CLI npm install -g neonctl # Log in neonctl auth # Create a project neonctl projects create --name my-app # List branches neonctl branches list --project-id # Create a development branch from production (Copy-on-Write) neonctl branches create \ --project-id \ --name feature/new-feature \ --parent main # Create a branch at a specific point in time (Point-in-Time) neonctl branches create \ --project-id \ --name recovery/before-migration \ --parent main \ --at "2024-01-15T10:30:00Z" # Check a branch connection string neonctl connection-string --branch feature/new-feature # Delete a branch neonctl branches delete feature/new-feature

4. Vercel + Neon Integration (Preview Deployments)

vercel.json
{ "build": { "env": { "DATABASE_URL": "@neon_database_url" } } }
GitHub Actions (Automatic Preview Branch Creation)
name: Create Neon Branch for PR on: pull_request: types: [opened, synchronize] jobs: create-branch: runs-on: ubuntu-latest steps: - name: Create Neon Branch uses: neondatabase/create-branch-action@v4 with: project_id: ${{ secrets.NEON_PROJECT_ID }} branch_name: preview/pr-${{ github.event.pull_request.number }} api_key: ${{ secrets.NEON_API_KEY }} - name: Run Migrations run: | DATABASE_URL=${{ steps.create-branch.outputs.db_url }} \ npx prisma migrate deploy - name: Comment PR with DB URL uses: actions/github-script@v6 with: script: | github.rest.issues.createComment({ issue_number: context.issue.number, owner: context.repo.owner, repo: context.repo.repo, body: `Preview DB: \`${{ steps.create-branch.outputs.branch_id }}\`` })

5. pgvector and AI Embeddings

SQL + TypeScript
-- Neon에서 pgvector 활성화 CREATE EXTENSION IF NOT EXISTS vector; -- 임베딩 테이블 생성 CREATE TABLE documents ( id SERIAL PRIMARY KEY, content TEXT, embedding vector(1536) -- OpenAI ada-002 ); -- HNSW 인덱스 (빠른 유사도 검색) CREATE INDEX ON documents USING hnsw (embedding vector_cosine_ops); -- TypeScript에서 사용 import { neon } from '@neondatabase/serverless'; import OpenAI from 'openai'; const sql = neon(process.env.DATABASE_URL!); const openai = new OpenAI(); async function semanticSearch(query: string) { // 쿼리 임베딩 생성 const response = await openai.embeddings.create({ model: 'text-embedding-ada-002', input: query, }); const embedding = response.data[0].embedding; // 유사도 검색 const results = await sql` SELECT id, content, 1 - (embedding <=> ${JSON.stringify(embedding)}::vector) as similarity FROM documents WHERE 1 - (embedding <=> ${JSON.stringify(embedding)}::vector) > 0.7 ORDER BY embedding <=> ${JSON.stringify(embedding)}::vector LIMIT 5 `; return results; }

💬 Real-world conversation examples

DevOps engineer
"If you use Neon, it shuts down automatically when there's no traffic, so the dev DB cost is almost 0. You don't need to keep it always on like RDS."
Backend developer
"Database Branching is really great. You can test with production data on every PR, and I've set it up so the branch is deleted automatically when merged."
Full-stack developer
"To connect to the DB from Vercel Edge Functions, WebSockets don't work, right? The Neon Serverless Driver is HTTP-based, so it works on Edge too."
Tech Lead
"There is a Cold Start, but it's fast after the first connection. For production, disable scale-to-zero and keep it on only for the dev environment."

⚠️ Cautions

Cold Start Latency

After Scale-to-Zero, the first connection incurs a Cold Start of several seconds. In production, set the minimum number of instances to 1 or consider the Warm option.

Connection Limits

Due to its serverless nature, there is a limit on Connection Pool size. Use Connection Pooling (PgBouncer built in) and we recommend using the Serverless Driver.

Branch Storage Cost

Branches use Copy-on-Write, but changed data is stored separately. Delete old or unused branches regularly.

🔗 Related Terms

📚 Learn More