AGENT SKILL

backend-database-and-orm

Guides backend database design, ORM patterns, zero-downtime migrations, and query performance tailored specifically for Neon (Serverless Postgres) and Firebase (Firestore / Auth / Rules). Use when modeling database schemas, writing ORM code, setting up database migrations, optimizing SQL/Firestore queries, or configuring connection pooling.

License 许可
MIT
最近更新
2026-11-05
Stars
★ 0
Forks
0

01 前言 Front Matter

name
backend-database-and-orm
description
Guides backend database design, ORM patterns, zero-downtime migrations, and query performance tailored specifically for Neon (Serverless Postgres) and Firebase (Firestore / Auth / Rules). Use when modeling database schemas, writing ORM code, setting up database migrations, optimizing SQL/Firestore queries, or configuring connection pooling.

03 SKILL.md 正文

Backend Database & ORM Engineering

Overview

High-performance, scalable backend database design focusing on Neon (Serverless Postgres) and Firebase (Firestore, Security Rules, Admin SDK). Enforces clean data modeling, zero-downtime schema evolution, N+1 query prevention, and safe connection pooling across serverless and stateful environments.


When to Use

  • Designing or modifying database schemas (SQL table structures, Firestore collections)
  • Writing database queries or using ORMs (Drizzle ORM, Prisma, TypeORM)
  • Configuring Neon database connections, WebSocket pooling, or database branching
  • Implementing Firebase Firestore queries, Security Rules, or Cloud Functions backend logic
  • Executing database migrations in staging or production environments
  • Diagnosing database query performance bottlenecks, slow queries, or missing indexes

Pillar 1: Neon (Serverless PostgreSQL)

Neon is a serverless Postgres platform with decoupled compute and storage, instant database branching, and HTTP/WebSocket proxies for serverless environments.

1. Connection Management & Driver Selection

  • Serverless Environments (Vercel, AWS Lambda, Cloudflare Workers): Use @neondatabase/serverless over WebSockets / HTTP proxy to avoid connection exhaustion.
    import { Pool, neonConfig } from '@neondatabase/serverless';
    import ws from 'ws';
    neonConfig.webSocketConstructor = ws;
    
    const pool = new Pool({ connectionString: process.env.DATABASE_URL });
    
  • Stateful Long-Running Servers (Node.js / Express): Use standard PostgreSQL connection poolers (e.g. pg.Pool) with Neon's pooled connection string (-pooler suffix).

2. ORM Patterns (Drizzle ORM & Prisma with Neon)

  • Drizzle ORM (Recommended for Light Overhead & Explicit SQL):
    • Always explicit select fields instead of returning SELECT *.
    • Use relational queries db.query.users.findMany(...) for structured tree fetches.
  • Prisma with Neon:
    • Enable @prisma/adapter-neon driver adapter when running in serverless contexts.
    • Avoid deeply nested include statements that cause wide SQL joins; use explicit select payloads.

3. Neon Branching Workflow for DB Migrations

  • Use Neon's instant copy-on-write branching for dev & staging test environments:
    1. Branch main database: neon branches create --name feature-branch
    2. Run migrations against feature-branch
    3. Verify application queries against feature-branch
    4. Apply approved migration to main

Pillar 2: Firebase (Firestore, Rules & Functions)

Firebase provides document-based Firestore, real-time sync, identity management, and serverless Cloud Functions.

1. Data Modeling & Firestore Layout

  • Normalized vs Denormalized: Firestore charges per document read/write. Prefer denormalizing frequently accessed sub-fields (e.g. authorName stored inside posts document) to avoid secondary fetches.
  • Collection Structures:
    • Subcollections for tightly bound sub-resources (users/{userId}/orders/{orderId}).
    • Root collections with indexed reference IDs (orders with userId field) when cross-user queries are required.

2. Firestore Security Rules & Access Control

  • Never rely solely on client-side checks. Every collection must have explicit firestore.rules.
  • Enforce strict data validation & auth checking:
    match /users/{userId} {
      allow read, write: if request.auth != null && request.auth.uid == userId;
    }
    match /posts/{postId} {
      allow read: if resource.data.isPublic == true;
      allow create: if request.auth != null && request.resource.data.authorId == request.auth.uid;
    }
    

3. Query Optimization & Indexing

  • Composite Indexes: Any query combining filtering (where) with sorting (orderBy) across multiple fields requires a composite index in firestore.indexes.json.
  • Pagination: Always use limit() combined with startAfter(lastDoc) for collection pagination. Never fetch entire collections into memory.

Pillar 3: Zero-Downtime Migration Pattern (Expand-Contract)

When changing database schemas in production (especially on Neon Postgres or Firestore schemas), NEVER drop or rename fields in a single breaking deploy. Use the Expand-Contract (Parallel Write) pattern:

Phase 1: Expand      ---> Phase 2: Dual Write  ---> Phase 3: Backfill  ---> Phase 4: Contract
(Add new col/field)       (Write to old & new)      (Migrate old rows)      (Remove old col/field)
  1. Expand (Deploy 1): Add the new column/field as optional (NULLable in SQL, optional in Firestore). Existing code continues using the old field.
  2. Dual Write (Deploy 2): Update backend code to write to BOTH old and new fields simultaneously. Read from old field if new field is missing.
  3. Backfill Script: Run an async background script to update existing rows/documents to populate the new field.
  4. Read Switch (Deploy 3): Switch read logic to strictly read from the new field.
  5. Contract (Deploy 4): Remove writes to the old field, drop the old column/field.

Pillar 4: Query Performance & Quality Checklist

  • [ ] N+1 Prevention: Are multi-row queries fetching relations in a single join / single batch query instead of looping async calls?
  • [ ] Indexing: Are all WHERE, JOIN, and ORDER BY columns in Postgres covered by B-Tree or GIN indexes? Are Firestore composite queries defined in firestore.indexes.json?
  • [ ] Transaction Boundaries: Are multi-statement updates wrapped in explicit SQL transactions (db.transaction(...)) or Firestore Batched Writes / Transactions?
  • [ ] Connection Leak Prevention: Are SQL connection pools cleanly shut down on process termination (SIGTERM)?

04 同仓库更多 Skills