NestJS Database
Data access patterns, Scaling, Migrations, and ORM selection.
Best use case
NestJS Database is best used when you need a repeatable AI agent workflow instead of a one-off prompt.
Data access patterns, Scaling, Migrations, and ORM selection.
Teams using NestJS Database should expect a more consistent output, faster repeated execution, less prompt rewriting.
When to use this skill
- You want a reusable workflow that can be run more than once with consistent structure.
When not to use this skill
- You only need a quick one-off answer and do not need a reusable workflow.
- You cannot install or maintain the underlying files, dependencies, or repository context.
Installation
Claude Code / Cursor / Codex
Manual Installation
- Download SKILL.md from GitHub
- Place it in
.claude/skills/nestjs-database/SKILL.mdinside your project - Restart your AI agent — it will auto-discover the skill
How NestJS Database Compares
| Feature / Agent | NestJS Database | Standard Approach |
|---|---|---|
| Platform Support | Not specified | Limited / Varies |
| Context Awareness | High | Baseline |
| Installation Complexity | Unknown | N/A |
Frequently Asked Questions
What does this skill do?
Data access patterns, Scaling, Migrations, and ORM selection.
Where can I find the source code?
You can find the source code on GitHub using the link provided at the top of the page.
SKILL.md Source
# NestJS Database Standards ## Selection Framework ### 1. Data Structure Analysis (The "What") - **Structured & Highly Related**: Users, Orders, Inventory, Financials. - **Choice**: **PostgreSQL** (Default). - _Why_: Strict schema validation, ACID transactions, complex generic queries (Joins). - **Unstructured / Polymorphic**: Product Catalogs (lots of unique attributes), CMS Content, Raw JSON blobs. - **Choice**: **MongoDB**. - _Why_: Schema flexibility, fast development speed for flexible data models. - **Time-Series / Metrics**: IoT Sensor Data, Stock Prices, Server Logs. - **Choice**: **TimescaleDB** (Postgres Extension). - _Why_: Compression, hypertable partitioning, rapid ingestion. ### 2. Access Pattern Analysis (The "How") - **Transactional (OLTP)**: "User buys items to cart". - **Requirement**: Strong Consistency (ACID). **SQL** is mandatory. - **Analytical (OLAP)**: "Dashboard showing sales trends". - **Requirement**: Aggregation speed. Columnar storage (ClickHouse) or Read Replicas. - **High Throughput Write**: "1M events/sec". - **Requirement**: Append-only speed. **Cassandra** / **DynamoDB** (Leaderless replication). ### 3. Decision Matrix | Feature Needed | Primary Choice | Alternative | | :--------------------- | :---------------- | :--------------------- | | General Purpose App | **PostgreSQL** | MySQL | | Flexible JSON Docs | **MongoDB** | PostgreSQL (JSONB) | | Search Engine | **ElasticSearch** | PostgreSQL (Full Text) | | Financial Transactions | **PostgreSQL** | (None) | ## Patterns - **Repository Pattern**: Isolate database logic. - **TypeORM**: Inject `@InjectRepository(Entity)`. - **Prisma**: Create a comprehensive `PrismaService`. - **Abstraction**: Services should call Repositories, not raw SQL queries. ## Configuration (TypeORM) - **Async Loading**: Always use `TypeOrmModule.forRootAsync` to load secrets from `ConfigService`. - **Sync**: Set `synchronize: false` in production; use migrations instead. ## Scaling & Production - **Read Replicas**: Configure separate `replication` connections (Master for Write, Slaves for Read) in TypeORM/Prisma to distribute load. - **Connection Multiplexing**: - **Problem**: Scaling K8s pods to 100+ exhausts DB connection limits (100 pods \* 10 connections = 1000 conns). - **Solution**: Use **PgBouncer** (Postgres) or **ProxySQL** (MySQL) in transaction mode. Do NOT rely solely on ORM pooling. - **Migrations**: - **NEVER** run `synchronize: true` in production. - **Execution**: Run migrations via a dedicated "init container" or CD job step. Do **NOT** auto-run inside the main app process on startup (race conditions when scaling to multiple pods). - **Soft Deletes**: Use `@DeleteDateColumn` (TypeORM) or middleware (Prisma) to preserve data integrity. ## Architectures (Multi-Tenancy & Sharding) - **Column-Based (SaaS Standard)**: Single DB, `tenant_id` column. - _Scale_: High. _Isolation_: Low. - _Code_: Requires Row-Level Security (RLS) policies or strict `Where` scopes. - **Schema-Based**: One DB, one Schema per Tenant. - _Scale_: Medium. _Isolation_: Medium. Good for B2B. - **Database-Based**: One DB per Tenant. - _Scale_: Low (max ~500 tenants per cluster). _Isolation_: High. - _Code_: Requires "Connection Switching" middleware. Complex. - **Horizontal Sharding**: - **Logic**: Shard massive tables by a key (e.g. `user_id`) across physical nodes to exceed single-node write limits. - **Complexity**: Extreme. Avoid until >10TB data. Use "Partitioning" first. - **Partioning (Postgres)**: - **Strategy**: Use native Table Partitioning (e.g., by range/date) for massive tables (Logs, Audit, Events). - **App Logic**: Ensure partition keys (e.g., `created_at`) are included in `WHERE` clauses to enable "Partition Pruning". ## Migrations & Data Evolution - **Separation**: - **Schema Migrations (DDL)**: Structural changes (`CREATE TABLE`, `ADD COLUMN`). Fast. Run before app deploy. - **Data Migrations (DML)**: transforming data (`UPDATE users SET name = ...`). Slow. Run as background jobs or separate scripts purely to avoid locking tables for too long. - **Zero-Downtime Field Migration (Expand-Contract Pattern)**: 1. **Expand**: Add new column `new_field` (nullable). Deploy App v1 (Writes to both `old` and `new`). 2. **Migrate**: Backfill data from `old` to `new` in batches (background script). 3. **Contract**: Deploy App v2 (Reads/Writes only `new`). Drop `old_field` in next schema migration. - **Seeding**: - **Dev**: Use factories (`@faker-js/faker`) to generate mock data. - **Prod**: Only seed static dictionaries (Roles, Countries) using "Upsert" logic to prevent duplicates. ## Best Practices 1. **Pagination**: Mandatory. Use limit/offset or cursor-based pagination. 2. **Indexing**: Define indexes in code (decorators/schema) for frequently filtered columns (`where`, `order by`). 3. **Transactions**: Use `QueryRunner` (TypeORM) or `$transaction` (Prisma) for all multi-step mutations to ensure atomicity.
Related Skills
nosql-databases
Apply NoSQL best practices for MongoDB, Convex, and document databases. Use when designing schemas, writing queries, optimizing performance, or building applications with non-relational databases. Use with database-expert for query optimization and DBA-level tuning (20+ years experience).
nestjs
Expert in implementing enterprise NestJS applications with Clean Architecture, strict TypeScript, and event-driven design. Supports Yarn build system and production-ready patterns.
nestjs-setup-guide
NestJS 프로젝트 아키텍처, 기술 스택 선택, 모듈 구조에 대한 질문이나 계획 수립 시 자동으로 가이드 제공
nestjs-expert
Nest.js framework expert specializing in module architecture, dependency injection, middleware, guards, interceptors, testing with Jest/Supertest, TypeORM/Mongoose integration, and Passport.js authentication. Use PROACTIVELY for any Nest.js application issues including architecture decisions, testing strategies, performance optimization, or debugging complex dependency injection problems. If a specialized expert is a better fit, I will recommend switching and stop.
nestjs-authentication
Use this skill whenever the user wants to design, implement, or refactor authentication and authorization in a NestJS TypeScript backend, including JWT, sessions, refresh tokens, guards, roles/permissions, and integration with modules/services/controllers.
discover-database
Automatically discover database skills when working with SQL, PostgreSQL, MongoDB, Redis, database schema design, query optimization, migrations, connection pooling, ORMs, or database selection. Activates for database design, optimization, and implementation tasks.
designing-databases
データベーススキーマ設計と最適化を支援します。正規化戦略、インデックス設計、パフォーマンス最適化を提供します。データモデル設計、データベース構造の最適化が必要な場合に使用してください。
databases
Work with MongoDB (document database, BSON documents, aggregation pipelines, Atlas cloud) and PostgreSQL (relational database, SQL queries, psql CLI, pgAdmin). Use when designing database schemas, writing queries and aggregations, optimizing indexes for performance, performing database migrations, configuring replication and sharding, implementing backup and restore strategies, managing database users and permissions, analyzing query performance, or administering production databases.
databases-architecture-skill
Master database design (SQL, NoSQL), system architecture, API design (REST, GraphQL), and building scalable systems. Learn PostgreSQL, MongoDB, system design patterns, and enterprise architectures.
database-workflow
Language-agnostic database best practices covering migrations, schema design, ORM patterns, query optimization, and testing strategies. Activate when working with database files, migrations, schema changes, SQL, ORM code, database tests, or when user mentions migrations, schema design, SQL optimization, NoSQL, database patterns, or connection pooling.
database-schema
Design a database schema
database-schema-design
Design and optimize database schemas for SQL and NoSQL databases. Use when creating new databases, designing tables, defining relationships, indexing strategies, or database migrations. Handles PostgreSQL, MySQL, MongoDB, normalization, and performance optimization.