# Hướng Dẫn Neon Database Project này sử dụng [Neon PostgreSQL](https://neon.tech) cho tất cả môi trường. ## Tại Sao Chọn Neon? - **Serverless**: Không cần quản lý infrastructure - **Branching**: Database riêng cho dev/staging/prod - **Auto-scaling**: Tự động xử lý traffic spikes - **Point-in-time restore**: Dễ dàng khôi phục từ lỗi - **Free tier**: Hoàn hảo cho development - **Connection pooling**: Hỗ trợ PgBouncer tích hợp ## Kiến Trúc Neon ```mermaid graph TB subgraph NeonProject[" Neon Project: goodgo-platform"] Main["Branch: main
Development
Auto-scaling
Point-in-time restore"] Staging["Branch: staging
Staging
Created from main
Pre-production testing"] Production["Branch: production
Production
Created from main
Live environment"] end subgraph Features[" Tính Năng Chính"] F1[" Serverless
No infrastructure"] F2[" Auto-scaling
Handle spikes"] F3[" Backups
Point-in-time"] F4[" Pooling
PgBouncer"] end Main -->|Branch từ| Staging Main -->|Branch từ| Production Features -.->|Áp dụng cho| Main Features -.->|Áp dụng cho| Staging Features -.->|Áp dụng cho| Production style NeonProject fill:#1a1a2e,stroke:#16213e,stroke-width:2px,color:#fff style Main fill:#0f3460,stroke:#16213e,stroke-width:2px,color:#fff style Staging fill:#533483,stroke:#16213e,stroke-width:2px,color:#fff style Production fill:#c72c41,stroke:#16213e,stroke-width:2px,color:#fff style Features fill:#1a1a2e,stroke:#16213e,stroke-width:2px,color:#fff style F1 fill:#0f3460,stroke:#16213e,stroke-width:2px,color:#fff style F2 fill:#0f3460,stroke:#16213e,stroke-width:2px,color:#fff style F3 fill:#0f3460,stroke:#16213e,stroke-width:2px,color:#fff style F4 fill:#0f3460,stroke:#16213e,stroke-width:2px,color:#fff ``` ## Bắt Đầu Nhanh ### 1. Tạo Tài Khoản Neon 1. Đăng ký tại https://neon.tech 2. Tạo project mới: `goodgo-platform` ### 2. Tạo Branches Trong Neon Console, tạo branches: - `main` (development) - đã tồn tại - `staging` - tạo từ main - `production` - tạo từ main ### 3. Lấy Connection Strings Cho mỗi branch, copy connection string: - Định dạng: `postgresql://user:password@ep-xxx.region.neon.tech/dbname?sslmode=require` - Thêm `?pgbouncer=true` cho connection pooling (khuyến nghị) ### 4. Cấu Hình Local Development ```bash # Tạo .env.local cp deployments/local/env.local.example deployments/local/.env.local # Chỉnh sửa .env.local và thêm: DATABASE_URL=postgresql://user:pass@ep-xxx.region.neon.tech/dbname?sslmode=require&pgbouncer=true ``` ### 5. Chạy Migrations ```bash ./scripts/db/migrate.sh iam-service dev ``` ## Định Dạng Connection String ``` postgresql://[user]:[password]@[endpoint]/[dbname]?sslmode=require&pgbouncer=true ``` **Tham số**: - `sslmode=require` - Bắt buộc cho Neon - `pgbouncer=true` - Bật connection pooling (khuyến nghị) ## Cấu Hình Môi Trường ### Local Development File: `deployments/local/.env.local` ```bash DATABASE_URL=postgresql://user:pass@ep-xxx.region.neon.tech/dbname?sslmode=require&pgbouncer=true ``` ### Staging Lưu trong GitHub Secrets: `NEON_DATABASE_URL_STAGING` Hoặc trong Kubernetes: ```bash kubectl create secret generic iam-service-secrets \ --from-literal=database-url='postgresql://...' \ -n staging ``` ### Production Lưu trong GitHub Secrets: `NEON_DATABASE_URL_PRODUCTION` Hoặc trong Kubernetes: ```bash kubectl create secret generic iam-service-secrets \ --from-literal=database-url='postgresql://...' \ -n production ``` ## Migrations ### Development ```bash # Tạo migration mới ./scripts/db/migrate.sh iam-service dev # Điều này sẽ: # 1. Tạo migration file # 2. Áp dụng vào database # 3. Cập nhật Prisma Client ``` ### Staging/Production Migrations chạy tự động trong CI/CD: - Trước khi deploy lên staging - Trước khi deploy lên production (cần approval) Migration thủ công: ```bash ./scripts/db/migrate.sh iam-service deploy ``` ### Quy Trình Migration ```mermaid flowchart TD Start([ Bắt đầu
Schema thay đổi]) --> Dev[ Development
Tạo migration mới
migrate.sh dev] Dev --> Test{ Test
Migration
OK?} Test -->| Không| Fix[ Sửa lỗi
Cập nhật schema] Fix --> Dev Test -->| Có| Commit[ Commit
Migration files
+ schema.prisma] Commit --> PR[ Pull Request
Code review] PR --> CICD[ CI/CD Pipeline
Kiểm tra migration] CICD --> Staging[ Staging Branch
Auto-apply migration] Staging --> StagingTest{ Staging
Test OK?} StagingTest -->| Không| Rollback1[↩ Rollback staging] Rollback1 --> Fix StagingTest -->| Có| Approval[ Approval
Production deploy] Approval --> Prod[ Production Branch
Apply migration] Prod --> ProdTest{ Production
OK?} ProdTest -->| Không| Rollback2[ Emergency Rollback
Restore point-in-time] ProdTest -->| Có| Complete([ Hoàn thành
Migration thành công]) style Start fill:#1a1a2e,stroke:#16213e,stroke-width:2px,color:#fff style Dev fill:#0f3460,stroke:#16213e,stroke-width:2px,color:#fff style Test fill:#16213e,stroke:#0f3460,stroke-width:2px,color:#fff style Fix fill:#c72c41,stroke:#16213e,stroke-width:2px,color:#fff style Commit fill:#0f3460,stroke:#16213e,stroke-width:2px,color:#fff style PR fill:#0f3460,stroke:#16213e,stroke-width:2px,color:#fff style CICD fill:#533483,stroke:#16213e,stroke-width:2px,color:#fff style Staging fill:#533483,stroke:#16213e,stroke-width:2px,color:#fff style StagingTest fill:#16213e,stroke:#533483,stroke-width:2px,color:#fff style Rollback1 fill:#c72c41,stroke:#16213e,stroke-width:2px,color:#fff style Approval fill:#16213e,stroke:#0f3460,stroke-width:2px,color:#fff style Prod fill:#c72c41,stroke:#16213e,stroke-width:2px,color:#fff style ProdTest fill:#16213e,stroke:#c72c41,stroke-width:2px,color:#fff style Rollback2 fill:#c72c41,stroke:#16213e,stroke-width:3px,color:#fff style Complete fill:#0f3460,stroke:#16213e,stroke-width:2px,color:#fff ``` ## Backup & Restore ### Backup Tự Động Neon cung cấp backup tự động. Truy cập qua Neon Console: - Point-in-time restore - Branch restore - Export data ### Backup Thủ Công ```bash ./scripts/db/backup.sh iam-service ``` Điều này tạo file SQL dump trong thư mục `backups/`. ### Restore ```bash # Từ Neon Console (khuyến nghị) # Hoặc sử dụng psql: psql $DATABASE_URL < backup.sql ``` ## Monitoring Theo dõi databases qua Neon Console: - Connection metrics - Query performance - Storage usage - Branch status ## Xử Lý Sự Cố ### Sơ Đồ Xử Lý Sự Cố ```mermaid flowchart TD Problem([ Vấn Đề Neon
Không kết nối được?]) --> Type{Loại
Vấn Đề?} Type -->| Kết nối| ConnIssue[Vấn Đề Kết Nối] Type -->| Migration| MigIssue[Vấn Đề Migration] Type -->| Hiệu suất| PerfIssue[Vấn Đề Hiệu Suất] ConnIssue --> CheckURL{Connection
String OK?} CheckURL -->| Không| FixURL[ Kiểm tra:
• sslmode=require
• Credentials đúng
• Endpoint active] CheckURL -->| Có| CheckIP{IP trong
allowlist?} CheckIP -->| Không| AddIP[ Thêm IP vào
Neon Console] CheckIP -->| Có| CheckBranch{Branch
active?} CheckBranch -->| Không| ActivateBranch[ Kích hoạt branch
hoặc tạo mới] CheckBranch -->| Có| ContactSupport[ Liên hệ
Neon Support] MigIssue --> CheckEnv{DATABASE_URL
đã set?} CheckEnv -->| Không| SetEnv[ Export
DATABASE_URL] CheckEnv -->| Có| CheckSchema{Schema
đồng bộ?} CheckSchema -->| Không| ResetMig[ DEV ONLY:
prisma migrate reset] CheckSchema -->| Có| CheckTimeout{Connection
timeout?} CheckTimeout -->| Có| AddPooling[ Thêm
?pgbouncer=true] CheckTimeout -->| Không| CheckLimits[ Kiểm tra
Neon Console limits] PerfIssue --> HasPooling{Connection
Pooling ON?} HasPooling -->| Không| EnablePooling[ Thêm
?pgbouncer=true] HasPooling -->| Có| CheckQueries{Slow
queries?} CheckQueries -->| Có| AnalyzeQueries[ Neon Console
Query Analyzer] CheckQueries -->| Không| CheckIndexes{Indexes
tối ưu?} CheckIndexes -->| Không| AddIndexes[ Thêm indexes
vào Prisma schema] CheckIndexes -->| Có| ScalePlan[ Nâng cấp
Neon plan] FixURL --> Solved([ Đã giải quyết]) AddIP --> Solved ActivateBranch --> Solved ContactSupport --> Solved SetEnv --> Solved ResetMig --> Solved AddPooling --> Solved CheckLimits --> Solved EnablePooling --> Solved AnalyzeQueries --> Solved AddIndexes --> Solved ScalePlan --> Solved style Problem fill:#c72c41,stroke:#16213e,stroke-width:3px,color:#fff style Type fill:#16213e,stroke:#0f3460,stroke-width:2px,color:#fff style ConnIssue fill:#533483,stroke:#16213e,stroke-width:2px,color:#fff style MigIssue fill:#533483,stroke:#16213e,stroke-width:2px,color:#fff style PerfIssue fill:#533483,stroke:#16213e,stroke-width:2px,color:#fff style CheckURL fill:#16213e,stroke:#533483,stroke-width:2px,color:#fff style CheckIP fill:#16213e,stroke:#533483,stroke-width:2px,color:#fff style CheckBranch fill:#16213e,stroke:#533483,stroke-width:2px,color:#fff style CheckEnv fill:#16213e,stroke:#533483,stroke-width:2px,color:#fff style CheckSchema fill:#16213e,stroke:#533483,stroke-width:2px,color:#fff style CheckTimeout fill:#16213e,stroke:#533483,stroke-width:2px,color:#fff style HasPooling fill:#16213e,stroke:#533483,stroke-width:2px,color:#fff style CheckQueries fill:#16213e,stroke:#533483,stroke-width:2px,color:#fff style CheckIndexes fill:#16213e,stroke:#533483,stroke-width:2px,color:#fff style FixURL fill:#0f3460,stroke:#16213e,stroke-width:2px,color:#fff style AddIP fill:#0f3460,stroke:#16213e,stroke-width:2px,color:#fff style ActivateBranch fill:#0f3460,stroke:#16213e,stroke-width:2px,color:#fff style ContactSupport fill:#0f3460,stroke:#16213e,stroke-width:2px,color:#fff style SetEnv fill:#0f3460,stroke:#16213e,stroke-width:2px,color:#fff style ResetMig fill:#0f3460,stroke:#16213e,stroke-width:2px,color:#fff style AddPooling fill:#0f3460,stroke:#16213e,stroke-width:2px,color:#fff style CheckLimits fill:#0f3460,stroke:#16213e,stroke-width:2px,color:#fff style EnablePooling fill:#0f3460,stroke:#16213e,stroke-width:2px,color:#fff style AnalyzeQueries fill:#0f3460,stroke:#16213e,stroke-width:2px,color:#fff style AddIndexes fill:#0f3460,stroke:#16213e,stroke-width:2px,color:#fff style ScalePlan fill:#0f3460,stroke:#16213e,stroke-width:2px,color:#fff style Solved fill:#0f3460,stroke:#16213e,stroke-width:2px,color:#fff ``` ### Vấn Đề Kết Nối 1. **Kiểm tra định dạng connection string** - Phải bao gồm `?sslmode=require` - Xác minh credentials 2. **Kiểm tra IP allowlist** - Neon có thể giới hạn IPs - Thêm IP của bạn trong Neon Console 3. **Kiểm tra branch status** - Đảm bảo branch đang active - Kiểm tra maintenance ### Vấn Đề Migration 1. **DATABASE_URL chưa set** ```bash export DATABASE_URL="your-neon-url" ``` 2. **Schema không khớp** ```bash # Reset và migrate lại (chỉ dev!) pnpm prisma migrate reset ``` 3. **Connection timeout** - Thêm `?pgbouncer=true` cho pooling - Kiểm tra Neon console cho limits ### Vấn Đề Hiệu Suất 1. **Bật connection pooling** - Thêm `?pgbouncer=true` vào connection string 2. **Kiểm tra query performance** - Sử dụng Neon Console query analyzer - Xem lại slow queries 3. **Tối ưu indexes** - Xem lại Prisma schema - Thêm indexes cho các query thường dùng ## Tối Ưu Chi Phí - **Free tier**: 0.5 GB storage, đủ cho dev - **Staging**: Sử dụng free tier hoặc plan trả phí tối thiểu - **Production**: Scale dựa trên usage - **Branching**: Free branches cho testing ## Best Practices 1. **Luôn sử dụng connection pooling**: `?pgbouncer=true` 2. **Sử dụng SSL**: `?sslmode=require` 3. **Tách branches**: Một branch cho mỗi môi trường 4. **Backup thường xuyên**: Sử dụng automatic backups của Neon 5. **Theo dõi usage**: Kiểm tra Neon Console thường xuyên ## Quick Tips ### Mermaid Diagram Colors Tất cả Mermaid diagrams sử dụng **bảng màu tối (dark palette)** với chữ trắng: | Loại Node | Màu | Mục Đích | |-----------|-----|----------| | **Primary** | `#0f3460` | Actions, Steps, Solutions | | **Purple** | `#533483` | Staging, Categories, Warnings | | **Red** | `#c72c41` | Production, Errors, Critical | | **Dark** | `#1a1a2e` | Backgrounds, Containers | | **Darker** | `#16213e` | Decision Points, Questions | **Pattern:** ```css style NodeName fill:#0f3460,stroke:#16213e,stroke-width:2px,color:#fff ``` ### Neon Common Issues & Solutions | Vấn đề | Giải pháp nhanh | Emoji | |--------|----------------|-------| | Connection timeout | Thêm `?pgbouncer=true` | | | SSL error | Thêm `?sslmode=require` | | | IP bị chặn | Thêm IP vào Neon Console allowlist | | | Branch inactive | Kích hoạt lại trong Console | | | Migration lỗi | Reset dev: `prisma migrate reset` | | | Slow queries | Bật Query Analyzer trong Console | | | Storage đầy | Nâng cấp plan hoặc cleanup data | | ### Visual Indicators - = Neon Project - = Development - = Staging - = Production - = Performance/Speed - = Connection - = Storage/Backup - = Retry/Rollback - = Success/OK - = Error/Failed - = Critical/Emergency - = Metrics/Analytics ## Tài Nguyên - [Neon Documentation](https://neon.tech/docs) - [Neon Console](https://console.neon.tech) - [Prisma + Neon Guide](https://neon.tech/docs/guides/prisma)