backend-database-patterns
Use when the user asks about database schema design, slow queries, indexes, EXPLAIN ANALYZE, N+1 problems, transactions, keyset pagination, connection pooling…
от j4flmao★ 47 звёзд на GitHub
Установить backend-database-patterns в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Об этом скилле
Backend Database Patterns
Purpose
Design efficient, maintainable database schemas and queries. Every schema change must be backward-compatible. Every query must be verifiable with EXPLAIN ANALYZE.
Agent Protocol
Trigger
Exact user phrases: "database design", "schema design", "query optimization", "slow query", "migration", "index", "ORM pattern", "repository pattern", "N+1 problem", "transaction", "table design", "data model".
Input Context
Before activating, verify:
- The database type is known (PostgreSQL, MySQL, MongoDB, SQLite).
- The ORM or query framework is known (TypeORM, Prisma, SQLAlchemy, Diesel, GORM, Spring Data JDBC/JPA).
- The specific schema, query, or problem is described.
Output Artifact
No file output unless requested. Produces text guidance.
Response Format
Schema design:
## {entity}
| Field | Type | Constraints | Index |
|-------|------|-------------|-------|
Query fix:
## Problem: {description}
Root cause: {specific cause}
Fix: {specific change}
Verification: EXPLAIN ANALYZE {query}
Migration:
## Migration: {description}
Up: {SQL}
Down: {SQL}
Backward-compatible: {yes/no}
Completion Criteria
- Schema design follows normalization principles (3NF by default).
- Indexes are specified for every foreign key and filtered column.
- N+1 queries are identified and fixed.
- Migration includes up AND down scripts.
- Migration is verified to be backward-compatible.
- Transaction boundaries are documented.
Max Response Length
Schema: unlimited. Query fix: 6 lines. Migration: 10 lines.
Architecture Decision Tree
Normalize or Denormalize?
Is the data write-heavy with complex relationships?
├── Yes → Normalize (3NF by default)
└── No → Is there a proven read performance problem (profiled)?
├── Yes → Denormalize (with documented trade-offs)
└── No → Normalize first, optimize later
Primary Key Choice
Is the system single-node with no sharding?
├── Yes → BIGSERIAL (auto-increment)
└── No → Is time-sortable ordering needed?
├── Yes → UUID v7 (time-ordered, distributed-safe)
└── No → UUID v4 (random, distributed-safe)
Index Type Selection
Query pattern:
├── Equality lookup (WHERE x = ?) → B-tree
├── Range query (WHERE x BETWEEN ? AND ?) → B-tree
├── Multi-column filter → Composite B-tree (high-selectivity first)
├── Partial subset → Partial index (WHERE status = 'active')
├── Full-text search → GIN (tsvector)
├── JSON/array containment → GIN (jsonb, @>)
├── Geospatial query → GiST (geography, geometry)
└── All columns in query → Covering index (INCLUDE)
ORM vs Raw SQL?
What is your priority?
├── Developer productivity, CRUD-heavy → ORM (Prisma, TypeORM, SQLAlchemy)
├── Complex queries, performance-critical → Raw SQL + query builder (kysely, SQLAlchemy core)
├── Migration management → ORM migrations or standalone (Alembic, Flyway)
└── Need both → Repository pattern with ORM for 80%, raw SQL for 20%
Workflow
Step 1: Schema Design
- Normalize to 3NF by default. Denormalize only when a performance measurement proves it necessary.
- UUID v7 for primary keys (time-sortable, no collisions in distributed systems).
- Every table has: id (UUID PK), created_at (TIMESTAMPTZ), updated_at (TIMESTAMPTZ).
- Soft deletes: use deleted_at TIMESTAMPTZ or is_active boolean.
CREATE TABLE orders (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
customer_id UUID NOT NULL REFERENCES customers(id),
status order_status NOT NULL DEFAULT 'pending',
total_amount NUMERIC(10,2) NOT NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
deleted_at TIMESTAMPTZ -- soft delete
);
CREATE INDEX idx_orders_customer_id ON orders(customer_id);
CREATE INDEX idx_orders_status ON orders(status) WHERE deleted_at IS NULL;
Step 2: Indexing Strategy
| Index Type | When | Example |
|---|---|---|
| B-tree | Equality and range lookups | WHERE status = 'active' |
| Composite B-tree | Multi-column filters | WHERE status = 'active' AND created_at > '2026-01-01' |
| Partial | Filtered subset | WHERE status = 'active' on 10M rows, 90% inactive |
| Covering | All columns in query covered | Include selected columns to avoid heap lookups |
| GIN | JSON, arrays, full-text | WHERE tags @> ['urgent'] |
| Unique | Uniqueness enforcement | WHERE email IS NOT NULL |
| BRIN | Large, naturally-ordered data | Time-series data, logs |
| Hash | Equality only, large values | URL lookup (smaller than B-tree) |
Step 3: N+1 Detection and Fix
// N+1 — BAD
const users = await db.user.findMany(); // 1 query
for (const user of users) {
const posts = await db.post.findMany({ where: { userId: user.id } }); // N queries
}
// Fixed — eager loading
const users = await db.user.findMany({ include: { posts: true } }); // 1 query
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
Без ограничений — скилл может использовать любой инструмент.
Вложенные файлы
- references/connection-pooling.md
- references/database-fundamentals.md
- references/database-migration-patterns.md
- references/database-sharding.md
- references/database-testing.md
- references/migration-guide.md
- references/migration-strategies.md
- references/query-optimization.md
- references/table-design-rules.md
FAQ
Что делает скилл backend-database-patterns?
Use when the user asks about database schema design, slow queries, indexes, EXPLAIN ANALYZE, N+1 problems, transactions, keyset pagination, connection pooling or repository pattern. Produces schema, index and query fixes. Not for engine internals (use architecture-postgresql-internals) or migrations tooling (use database-migration).
Как установить скилл backend-database-patterns?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл backend-database-patterns запускает скрипты?
Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.
Похожие скиллы
frontend-design
AnthropicGuidance for distinctive, intentional visual design when building new UI or reshaping an existing one. Helps with aesthetic direction, typography, and making…
webapp-testing
AnthropicToolkit for interacting with and testing local web applications using Playwright. Supports verifying frontend functionality, debugging UI behavior, capturing…
brand-guidelines
AnthropicApplies Anthropic's official brand colors and typography to any sort of artifact that may benefit from having Anthropic's look-and-feel. Use it when brand…
web-artifacts-builder
AnthropicSuite of tools for creating elaborate, multi-component claude.ai HTML artifacts using modern frontend web technologies (React, Tailwind CSS, shadcn/ui). Use…