Files
pos-system/docs/vi/guides/neon-database.md
Ho Ngoc Hai b441a7757a feat(docs): Enhance Vietnamese documentation with updated diagrams and troubleshooting flowcharts
- Revised the Vietnamese documentation to include clearer instructions and improved Mermaid diagrams for better visualization.
- Added detailed troubleshooting flowcharts to assist users in diagnosing issues effectively.
- Updated color palette references and visual elements in diagrams for consistency and clarity.
- Enhanced the structure of various guides, ensuring alignment between English and Vietnamese versions.
- Included quick tips and common issues sections to facilitate user navigation through the documentation.
2026-01-08 16:57:56 +07:00

14 KiB

Hướng Dẫn Neon Database

Project này sử dụng Neon PostgreSQL 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

graph TB
    subgraph NeonProject["🌐 Neon Project: goodgo-platform"]
        Main["<b>Branch: main</b><br/>🔧 Development<br/>Auto-scaling<br/>Point-in-time restore"]
        Staging["<b>Branch: staging</b><br/>🧪 Staging<br/>Created from main<br/>Pre-production testing"]
        Production["<b>Branch: production</b><br/>🚀 Production<br/>Created from main<br/>Live environment"]
    end
    
    subgraph Features["✨ Tính Năng Chính"]
        F1["⚡ Serverless<br/>No infrastructure"]
        F2["🔄 Auto-scaling<br/>Handle spikes"]
        F3["💾 Backups<br/>Point-in-time"]
        F4["🔌 Pooling<br/>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

# 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

./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

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:

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:

kubectl create secret generic iam-service-secrets \
  --from-literal=database-url='postgresql://...' \
  -n production

Migrations

Development

# 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:

./scripts/db/migrate.sh iam-service deploy

Quy Trình Migration

flowchart TD
    Start([👨‍💻 Bắt đầu<br/>Schema thay đổi]) --> Dev[📝 Development<br/>Tạo migration mới<br/>migrate.sh dev]
    Dev --> Test{✅ Test<br/>Migration<br/>OK?}
    
    Test -->|❌ Không| Fix[🔧 Sửa lỗi<br/>Cập nhật schema]
    Fix --> Dev
    
    Test -->|✅ Có| Commit[📦 Commit<br/>Migration files<br/>+ schema.prisma]
    Commit --> PR[🔀 Pull Request<br/>Code review]
    
    PR --> CICD[⚙️ CI/CD Pipeline<br/>Kiểm tra migration]
    CICD --> Staging[🧪 Staging Branch<br/>Auto-apply migration]
    
    Staging --> StagingTest{✅ Staging<br/>Test OK?}
    StagingTest -->|❌ Không| Rollback1[↩️ Rollback staging]
    Rollback1 --> Fix
    
    StagingTest -->|✅ Có| Approval[👥 Approval<br/>Production deploy]
    Approval --> Prod[🚀 Production Branch<br/>Apply migration]
    
    Prod --> ProdTest{✅ Production<br/>OK?}
    ProdTest -->|❌ Không| Rollback2[🚨 Emergency Rollback<br/>Restore point-in-time]
    ProdTest -->|✅ Có| Complete([✨ Hoàn thành<br/>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

./scripts/db/backup.sh iam-service

Điều này tạo file SQL dump trong thư mục backups/.

Restore

# 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ố

flowchart TD
    Problem([🚨 Vấn Đề Neon<br/>Không kết nối được?]) --> Type{Loại<br/>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<br/>String OK?}
    CheckURL -->|❌ Không| FixURL[✅ Kiểm tra:<br/>• sslmode=require<br/>• Credentials đúng<br/>• Endpoint active]
    CheckURL -->|✅ Có| CheckIP{IP trong<br/>allowlist?}
    CheckIP -->|❌ Không| AddIP[✅ Thêm IP vào<br/>Neon Console]
    CheckIP -->|✅ Có| CheckBranch{Branch<br/>active?}
    CheckBranch -->|❌ Không| ActivateBranch[✅ Kích hoạt branch<br/>hoặc tạo mới]
    CheckBranch -->|✅ Có| ContactSupport[📞 Liên hệ<br/>Neon Support]
    
    MigIssue --> CheckEnv{DATABASE_URL<br/>đã set?}
    CheckEnv -->|❌ Không| SetEnv[✅ Export<br/>DATABASE_URL]
    CheckEnv -->|✅ Có| CheckSchema{Schema<br/>đồng bộ?}
    CheckSchema -->|❌ Không| ResetMig[✅ DEV ONLY:<br/>prisma migrate reset]
    CheckSchema -->|✅ Có| CheckTimeout{Connection<br/>timeout?}
    CheckTimeout -->|✅ Có| AddPooling[✅ Thêm<br/>?pgbouncer=true]
    CheckTimeout -->|❌ Không| CheckLimits[✅ Kiểm tra<br/>Neon Console limits]
    
    PerfIssue --> HasPooling{Connection<br/>Pooling ON?}
    HasPooling -->|❌ Không| EnablePooling[✅ Thêm<br/>?pgbouncer=true]
    HasPooling -->|✅ Có| CheckQueries{Slow<br/>queries?}
    CheckQueries -->|✅ Có| AnalyzeQueries[✅ Neon Console<br/>Query Analyzer]
    CheckQueries -->|❌ Không| CheckIndexes{Indexes<br/>tối ưu?}
    CheckIndexes -->|❌ Không| AddIndexes[✅ Thêm indexes<br/>vào Prisma schema]
    CheckIndexes -->|✅ Có| ScalePlan[✅ Nâng cấp<br/>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

    export DATABASE_URL="your-neon-url"
    
  2. Schema không khớp

    # 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:

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