Neon Serverless Postgres — Cơ sở dữ liệu tách biệt Storage & Compute với Database Branching
Posted on: 4/27/2026 11:16:00 AM
Table of contents
- Vấn đề với PostgreSQL truyền thống
- Neon là gì?
- Kiến trúc tách Storage & Compute
- Database Branching — "Git cho Database"
- Autoscaling & Scale-to-Zero
- Point-in-Time Restore
- So sánh: Neon vs RDS vs Aurora vs Supabase
- Tích hợp với .NET & Node.js
- Use Cases thực tế trong Production
- Pricing & Free Tier 2026
- Kết luận
Vấn đề với PostgreSQL truyền thống
PostgreSQL là cơ sở dữ liệu quan hệ mã nguồn mở mạnh mẽ nhất hiện nay, nhưng khi triển khai trên cloud, mô hình truyền thống bộc lộ nhiều hạn chế:
- Compute và Storage gắn chặt — một instance RDS chạy cả query engine lẫn lưu trữ dữ liệu. Muốn scale storage phải scale cả compute, dẫn đến lãng phí tài nguyên.
- Không có scale-to-zero — dù không có traffic, instance vẫn chạy 24/7 và tính tiền. Một staging database chạy RDS db.t3.medium tốn ~30 USD/tháng dù chỉ dùng vài giờ.
- Tạo bản sao mất thời gian — snapshot và restore một database 100GB có thể mất 30-60 phút. Developer phải chờ đợi để có môi trường test riêng.
- Thiếu workflow branching — không có cơ chế tạo "nhánh" database giống như Git branch cho code. Mỗi developer test trên cùng staging DB, conflict liên tục.
Neon giải quyết toàn bộ các vấn đề trên bằng kiến trúc tách biệt storage và compute hoàn toàn.
Neon là gì?
Neon là nền tảng serverless PostgreSQL mã nguồn mở (Apache 2.0), được thiết kế lại từ đầu với triết lý tách biệt hoàn toàn tầng storage và compute. Neon tương thích 100% với PostgreSQL — mọi extension, ORM, driver hoạt động y như PostgreSQL gốc vì compute layer chạy chính xác PostgreSQL process.
Điểm khác biệt cốt lõi
Neon không phải là một "managed PostgreSQL" đơn thuần như RDS hay Cloud SQL. Neon viết lại tầng storage bằng Rust, tách biệt hoàn toàn khỏi compute, cho phép tính năng chưa từng có: database branching tức thì, autoscaling tự động, và scale-to-zero thật sự.
Tháng 5/2025, Databricks mua lại Neon với giá khoảng 1 tỷ USD — thương vụ lớn nhất trong lịch sử PostgreSQL — khẳng định giá trị của mô hình serverless database trong hệ sinh thái data hiện đại.
Kiến trúc tách Storage & Compute
Kiến trúc Neon gồm 3 thành phần chính, mỗi thành phần có thể scale độc lập:
graph TD
Client["🖥️ Application"] --> Compute["⚡ Compute Node
(PostgreSQL Process)"]
Compute --> |"WAL Stream"| SK1["📝 Safekeeper 1"]
Compute --> |"WAL Stream"| SK2["📝 Safekeeper 2"]
Compute --> |"WAL Stream"| SK3["📝 Safekeeper 3"]
SK1 --> PS["💾 Pageserver"]
SK2 --> PS
SK3 --> PS
PS --> S3["☁️ Object Storage
(S3 / compatible)"]
Compute --> |"Page Request"| PS
style Client fill:#f8f9fa,stroke:#e94560,color:#2c3e50
style Compute fill:#e94560,stroke:#fff,color:#fff
style SK1 fill:#2c3e50,stroke:#fff,color:#fff
style SK2 fill:#2c3e50,stroke:#fff,color:#fff
style SK3 fill:#2c3e50,stroke:#fff,color:#fff
style PS fill:#16213e,stroke:#fff,color:#fff
style S3 fill:#f8f9fa,stroke:#e94560,color:#2c3e50
Kiến trúc 3 tầng của Neon: Compute → Safekeeper → Pageserver → Object Storage
Compute Node
Mỗi compute node chạy một PostgreSQL process thật (không phải fork hay custom engine). Khi client gửi query, compute xử lý query bình thường, nhưng thay vì đọc/ghi dữ liệu trên disk cục bộ, nó giao tiếp với Pageserver qua network để lấy data pages.
Compute node là stateless — không lưu trữ durable state. Khi scale-to-zero, compute tắt hoàn toàn. Khi có request mới, một compute node mới được khởi tạo và kết nối lại với storage layer trong chưa đến 500ms.
Safekeeper
Safekeeper đóng vai trò trung gian cho Write-Ahead Log (WAL). Khi PostgreSQL ghi WAL records, chúng được replicate đến ít nhất 3 Safekeeper nodes sử dụng giao thức Paxos-based consensus. Điều này đảm bảo:
- Durability — WAL không bao giờ mất dù một Safekeeper node chết
- Low latency commit — transaction commit ngay khi majority (2/3) Safekeepers acknowledge
- Tách biệt khỏi Pageserver — Pageserver có thể xử lý WAL async mà không block writes
Pageserver
Pageserver là "bộ não" của storage layer. Nó nhận WAL records từ Safekeeper, materialize thành data pages, phục vụ page requests từ compute, và offload cold data xuống object storage (S3). Pageserver duy trì một Layer Store — cấu trúc LSM-tree-like lưu trữ page versions theo timeline, cho phép:
- Truy vấn data tại bất kỳ thời điểm nào trong quá khứ (point-in-time)
- Tạo branch mới từ bất kỳ thời điểm nào mà không copy data (copy-on-write)
- Garbage collect các page versions không còn cần thiết
Database Branching — "Git cho Database"
Đây là tính năng game-changer của Neon. Database branching hoạt động tương tự Git branching cho code:
graph LR
Main["🟢 main branch
(Production Data)"] --> |"Branch tại T1"| Dev["🔵 dev/feature-auth
(Copy-on-Write)"]
Main --> |"Branch tại T2"| Preview["🟣 preview/pr-142
(Copy-on-Write)"]
Main --> |"Branch tại T1"| Test["🟠 test/load-test
(Copy-on-Write)"]
style Main fill:#e94560,stroke:#fff,color:#fff
style Dev fill:#2c3e50,stroke:#fff,color:#fff
style Preview fill:#16213e,stroke:#fff,color:#fff
style Test fill:#f8f9fa,stroke:#e94560,color:#2c3e50
Database branching: mỗi branch là copy-on-write snapshot, không tốn storage cho data giống nhau
Cơ chế Copy-on-Write
Khi tạo branch, Neon không duplicate data. Branch mới chỉ tạo một con trỏ đến thời điểm trong timeline của branch gốc. Chỉ khi data bị modified trên branch mới, pages mới mới được tạo ra. Một database production 50GB có thể tạo branch trong < 1 giây và tốn gần 0 storage bổ sung.
Workflow thực tế
# Tạo branch cho feature development
neonctl branches create --name dev/feature-payment --parent main
# Tạo branch cho mỗi Pull Request (tự động qua GitHub Actions)
neonctl branches create --name preview/pr-${PR_NUMBER} --parent main
# Xóa branch khi PR merged
neonctl branches delete preview/pr-${PR_NUMBER}
💡 Tích hợp CI/CD
Neon cung cấp GitHub integration tự động tạo database branch cho mỗi Pull Request và xóa khi PR merged/closed. Mỗi preview deployment có database riêng với data production thật — không cần maintain fixtures hay seed scripts.
Use case branching
- Preview environments — mỗi PR có database branch riêng, Vercel/Netlify preview deploy kết nối đến branch tương ứng
- Schema migration testing — chạy migration trên branch trước, verify không lỗi, rồi mới chạy trên production
- Load testing — branch production data, chạy load test mà không ảnh hưởng production
- Debugging — branch data tại thời điểm xảy ra bug, debug trên branch mà không block team
Autoscaling & Scale-to-Zero
Neon autoscaling hoạt động ở tầng compute, tự động điều chỉnh CPU và RAM theo workload thực tế:
graph LR
Zero["💤 Scale-to-Zero
0 CU — $0"] --> |"Request đến"| Cold["⚡ Cold Start
~350-500ms"]
Cold --> Min["🟢 Min: 0.25 CU"]
Min --> |"Load tăng"| Mid["🔵 Auto: 2 CU"]
Mid --> |"Traffic spike"| Max["🔴 Max: 16 CU"]
Max --> |"Load giảm"| Mid
Mid --> |"Idle 5 phút"| Zero
style Zero fill:#f8f9fa,stroke:#e94560,color:#2c3e50
style Cold fill:#ff9800,stroke:#fff,color:#fff
style Min fill:#4CAF50,stroke:#fff,color:#fff
style Mid fill:#2c3e50,stroke:#fff,color:#fff
style Max fill:#e94560,stroke:#fff,color:#fff
Vòng đời autoscaling: từ zero → cold start → scale up/down → zero
Mỗi Compute Unit (CU) = 1 vCPU + 4GB RAM. Autoscaling cho phép cấu hình min/max CU:
| Cấu hình | Min CU | Max CU | Use Case |
|---|---|---|---|
| Development | 0 (scale-to-zero) | 0.25 | Local dev, staging ít traffic |
| Startup/Side Project | 0.25 | 2 | App nhỏ, traffic vừa phải |
| Production Standard | 1 | 8 | SaaS app, API service |
| High Traffic | 2 | 16 | E-commerce, real-time analytics |
⚠️ Cold Start Latency
Scale-to-zero có cold start ~350-500ms. Với ứng dụng yêu cầu latency cực thấp (real-time trading, gaming), nên set min CU ≥ 0.25 để compute luôn sẵn sàng. Phần lớn web app và API service chấp nhận được cold start này vì chỉ xảy ra sau thời gian idle.
Point-in-Time Restore
Nhờ storage layer lưu trữ page versions theo timeline, Neon hỗ trợ point-in-time restore (PITR) không cần backup thủ công:
| Plan | History Retention | Restore Time |
|---|---|---|
| Free | 6 giờ | Tức thì (tạo branch tại thời điểm bất kỳ) |
| Launch | 7 ngày | Tức thì |
| Scale | 30 ngày | Tức thì |
| Business | 30 ngày | Tức thì |
So sánh với RDS: restore từ snapshot mất 15-60 phút (phải tạo instance mới từ snapshot). Neon restore bằng cách tạo branch tại thời điểm mong muốn — dưới 1 giây.
# Restore database đến 2 giờ trước
neonctl branches create \
--name restore/before-incident \
--parent main \
--at "2026-04-27T08:00:00Z"
# Verify data trên branch restore
psql $RESTORE_BRANCH_CONNECTION_STRING -c "SELECT count(*) FROM orders;"
# Nếu OK, promote branch restore thành main
neonctl branches set-primary restore/before-incident
So sánh: Neon vs RDS vs Aurora vs Supabase
| Tiêu chí | Neon | AWS RDS | Aurora Serverless v2 | Supabase |
|---|---|---|---|---|
| Storage-Compute tách biệt | ✅ Hoàn toàn | ❌ Gắn chặt | ✅ (Aurora storage) | ❌ (dùng RDS bên dưới) |
| Scale-to-Zero | ✅ Thật sự (0 CU) | ❌ | ⚠️ Min 0.5 ACU | ✅ (pause project) |
| Database Branching | ✅ Copy-on-Write tức thì | ❌ (chỉ snapshot) | ❌ (clone mất phút) | ❌ |
| Cold Start | ~350-500ms | N/A (luôn chạy) | ~15-30 giây | Vài giây |
| PITR | Branch-based, tức thì | Snapshot-based, 15-60 phút | Backtrack, nhanh hơn RDS | Qua backup, chậm |
| Free Tier | 100 CU-hours, 0.5GB/project | 12 tháng free tier | Không | 500MB, 2 projects |
| PostgreSQL Compatibility | 100% (chạy PG thật) | 100% | 99%+ (Aurora-compatible) | 100% (chạy PG thật) |
| Mã nguồn mở | ✅ Apache 2.0 | ❌ | ❌ | ✅ (phần lớn) |
| Built-in Auth/API | ❌ (chỉ database) | ❌ | ❌ | ✅ (Auth, REST, Realtime) |
Khi nào chọn Neon?
Chọn Neon khi bạn cần database branching cho CI/CD, scale-to-zero để tiết kiệm chi phí staging/dev, hoặc PITR nhanh. Chọn Supabase khi cần BaaS đầy đủ (Auth, Storage, Realtime, Edge Functions). Chọn Aurora khi workload cần throughput cực cao và đã sâu vào hệ sinh thái AWS. Chọn RDS khi cần đơn giản, workload ổn định, không cần serverless.
Tích hợp với .NET & Node.js
Kết nối từ .NET (Npgsql + Entity Framework Core)
// appsettings.json
{
"ConnectionStrings": {
"NeonDb": "Host=ep-cool-name-123456.us-east-2.aws.neon.tech;Database=myapp;Username=myuser;Password=mypassword;SSL Mode=Require"
}
}
// Program.cs
builder.Services.AddDbContext<AppDbContext>(options =>
options.UseNpgsql(builder.Configuration.GetConnectionString("NeonDb")));
// Neon hỗ trợ connection pooling qua PgBouncer built-in
// Thêm ?pgbouncer=true vào connection string cho serverless workload
// Host=ep-cool-name-123456.us-east-2.aws.neon.tech;...;Pooling=true;Minimum Pool Size=0;Maximum Pool Size=20
Kết nối từ Node.js (Neon Serverless Driver)
import { neon } from '@neondatabase/serverless';
// Serverless driver — dùng HTTP, không cần TCP connection
const sql = neon(process.env.DATABASE_URL);
// Query đơn giản
const posts = await sql`SELECT * FROM posts WHERE status = 'published' ORDER BY created_at DESC LIMIT 10`;
// Transaction
import { neon } from '@neondatabase/serverless';
const sql = neon(process.env.DATABASE_URL);
const [order] = await sql.transaction([
sql`INSERT INTO orders (user_id, total) VALUES (${userId}, ${total}) RETURNING id`,
sql`UPDATE inventory SET quantity = quantity - ${qty} WHERE product_id = ${productId}`,
]);
💡 Neon Serverless Driver
Neon cung cấp driver JavaScript/TypeScript sử dụng HTTP thay vì TCP connection truyền thống. Điều này quan trọng cho serverless environments (Vercel Edge Functions, Cloudflare Workers) nơi TCP connection không khả dụng hoặc tốn kém do cold start.
Kết nối với Drizzle ORM
import { drizzle } from 'drizzle-orm/neon-http';
import { neon } from '@neondatabase/serverless';
const sql = neon(process.env.DATABASE_URL);
const db = drizzle(sql);
// Type-safe query
const users = await db.select().from(usersTable).where(eq(usersTable.role, 'admin'));
Use Cases thực tế trong Production
1. Preview Environments cho SaaS
graph LR
PR["📝 Pull Request"] --> GHA["⚙️ GitHub Actions"]
GHA --> Branch["🔀 Neon Branch
(Copy prod data)"]
GHA --> Deploy["🚀 Vercel Preview"]
Deploy --> Branch
Merge["✅ PR Merged"] --> Delete["🗑️ Delete Branch"]
style PR fill:#f8f9fa,stroke:#e94560,color:#2c3e50
style GHA fill:#2c3e50,stroke:#fff,color:#fff
style Branch fill:#e94560,stroke:#fff,color:#fff
style Deploy fill:#16213e,stroke:#fff,color:#fff
style Merge fill:#4CAF50,stroke:#fff,color:#fff
style Delete fill:#f8f9fa,stroke:#e94560,color:#2c3e50
Workflow CI/CD: mỗi PR tự động có database branch + preview deployment
2. Multi-tenant SaaS với Database-per-Tenant
Thay vì shared database với Row-Level Security, mỗi tenant có thể có một Neon project hoặc branch riêng. Với copy-on-write, tạo tenant mới gần như không tốn storage — chỉ data khác biệt mới tốn thêm.
3. Schema Migration Zero-Downtime
# Bước 1: Tạo branch từ production
neonctl branches create --name migration/add-payment-columns --parent main
# Bước 2: Chạy migration trên branch
psql $BRANCH_URL -f migrations/add_payment_columns.sql
# Bước 3: Chạy test suite với branch connection string
DATABASE_URL=$BRANCH_URL npm run test:integration
# Bước 4: Nếu OK, chạy migration trên production
psql $PRODUCTION_URL -f migrations/add_payment_columns.sql
# Bước 5: Cleanup
neonctl branches delete migration/add-payment-columns
4. AI/ML Development
Branch production data cho training pipeline, chạy vector search experiments (pgvector) trên branch riêng mà không ảnh hưởng production. Kể từ khi được Databricks mua lại, Neon đang tích hợp sâu hơn vào hệ sinh thái data — kỳ vọng sẽ có native integration với Databricks lakehouse trong tương lai.
Pricing & Free Tier 2026
| Plan | Compute | Storage | Projects | Giá/tháng |
|---|---|---|---|---|
| Free | 100 CU-hours, max 0.25 CU | 0.5 GB/project, tổng 5 GB | 10 | $0 |
| Launch | 300 CU-hours, max 4 CU | 10 GB included | 100 | $19 |
| Scale | 750 CU-hours, max 8 CU | 50 GB included | 1000 | $69 |
| Business | 1000 CU-hours, max 16 CU | 500 GB included | 5000 | $700 |
💡 Free Tier khá hào phóng
100 CU-hours/tháng đủ cho: 1 database 0.25 CU chạy liên tục 400 giờ (~16 ngày), hoặc nhiều branch database cho development workflow. Storage 0.5GB/project nghe ít nhưng nhờ copy-on-write, branches gần như không tốn thêm. 10 projects = 10 databases miễn phí cho side projects.
Kết luận
Neon đại diện cho thế hệ tiếp theo của cloud database — nơi storage và compute được tách biệt triệt để, cho phép những tính năng mà PostgreSQL truyền thống không thể cung cấp: branching tức thì, autoscaling linh hoạt, scale-to-zero thật sự, và point-in-time restore dưới 1 giây.
Với việc được Databricks mua lại, Neon đang trên đà trở thành tiêu chuẩn mới cho serverless PostgreSQL trong hệ sinh thái data hiện đại. Nếu bạn đang chạy staging/dev databases 24/7 trên RDS mà chỉ dùng vài giờ/ngày, hoặc đang loay hoay tạo test data cho CI/CD pipeline — Neon là lựa chọn đáng cân nhắc ngay lập tức.
Nguồn tham khảo:
Neon Architecture Overview — Neon Docs
Neon GitHub Repository (Apache 2.0)
Separation of Storage and Compute Without Performance Tradeoff — Neon Blog
Neon Pricing 2026 — vela.simplyblock.io
Neon Pricing — neon.com
Databricks and Neon — Databricks Blog
WebRTC — Kiến trúc Video Call P2P trực tiếp trên trình duyệt
Cloudflare R2 — Object Storage không phí Egress cho Developer
Disclaimer: The opinions expressed in this blog are solely my own and do not reflect the views or opinions of my employer or any affiliated organizations. The content provided is for informational and educational purposes only and should not be taken as professional advice. While I strive to provide accurate and up-to-date information, I make no warranties or guarantees about the completeness, reliability, or accuracy of the content. Readers are encouraged to verify the information and seek independent advice as needed. I disclaim any liability for decisions or actions taken based on the content of this blog.