database-designer
alirezarezvani/claude-skills
전문가의 분석과 자동화 도구를 활용하여 데이터베이스 스키마를 설계하고, 데이터 마이그레이션을 계획하며, 쿼리를 최적화하고, 데이터 관계를 모델링합니다.
...모든 것을 확장하십시오데이터베이스 설계자 - 강력한 계층별 기술
개요
최신 데이터베이스 시스템을 위한 전문가 수준의 분석, 최적화 및 마이그레이션 역량을 제공하는 포괄적인 데이터베이스 설계 기술입니다. 이 기술은 이론적 원리와 실무 도구를 결합하여 아키텍트와 개발자가 확장성이 뛰어나고 성능이 우수하며 유지보수가 용이한 데이터베이스 스키마를 구축할 수 있도록 지원합니다.
핵심 역량
스키마 설계 및 분석
- 정규화 분석: 정규화 수준(1NF부터 BCNF까지)의 자동 탐지
- 비정규화 전략: 성능 최적화를 위한 스마트한 권장 사항
- 데이터형 최적화: 부적절한 데이터형 및 크기 문제 식별
- 제약 조건 분석: 누락된 외래 키, 고유 제약 조건 및 NULL 검사
- 명명 규칙 검증: 일관된 테이블 및 열 명명 패턴
- ERD 생성: DDL을 기반으로 한 Mermaid 다이어그램 자동 생성
인덱스 최적화
- 인덱스 격차 분석: 외래 키 및 쿼리 패턴에 대한 누락된 인덱스 식별
- 복합 인덱스 전략: 다중 열 인덱스를 위한 최적의 열 순서 지정
- 인덱스 중복 감지: 중복 및 미사용 인덱스 제거
- 성능 영향 모델링: 선택도 추정 및 쿼리 비용 분석
- 인덱스 유형 선택: B-트리, 해시, 부분, 커버링 및 특수 인덱스
마이그레이션 관리
- 다운타임 없는 마이그레이션: 확장-축소 패턴 구현
- 스키마 진화: 안전한 열 추가, 삭제 및 유형 변경
- 데이터 마이그레이션 스크립트: 자동화된 데이터 변환 및 유효성 검사
- 롤백 전략: 유효성 검증을 통한 완전한 롤백 기능
- 실행 계획: 종속성 해결을 통한 순차적 마이그레이션 단계
도구 워크플로우 (이 스크립트를 실행하십시오 — 스키마를 수동으로 분석하지 마십시오)
모든 경로는 이 스킬 폴더를 기준으로 하며, 샘플 입력은 assets/.
1. 스키마 분석
python3 schema_analyzer.py --input schema.sql --generate-erd --output-format json -o analysis.json
SQL DDL 또는 JSON 스키마를 지원합니다 (assets/sample_schema.sql / sample_schema.json). 출력 결과에는 정규화 분석 결과, 누락된 제약 조건, 명명 규칙 문제 및 Mermaid ERD가 포함됩니다. 최적화 전에 사용자에게 ERD를 표시하고 표시된 문제를 수정하십시오.
2. 실제 쿼리 패턴에 맞춰 인덱스 최적화
python3 index_optimizer.py --schema assets/sample_schema.json --queries assets/sample_query_patterns.json --analyze-existing --format json -o indexes.json
먼저 사용자의 자주 실행되는 쿼리를 쿼리 패턴 JSON 파일에 기록합니다(복사 assets/sample_query_patterns.json). 출력 결과로는 우선순위 순으로 정렬된 CREATE INDEX 권장 사항 목록과 중복 인덱스 제거 목록이 제공됩니다.
3. 마이그레이션 생성
python3 migration_generator.py --current current_schema.json --target target_schema.json --zero-downtime --format sql -o migration.sql
--zero-downtime 확장-축소 계획을 생성하며; --validate-only SQL을 생성하지 않고 실행 가능성을 확인합니다.
4. 검증 루프
대상 스키마에서 1단계를 다시 실행하고, 첫 번째 실행에서 발견된 문제가 해결되었는지 확인한 후; migration_generator.py --validate-only 마이그레이션을 인계하기 전에 실행합니다.
데이터베이스 설계 원칙
→ 자세한 내용은 references/database-design-reference.md를 참조하십시오
모범 사례
스키마 설계
- 의미 있는 이름 사용: 명확하고 일관된 명명 규칙
- 적절한 데이터 유형 선택: 저장 효율을 위한 적절한 크기의 열
- 적절한 제약 조건 정의: 외래 키, 체크 제약 조건, 고유 인덱스
- 향후 확장을 고려하십시오: 초기 단계부터 확장성을 고려한 설계
- 관계 문서화: 명확한 외래 키 관계 및 비즈니스 규칙
성능 최적화
- 전략적인 인덱스 생성: 과도한 인덱싱 없이 일반적인 쿼리 패턴을 포괄
- 쿼리 성능 모니터링: 느린 쿼리에 대한 정기적인 분석
- 대용량 테이블을 파티션화하십시오: 쿼리 성능과 유지 관리를 개선하십시오
- 적절한 격리 수준 사용: 일관성과 성능의 균형 유지
- 연결 풀링 구현: 효율적인 리소스 활용
보안 고려 사항
- 최소 권한 원칙: 필요한 최소한의 권한만 부여
- 민감한 데이터 암호화: 저장 시 및 전송 중
- 액세스 패턴 감사: 데이터베이스 액세스를 모니터링하고 기록하십시오
- 입력값 검증: SQL 인젝션 공격 방지
- 정기적인 보안 업데이트: 데이터베이스 소프트웨어를 최신 상태로 유지
쿼리 생성 패턴
JOIN이 포함된 SELECT
-- INNER JOIN: only matching rows
SELECT o.id, c.name, o.total
FROM orders o
INNER JOIN customers c ON c.id = o.customer_id;
-- LEFT JOIN: all left rows, NULLs for non-matches
SELECT c.name, COUNT(o.id) AS order_count
FROM customers c
LEFT JOIN orders o ON o.customer_id = c.id
GROUP BY c.name;
-- Self-join: hierarchical data (employees/managers)
SELECT e.name AS employee, m.name AS manager
FROM employees e
LEFT JOIN employees m ON m.id = e.manager_id;
공통 테이블 표현식(CTE)
-- Recursive CTE for org chart
WITH RECURSIVE org AS (
SELECT id, name, manager_id, 1 AS depth
FROM employees WHERE manager_id IS NULL
UNION ALL
SELECT e.id, e.name, e.manager_id, o.depth + 1
FROM employees e INNER JOIN org o ON o.id = e.manager_id
)
SELECT * FROM org ORDER BY depth, name;
윈도우 함수
-- ROW_NUMBER for pagination / dedup
SELECT *, ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY created_at DESC) AS rn
FROM orders;
-- RANK with gaps, DENSE_RANK without gaps
SELECT name, score, RANK() OVER (ORDER BY score DESC) AS rank FROM leaderboard;
-- LAG/LEAD for comparing adjacent rows
SELECT date, revenue,
revenue - LAG(revenue) OVER (ORDER BY date) AS daily_change
FROM daily_sales;
집계 패턴
-- FILTER clause (PostgreSQL) for conditional aggregation
SELECT
COUNT(*) AS total,
COUNT(*) FILTER (WHERE status = 'active') AS active,
AVG(amount) FILTER (WHERE amount > 0) AS avg_positive
FROM accounts;
-- GROUPING SETS for multi-level rollups
SELECT region, product, SUM(revenue)
FROM sales
GROUP BY GROUPING SETS ((region, product), (region), ());
마이그레이션 패턴
상향/하향 마이그레이션 스크립트
모든 마이그레이션에는 되돌릴 수 있는 대응 과정이 있어야 합니다. 정렬을 위해 파일 이름에 타임스탬프 접두사를 붙이세요:
migrations/
├── 20260101_000001_create_users.up.sql
├── 20260101_000001_create_users.down.sql
├── 20260115_000002_add_users_email_index.up.sql
└── 20260115_000002_add_users_email_index.down.sql
다운타임 없는 마이그레이션 (확장/축소)
실행 중인 코드의 잠금이나 오류를 방지하려면 확장-축소 패턴을 사용하십시오:
- 확장 — 새 열/테이블 추가 (NULL 허용, 기본값 지정)
- 데이터 마이그레이션 — 일괄 처리 방식으로 데이터 채우기; 애플리케이션에서 이중 쓰기 수행
- 전환 — 애플리케이션이 새 컬럼에서 데이터를 읽도록 하고, 기존 컬럼에 대한 쓰기를 중지
- 축소 — 후속 마이그레이션에서 기존 열 삭제
데이터 백필 전략
-- Batch update to avoid long-running locks
UPDATE users SET email_normalized = LOWER(email)
WHERE id IN (SELECT id FROM users WHERE email_normalized IS NULL LIMIT 5000);
-- Repeat in a loop until 0 rows affected
롤백 절차
- 항상
down.sql스테이징 환경에서 항상 테스트한 후up.sql프로덕션에 배포하기 전에 - 롤백 기간을 짧게 유지하십시오 — 계약 단계가 이미 실행된 경우, 롤백을 수행하려면 새로운 순방향 마이그레이션이 필요합니다
- 되돌릴 수 없는 변경(데이터가 포함된 열 삭제)의 경우, 먼저 논리적 백업을 수행하십시오
성능 최적화
인덱싱 전략
| 인덱스 유형 | 사용 사례 | 예 |
|---|---|---|
| B-트리 (기본값) | 동일성, 범위, ORDER BY | CREATE INDEX idx_users_email ON users(email); |
| GIN | 전체 텍스트 검색, JSONB, 배열 | CREATE INDEX idx_docs_body ON docs USING gin(to_tsvector('english', body)); |
| GiST | 기하형, 범위형, 최인접 이웃 | CREATE INDEX idx_locations ON places USING gist(coords); |
| 부분 | 행의 부분 집합 (크기 축소) | CREATE INDEX idx_active ON users(email) WHERE active = true; |
| 커버링 | 인덱스 전용 스캔 | CREATE INDEX idx_cov ON orders(customer_id) INCLUDE (total, created_at); |
EXPLAIN 실행 계획 읽기
EXPLAIN (ANALYZE, BUFFERS, FORMAT TEXT) SELECT ...;
주목해야 할 주요 신호:
- 대용량 테이블에 대한 순차 스캔 — 인덱스 누락
- 행 수 추정치가 높은 중첩 루프(Nested Loop) — 해시/병합 조인(hash/merge join)을 고려하거나 인덱스를 추가
- 버퍼 공유 읽기 횟수가 히트 횟수보다 훨씬 높은 경우 — 작업 집합이 메모리 용량을 초과함
N+1 쿼리 탐지
증상: 애플리케이션이 행당 하나의 쿼리를 발행함(예: 루프 내에서 관련 레코드 가져오기).
해결 방법:
- 단일 왕복으로 데이터를 가져올 수 있는
JOIN또는 서브쿼리를 사용하여 한 번의 왕복으로 데이터를 가져옵니다 - ORM 이거 로딩 (
select_related/includes/with) - GraphQL 리졸버용 DataLoader 패턴
연결 풀링
| 도구 | 프로토콜 | 가장 적합한 용도 |
|---|---|---|
| PgBouncer | PostgreSQL | 트랜잭션/문 풀링, 낮은 오버헤드 |
| ProxySQL | MySQL | 쿼리 라우팅, 읽기/쓰기 분할 |
| 내장 풀 (HikariCP, SQLAlchemy 풀) | 모든 | 애플리케이션 수준 풀링 |
일반적인 지침: 풀 크기를 (2 * CPU cores) + disk spindles로 설정하십시오. 클라우드 SSD의 경우 2 * vCPUs 로 시작하여 조정하십시오.
읽기 복제본 및 쿼리 라우팅
- 모든
SELECT쿼리는 모두 복제본으로 라우팅하고, 쓰기 작업은 주 노드로 라우팅하십시오 - 복제 지연 시간을 고려하십시오(일반적으로 비동기 방식의 경우 <1초, 동기 방식의 경우 0).
- 다음
pg_last_wal_replay_lsn()중요한 데이터를 읽기 전에 지연을 감지하기 위해
다중 데이터베이스 의사 결정 매트릭스
| 기준 | PostgreSQL | MySQL | SQLite | SQL Server |
|---|---|---|---|---|
| 가장 적합한 용도 | 복잡한 쿼리, JSONB, 확장 기능 | 웹 앱, 읽기 위주의 워크로드 | 임베디드, 개발/테스트, 엣지 | 엔터프라이즈 .NET 스택 |
| JSON 지원 | 탁월함 (JSONB + GIN) | 양호 (JSON 유형) | 최소 | 양호 (OPENJSON) |
| 복제 | 스트리밍, 논리적 | 그룹 복제, InnoDB 클러스터 | 해당 없음 | Always On AG |
| 라이선스 | 오픈 소스 (PostgreSQL 라이선스) | 오픈 소스(GPL) / 상용 | 퍼블릭 도메인 | 상용 |
| 실질적 최대 크기 | 수 TB | 수 TB | ~1 TB (단일 작성자) | 수 TB |
선택 시점:
- PostgreSQL — 신규 프로젝트의 기본 선택지; 최고의 확장성 및 표준 준수
- MySQL — 기존 MySQL 생태계; 읽기 위주의 간단한 웹 애플리케이션
- SQLite — 모바일 앱, CLI 도구, 단위 테스트 데이터베이스, IoT/엣지
- SQL Server — 기업 정책에 의해 의무화된 경우; .NET/Azure와의 긴밀한 통합
NoSQL 고려 사항
| 데이터베이스 | 모델 | 사용 시점 |
|---|---|---|
| MongoDB | 문서 | 스키마 유연성, 신속한 프로토타이핑, 콘텐츠 관리 |
| Redis | 키-값 / 캐시 | 세션 저장소, 속도 제한, 리더보드, 퍼블/서브 |
| DynamoDB | 와이드 컬럼 | 서버리스 AWS 애플리케이션, 어떤 규모에서도 1자리 수 밀리초(ms) 수준의 지연 시간 |
기본적으로 SQL을 사용합니다. 액세스 패턴이 NoSQL을 통해 명확한 이점을 얻을 수 있는 경우에만 NoSQL을 활용하십시오.
샤딩 및 복제
수평 분할 대 수직 분할
- 수직 분할: 열을 여러 테이블에 분산합니다(예: BLOB 열 분리). 좁은 범위의 쿼리에 대한 I/O를 줄여줍니다.
- 수평 파티셔닝(샤딩): 행을 여러 데이터베이스/서버에 분산합니다. 단일 노드로는 데이터 세트를 모두 수용하거나 처리량을 감당할 수 없을 때 필요합니다.
샤딩 전략
| 전략 | 작동 원리 | 장점 | 단점 |
|---|---|---|---|
| 해시 | shard = hash(key) % N |
균등한 분산 | 리샤딩 비용이 많이 듦 |
| 범위 | 날짜 또는 ID 범위에 따른 샤딩 | 간단하며, 시계열 데이터에 적합 | 최신 샤드에 핫스팟 발생 |
| 지리적 | 사용자 지역별 샤드 분할 | 데이터 지역성, 규정 준수 | 지역 간 쿼리 처리가 어렵습니다 |
복제 패턴
| 패턴 | 일관성 | 지연 시간 | 사용 사례 |
|---|---|---|---|
| 동기식 | 강력한 | 더 높은 쓰기 지연 시간 | 금융 거래 |
| 비동기식 | 최종 | 낮은 쓰기 지연 시간 | 읽기 위주의 웹 앱 |
| 반동기식 | 최소 하나의 복제본 확인 | 보통 | 안전성과 속도의 균형 |
관련 항목
- sql-database-assistant — 일상적인 SQL 작업을 위한 쿼리 작성, 최적화 및 디버깅
- database-schema-designer — ERD 모델링, 정규화 분석 및 스키마 생성
- migration-architect — 데이터베이스 엔진 간 대규모 마이그레이션 계획 또는 주요 스키마 대대적 개편
- senior-backend — 애플리케이션 계층 패턴 (커넥션 풀링, ORM 모범 사례)
- senior-devops — 데이터베이스 클러스터 및 복제본을 위한 인프라 프로비저닝
---
name: database-designer
description: Design database schemas, plan data migrations, optimize queries, and model data relationships using expert analysis and automated tools.
---
# Database Designer - POWERFUL Tier Skill
## Overview
A comprehensive database design skill that provides expert-level analysis, optimization, and migration capabilities for modern database systems. This skill combines theoretical principles with practical tools to help architects and developers create scalable, performant, and maintainable database schemas.
## Core Competencies
### Schema Design & Analysis
- **Normalization Analysis**: Automated detection of normalization levels (1NF through BCNF)
- **Denormalization Strategy**: Smart recommendations for performance optimization
- **Data Type Optimization**: Identification of inappropriate types and size issues
- **Constraint Analysis**: Missing foreign keys, unique constraints, and null checks
- **Naming Convention Validation**: Consistent table and column naming patterns
- **ERD Generation**: Automatic Mermaid diagram creation from DDL
### Index Optimization
- **Index Gap Analysis**: Identification of missing indexes on foreign keys and query patterns
- **Composite Index Strategy**: Optimal column ordering for multi-column indexes
- **Index Redundancy Detection**: Elimination of overlapping and unused indexes
- **Performance Impact Modeling**: Selectivity estimation and query cost analysis
- **Index Type Selection**: B-tree, hash, partial, covering, and specialized indexes
### Migration Management
- **Zero-Downtime Migrations**: Expand-contract pattern implementation
- **Schema Evolution**: Safe column additions, deletions, and type changes
- **Data Migration Scripts**: Automated data transformation and validation
- **Rollback Strategy**: Complete reversal capabilities with validation
- **Execution Planning**: Ordered migration steps with dependency resolution
## Tool Workflow (run these — do not analyze schemas by hand)
All paths relative to this skill folder; sample inputs in `assets/`.
### 1. Analyze the schema
```bash
python3 schema_analyzer.py --input schema.sql --generate-erd --output-format json -o analysis.json
```
Accepts SQL DDL or JSON schema (`assets/sample_schema.sql` / `sample_schema.json`). Output includes normalization findings, missing constraints, naming issues, and a Mermaid ERD — show the ERD to the user and fix flagged issues before optimizing.
### 2. Optimize indexes against real query patterns
```bash
python3 index_optimizer.py --schema assets/sample_schema.json --queries assets/sample_query_patterns.json --analyze-existing --format json -o indexes.json
```
Write the user's hot queries into a query-patterns JSON first (copy `assets/sample_query_patterns.json`). Output is a priority-ordered list of CREATE INDEX recommendations plus redundant-index removals.
### 3. Generate the migration
```bash
python3 migration_generator.py --current current_schema.json --target target_schema.json --zero-downtime --format sql -o migration.sql
```
`--zero-downtime` emits an expand-contract plan; `--validate-only` checks feasibility without generating SQL.
### 4. Verification loop
Re-run step 1 on the *target* schema and assert the issues found in the first pass are gone; run `migration_generator.py --validate-only` before handing over the migration.
## Database Design Principles
→ See references/database-design-reference.md for details
## Best Practices
### Schema Design
1. **Use meaningful names**: Clear, consistent naming conventions
2. **Choose appropriate data types**: Right-sized columns for storage efficiency
3. **Define proper constraints**: Foreign keys, check constraints, unique indexes
4. **Consider future growth**: Plan for scale from the beginning
5. **Document relationships**: Clear foreign key relationships and business rules
### Performance Optimization
1. **Index strategically**: Cover common query patterns without over-indexing
2. **Monitor query performance**: Regular analysis of slow queries
3. **Partition large tables**: Improve query performance and maintenance
4. **Use appropriate isolation levels**: Balance consistency with performance
5. **Implement connection pooling**: Efficient resource utilization
### Security Considerations
1. **Principle of least privilege**: Grant minimal necessary permissions
2. **Encrypt sensitive data**: At rest and in transit
3. **Audit access patterns**: Monitor and log database access
4. **Validate inputs**: Prevent SQL injection attacks
5. **Regular security updates**: Keep database software current
## Query Generation Patterns
### SELECT with JOINs
```sql
-- INNER JOIN: only matching rows
SELECT o.id, c.name, o.total
FROM orders o
INNER JOIN customers c ON c.id = o.customer_id;
-- LEFT JOIN: all left rows, NULLs for non-matches
SELECT c.name, COUNT(o.id) AS order_count
FROM customers c
LEFT JOIN orders o ON o.customer_id = c.id
GROUP BY c.name;
-- Self-join: hierarchical data (employees/managers)
SELECT e.name AS employee, m.name AS manager
FROM employees e
LEFT JOIN employees m ON m.id = e.manager_id;
```
### Common Table Expressions (CTEs)
```sql
-- Recursive CTE for org chart
WITH RECURSIVE org AS (
SELECT id, name, manager_id, 1 AS depth
FROM employees WHERE manager_id IS NULL
UNION ALL
SELECT e.id, e.name, e.manager_id, o.depth + 1
FROM employees e INNER JOIN org o ON o.id = e.manager_id
)
SELECT * FROM org ORDER BY depth, name;
```
### Window Functions
```sql
-- ROW_NUMBER for pagination / dedup
SELECT *, ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY created_at DESC) AS rn
FROM orders;
-- RANK with gaps, DENSE_RANK without gaps
SELECT name, score, RANK() OVER (ORDER BY score DESC) AS rank FROM leaderboard;
-- LAG/LEAD for comparing adjacent rows
SELECT date, revenue,
revenue - LAG(revenue) OVER (ORDER BY date) AS daily_change
FROM daily_sales;
```
### Aggregation Patterns
```sql
-- FILTER clause (PostgreSQL) for conditional aggregation
SELECT
COUNT(*) AS total,
COUNT(*) FILTER (WHERE status = 'active') AS active,
AVG(amount) FILTER (WHERE amount > 0) AS avg_positive
FROM accounts;
-- GROUPING SETS for multi-level rollups
SELECT region, product, SUM(revenue)
FROM sales
GROUP BY GROUPING SETS ((region, product), (region), ());
```
---
## Migration Patterns
### Up/Down Migration Scripts
Every migration must have a reversible counterpart. Name files with a timestamp prefix for ordering:
```
migrations/
├── 20260101_000001_create_users.up.sql
├── 20260101_000001_create_users.down.sql
├── 20260115_000002_add_users_email_index.up.sql
└── 20260115_000002_add_users_email_index.down.sql
```
### Zero-Downtime Migrations (Expand/Contract)
Use the expand-contract pattern to avoid locking or breaking running code:
1. **Expand** — add the new column/table (nullable, with default)
2. **Migrate data** — backfill in batches; dual-write from application
3. **Transition** — application reads from new column; stop writing to old
4. **Contract** — drop old column in a follow-up migration
### Data Backfill Strategies
```sql
-- Batch update to avoid long-running locks
UPDATE users SET email_normalized = LOWER(email)
WHERE id IN (SELECT id FROM users WHERE email_normalized IS NULL LIMIT 5000);
-- Repeat in a loop until 0 rows affected
```
### Rollback Procedures
- Always test the `down.sql` in staging before deploying `up.sql` to production
- Keep rollback window short — if the contract step has run, rollback requires a new forward migration
- For irreversible changes (dropping columns with data), take a logical backup first
---
## Performance Optimization
### Indexing Strategies
| Index Type | Use Case | Example |
|------------|----------|---------|
| **B-tree** (default) | Equality, range, ORDER BY | `CREATE INDEX idx_users_email ON users(email);` |
| **GIN** | Full-text search, JSONB, arrays | `CREATE INDEX idx_docs_body ON docs USING gin(to_tsvector('english', body));` |
| **GiST** | Geometry, range types, nearest-neighbor | `CREATE INDEX idx_locations ON places USING gist(coords);` |
| **Partial** | Subset of rows (reduce size) | `CREATE INDEX idx_active ON users(email) WHERE active = true;` |
| **Covering** | Index-only scans | `CREATE INDEX idx_cov ON orders(customer_id) INCLUDE (total, created_at);` |
### EXPLAIN Plan Reading
```sql
EXPLAIN (ANALYZE, BUFFERS, FORMAT TEXT) SELECT ...;
```
Key signals to watch:
- **Seq Scan** on large tables — missing index
- **Nested Loop** with high row estimates — consider hash/merge join or add index
- **Buffers shared read** much higher than **hit** — working set exceeds memory
### N+1 Query Detection
Symptoms: application issues one query per row (e.g., fetching related records in a loop).
Fixes:
- Use `JOIN` or subquery to fetch in one round-trip
- ORM eager loading (`select_related` / `includes` / `with`)
- DataLoader pattern for GraphQL resolvers
### Connection Pooling
| Tool | Protocol | Best For |
|------|----------|----------|
| **PgBouncer** | PostgreSQL | Transaction/statement pooling, low overhead |
| **ProxySQL** | MySQL | Query routing, read/write splitting |
| **Built-in pool** (HikariCP, SQLAlchemy pool) | Any | Application-level pooling |
**Rule of thumb:** Set pool size to `(2 * CPU cores) + disk spindles`. For cloud SSDs, start with `2 * vCPUs` and tune.
### Read Replicas and Query Routing
- Route all `SELECT` queries to replicas; writes to primary
- Account for replication lag (typically <1s for async, 0 for sync)
- Use `pg_last_wal_replay_lsn()` to detect lag before reading critical data
---
## Multi-Database Decision Matrix
| Criteria | PostgreSQL | MySQL | SQLite | SQL Server |
|----------|-----------|-------|--------|------------|
| **Best for** | Complex queries, JSONB, extensions | Web apps, read-heavy workloads | Embedded, dev/test, edge | Enterprise .NET stacks |
| **JSON support** | Excellent (JSONB + GIN) | Good (JSON type) | Minimal | Good (OPENJSON) |
| **Replication** | Streaming, logical | Group replication, InnoDB cluster | N/A | Always On AG |
| **Licensing** | Open source (PostgreSQL License) | Open source (GPL) / commercial | Public domain | Commercial |
| **Max practical size** | Multi-TB | Multi-TB | ~1 TB (single-writer) | Multi-TB |
**When to choose:**
- **PostgreSQL** — default choice for new projects; best extensibility and standards compliance
- **MySQL** — existing MySQL ecosystem; simple read-heavy web applications
- **SQLite** — mobile apps, CLI tools, unit test databases, IoT/edge
- **SQL Server** — mandated by enterprise policy; deep .NET/Azure integration
### NoSQL Considerations
| Database | Model | Use When |
|----------|-------|----------|
| **MongoDB** | Document | Schema flexibility, rapid prototyping, content management |
| **Redis** | Key-value / cache | Session store, rate limiting, leaderboards, pub/sub |
| **DynamoDB** | Wide-column | Serverless AWS apps, single-digit-ms latency at any scale |
> Use SQL as default. Reach for NoSQL only when the access pattern clearly benefits from it.
---
## Sharding & Replication
### Horizontal vs Vertical Partitioning
- **Vertical partitioning**: Split columns across tables (e.g., separate BLOB columns). Reduces I/O for narrow queries.
- **Horizontal partitioning (sharding)**: Split rows across databases/servers. Required when a single node cannot hold the dataset or handle the throughput.
### Sharding Strategies
| Strategy | How It Works | Pros | Cons |
|----------|-------------|------|------|
| **Hash** | `shard = hash(key) % N` | Even distribution | Resharding is expensive |
| **Range** | Shard by date or ID range | Simple, good for time-series | Hot spots on latest shard |
| **Geographic** | Shard by user region | Data locality, compliance | Cross-region queries are hard |
### Replication Patterns
| Pattern | Consistency | Latency | Use Case |
|---------|------------|---------|----------|
| **Synchronous** | Strong | Higher write latency | Financial transactions |
| **Asynchronous** | Eventual | Low write latency | Read-heavy web apps |
| **Semi-synchronous** | At-least-one replica confirmed | Moderate | Balance of safety and speed |
---
## Cross-References
- **sql-database-assistant** — query writing, optimization, and debugging for day-to-day SQL work
- **database-schema-designer** — ERD modeling, normalization analysis, and schema generation
- **migration-architect** — large-scale migration planning across database engines or major schema overhauls
- **senior-backend** — application-layer patterns (connection pooling, ORM best practices)
- **senior-devops** — infrastructure provisioning for database clusters and replicas
모든 파일
0개 파일database-designer 설치
스킬 파일을 다운로드하여 .claude/skills/ 디렉터리에 압축을 풀어주세요.
ZIP 다운로드저장소를 클론하고 스킬 파일을 프로젝트에 복사하세요.
git clone https://github.com/alirezarezvani/claude-skills/tree/main/engineering/skills/database-designer # Copy SKILL.md to your .claude/skills/ directory
복사





집
