[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M79A7JQVJNGSZETJFMPHE6RN":3,"skill-same:01M79A7JQVJNGSZETJFMPHE6RN":90},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":26,"commitSha":27,"skillDirectory":28,"forksCount":14,"repositoryHtmlUrl":29,"repositoryHomepageUrl":6,"ownerHtmlUrl":30,"ownerBlogUrl":6,"ownerDescription":6,"updatedAt":31,"install":32,"resources":45},"01M79A7JQVJNGSZETJFMPHE6RN","database-sharding",null,"Database sharding for PostgreSQL\u002FMySQL with hash\u002Frange\u002Fdirectory strategies. Use for horizontal scaling, multi-tenant isolation, billions of records, or encountering wrong shard keys, hotspots, cross-shard transactions, rebalancing issues.","Elogic360\u002Fsoftware-factory","Elogic360","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F156535519?v=4","01M74NH3F0RB13PWB7JZDE2V80","elogic360","01M74NH3FPC65082MDZVMFHDM3",0,"MIT","https:\u002F\u002Fgithub.com\u002FElogic360\u002Fsoftware-factory\u002Fblob\u002Fmain\u002Fintegrations\u002Fclaude-skills-secondsky\u002Fplugins\u002Fdatabase-sharding\u002Fskills\u002Fdatabase-sharding\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"---\nname: database-sharding\ndescription: Database sharding for PostgreSQL\u002FMySQL with hash\u002Frange\u002Fdirectory strategies. Use for horizontal scaling, multi-tenant isolation, billions of records, or encountering wrong shard keys, hotspots, cross-shard transactions, rebalancing issues.\nlicense: MIT\nmetadata:\n  keywords: \"database sharding, horizontal partitioning, shard key, consistent hashing, hash sharding, range sharding, directory sharding, cross-shard queries, shard rebalancing, scatter-gather pattern, multi-tenant sharding, shard router, distributed database, database scalability, shard migration, hotspot shards, shard key selection, cross-shard aggregation, two-phase commit, saga pattern, virtual shards\"\n---\n\n# database-sharding\n\nComprehensive database sharding patterns for horizontal scaling with hash, range, and directory-based strategies.\n\n---\n\n## Quick Start (10 Minutes)\n\n**Step 1**: Choose sharding strategy from templates:\n```bash\n# Hash-based (even distribution)\ncat templates\u002Fhash-router.ts\n\n# Range-based (time-series data)\ncat templates\u002Frange-router.ts\n\n# Directory-based (multi-tenancy)\ncat templates\u002Fdirectory-router.ts\n```\n\n**Step 2**: Select shard key criteria:\n- ✅ **High cardinality** (millions of unique values)\n- ✅ **Even distribution** (no single value > 5%)\n- ✅ **Immutable** (never changes)\n- ✅ **Query alignment** (in 80%+ of WHERE clauses)\n\n**Step 3**: Implement router:\n```typescript\nimport { HashRouter } from '.\u002Fhash-router';\n\nconst router = new HashRouter([\n  { id: 'shard_0', connection: { host: 'db0.example.com' } },\n  { id: 'shard_1', connection: { host: 'db1.example.com' } },\n  { id: 'shard_2', connection: { host: 'db2.example.com' } },\n  { id: 'shard_3', connection: { host: 'db3.example.com' } },\n]);\n\n\u002F\u002F Query single shard\nconst user = await router.query('user_123', 'SELECT * FROM users WHERE id = $1', ['user_123']);\n```\n\n---\n\n## Critical Rules\n\n### ✓ Always Do\n\n| Rule | Reason |\n|------|--------|\n| **Include shard key in queries** | Avoid scanning all shards (100x slower) |\n| **Monitor shard distribution** | Detect hotspots before they cause outages |\n| **Plan for rebalancing upfront** | Cannot easily add shards later |\n| **Choose immutable shard key** | Changing key = data migration nightmare |\n| **Test distribution with production data** | Synthetic data hides real hotspots |\n| **Denormalize for data locality** | Keep related data on same shard |\n\n### ✗ Never Do\n\n| Anti-Pattern | Why It's Bad |\n|--------------|--------------|\n| **Sequential ID with range sharding** | Latest shard gets all writes (hotspot) |\n| **Timestamp as shard key** | Recent shard overwhelmed |\n| **Cross-shard transactions without 2PC** | Data corruption, inconsistency |\n| **Simple modulo without consistent hashing** | Cannot add shards without full re-shard |\n| **Nullable shard key** | Special NULL handling creates hotspots |\n| **No shard routing layer** | Hardcoded shards = cannot rebalance |\n\n---\n\n## Top 7 Critical Errors\n\n### Error 1: Wrong Shard Key Choice (Hotspots)\n**Symptom**: One shard receives 80%+ of traffic\n**Fix**:\n```typescript\n\u002F\u002F ❌ Bad: Low cardinality (status field)\nshard_key = order.status; \u002F\u002F 90% are 'pending' → shard_0 overloaded\n\n\u002F\u002F ✅ Good: High cardinality (user_id)\nshard_key = order.user_id; \u002F\u002F Millions of users, even distribution\n```\n\n### Error 2: Missing Shard Key in Queries\n**Symptom**: Queries scan ALL shards (extremely slow)\n**Fix**:\n```typescript\n\u002F\u002F ❌ Bad: No shard key\nSELECT * FROM orders WHERE status = 'shipped'; \u002F\u002F Scans all 100 shards!\n\n\u002F\u002F ✅ Good: Include shard key\nSELECT * FROM orders WHERE user_id = ? AND status = 'shipped'; \u002F\u002F Targets 1 shard\n```\n\n### Error 3: Sequential IDs with Range Sharding\n**Symptom**: Latest shard gets all writes\n**Fix**:\n```typescript\n\u002F\u002F ❌ Bad: Range sharding with auto-increment\n\u002F\u002F Shard 0: 1-1M, Shard 1: 1M-2M, Shard 2: 2M+ → All new writes to Shard 2!\n\n\u002F\u002F ✅ Good: Hash-based sharding\nconst shardId = hash(id) % shardCount; \u002F\u002F Even distribution\n```\n\n### Error 4: No Rebalancing Strategy\n**Symptom**: Stuck with initial shard count, cannot scale\n**Fix**:\n```typescript\n\u002F\u002F ❌ Bad: Simple modulo\nconst shardId = hash(key) % shardCount; \u002F\u002F Adding 5th shard breaks ALL keys\n\n\u002F\u002F ✅ Good: Consistent hashing\nconst ring = new ConsistentHashRing(shards);\nconst shardId = ring.getNode(key); \u002F\u002F Only ~25% of keys move when adding shard\n```\n\n### Error 5: Cross-Shard Transactions\n**Symptom**: Data inconsistency, partial writes\n**Fix**:\n```typescript\n\u002F\u002F ❌ Bad: Cross-shard transaction (will corrupt)\nBEGIN;\nUPDATE shard_1.accounts SET balance = balance - 100 WHERE id = 'A';\nUPDATE shard_2.accounts SET balance = balance + 100 WHERE id = 'B';\nCOMMIT; \u002F\u002F If shard_2 fails, shard_1 already committed!\n\n\u002F\u002F ✅ Good: Two-Phase Commit or Saga pattern\nconst txn = new TwoPhaseCommitTransaction();\ntxn.addOperation(shard_1, 'UPDATE accounts SET balance = balance - 100 WHERE id = ?', ['A']);\ntxn.addOperation(shard_2, 'UPDATE accounts SET balance = balance + 100 WHERE id = ?', ['B']);\nawait txn.execute(); \u002F\u002F Atomic across shards\n```\n\n### Error 6: Mutable Shard Key\n**Symptom**: Records move shards, causing duplicates\n**Fix**:\n```typescript\n\u002F\u002F ❌ Bad: Shard by country (user relocates)\nshard_key = user.country; \u002F\u002F User moves US → CA, now in different shard!\n\n\u002F\u002F ✅ Good: Shard by immutable user_id\nshard_key = user.id; \u002F\u002F Never changes\n```\n\n### Error 7: No Monitoring\n**Symptom**: Silent hotspots, sudden performance degradation\n**Fix**:\n```typescript\n\u002F\u002F ✅ Required metrics\n- Per-shard record counts (should be within 20%)\n- Query distribution (no shard > 40% of queries)\n- Storage per shard (alert at 80%)\n- Latency p99 per shard\n```\n\n**Load** `references\u002Ferror-catalog.md` for all 10 errors with detailed fixes.\n\n---\n\n## Sharding Strategies\n\n| Strategy | Best For | Pros | Cons |\n|----------|----------|------|------|\n| **Hash** | User data, even load critical | No hotspots, predictable | Range queries scatter |\n| **Range** | Time-series, logs, append-only | Range queries efficient, archival | Recent shard hotspot |\n| **Directory** | Multi-tenancy, complex routing | Flexible, easy rebalancing | Lookup overhead, SPOF |\n\n**Load** `references\u002Fsharding-strategies.md` for detailed comparisons with production examples (Instagram, Discord, Salesforce).\n\n---\n\n## Shard Key Selection Criteria\n\n| Criterion | Importance | Check Method |\n|-----------|------------|--------------|\n| **High cardinality** | Critical | `COUNT(DISTINCT shard_key)` > shard_count × 100 |\n| **Even distribution** | Critical | No value > 5% of total |\n| **Immutable** | Critical | Value never changes |\n| **Query alignment** | High | 80%+ queries include it |\n| **Data locality** | Medium | Related records together |\n\n**Decision Tree**:\n- User-focused app → `user_id`\n- Multi-tenant SaaS → `tenant_id`\n- Time-series\u002Flogs → `timestamp` (range sharding)\n- Product catalog → `product_id`\n\n**Load** `references\u002Fshard-key-selection.md` for comprehensive decision trees and testing strategies.\n\n---\n\n## Configuration Summary\n\n### Hash-Based Router\n\n```typescript\nimport { HashRouter } from '.\u002Ftemplates\u002Fhash-router';\n\nconst router = new HashRouter([\n  { id: 'shard_0', connection: { \u002F* PostgreSQL config *\u002F } },\n  { id: 'shard_1', connection: { \u002F* PostgreSQL config *\u002F } },\n]);\n\n\u002F\u002F Automatically routes to correct shard\nconst user = await router.query('user_123', 'SELECT * FROM users WHERE id = $1', ['user_123']);\n```\n\n### Range-Based Router\n\n```typescript\nimport { RangeRouter } from '.\u002Ftemplates\u002Frange-router';\n\nconst router = new RangeRouter(shardConfigs, [\n  { start: Date.parse('2024-01-01'), end: Date.parse('2024-04-01'), shardId: 'shard_q1' },\n  { start: Date.parse('2024-04-01'), end: Date.parse('2024-07-01'), shardId: 'shard_q2' },\n  { start: Date.parse('2024-07-01'), end: Infinity, shardId: 'shard_q3' },\n]);\n\n\u002F\u002F Range queries target specific shards\nconst janEvents = await router.queryRange(\n  Date.parse('2024-01-01'),\n  Date.parse('2024-02-01'),\n  'SELECT * FROM events WHERE created_at BETWEEN $1 AND $2'\n);\n```\n\n### Directory-Based Router\n\n```typescript\nimport { DirectoryRouter } from '.\u002Ftemplates\u002Fdirectory-router';\n\nconst router = new DirectoryRouter(directoryDBConfig, shardConfigs);\n\n\u002F\u002F Assign tenant to specific shard\nawait router.assignShard('tenant_acme', 'shard_enterprise');\n\n\u002F\u002F Route automatically\nconst users = await router.query('tenant_acme', 'SELECT * FROM users');\n```\n\n---\n\n## When to Load References\n\n### Choosing Strategy\n**Load** `references\u002Fsharding-strategies.md` when:\n- Deciding between hash, range, directory\n- Need production examples (Instagram, Discord)\n- Planning hybrid approaches\n\n### Selecting Shard Key\n**Load** `references\u002Fshard-key-selection.md` when:\n- Choosing shard key for new project\n- Evaluating existing shard key\n- Testing distribution with production data\n\n### Implementation\n**Load** `references\u002Fimplementation-patterns.md` when:\n- Building shard router from scratch\n- Implementing consistent hashing\n- Need transaction handling (2PC, Saga)\n- Setting up monitoring\u002Fmetrics\n\n### Cross-Shard Operations\n**Load** `references\u002Fcross-shard-queries.md` when:\n- Need to aggregate across shards (COUNT, SUM, AVG)\n- Implementing cross-shard joins\n- Building pagination across shards\n- Optimizing scatter-gather patterns\n\n### Rebalancing\n**Load** `references\u002Frebalancing-guide.md` when:\n- Adding new shards\n- Migrating data between shards\n- Planning zero-downtime migrations\n- Balancing uneven load\n\n### Error Prevention\n**Load** `references\u002Ferror-catalog.md` when:\n- Troubleshooting performance issues\n- Reviewing shard architecture\n- All 10 documented errors with fixes\n\n---\n\n## Complete Setup Checklist\n\n**Before Sharding**:\n- [ ] Tested shard key distribution with production data\n- [ ] Shard key in 80%+ of queries\n- [ ] Monitoring infrastructure ready\n- [ ] Rebalancing strategy planned\n\n**Router Implementation**:\n- [ ] Shard routing layer (not hardcoded shards)\n- [ ] Connection pooling per shard\n- [ ] Error handling and retries\n- [ ] Metrics collection (queries\u002Fshard, latency)\n\n**Shard Configuration**:\n- [ ] 4-8 shards initially (room to grow)\n- [ ] Consistent hashing or virtual shards\n- [ ] Replicas per shard (HA)\n- [ ] Backup strategy per shard\n\n**Application Changes**:\n- [ ] All queries include shard key\n- [ ] Cross-shard joins eliminated (denormalized)\n- [ ] Transaction boundaries respected\n- [ ] Connection pooling configured\n\n---\n\n## Production Example\n\n**Before** (Single database overwhelmed):\n```typescript\n\u002F\u002F Single PostgreSQL instance\nconst db = new Pool({ host: 'db.example.com' });\n\n\u002F\u002F All 10M users on one server\nconst users = await db.query('SELECT * FROM users WHERE status = $1', ['active']);\n\u002F\u002F Query time: 5000ms (slow!)\n\u002F\u002F DB CPU: 95%\n\u002F\u002F Disk: 500GB, growing\n```\n\n**After** (Sharded across 8 servers):\n```typescript\n\u002F\u002F Hash-based sharding with 8 shards\nconst router = new HashRouter([\n  { id: 'shard_0', connection: { host: 'db0.example.com' } },\n  { id: 'shard_1', connection: { host: 'db1.example.com' } },\n  \u002F\u002F ... 6 more shards\n]);\n\n\u002F\u002F Query single user (targets 1 shard)\nconst user = await router.query('user_123', 'SELECT * FROM users WHERE id = $1', ['user_123']);\n\u002F\u002F Query time: 10ms (500x faster!)\n\n\u002F\u002F Query all shards (scatter-gather)\nconst allActive = await router.queryAll('SELECT * FROM users WHERE status = $1', ['active']);\n\u002F\u002F Query time: 800ms (parallelized across 8 shards, 6x faster than single)\n\n\u002F\u002F Result: Each shard handles ~1.25M users\n\u002F\u002F DB CPU per shard: 20%\n\u002F\u002F Disk per shard: 65GB\n\u002F\u002F Can scale to 16 shards easily (consistent hashing)\n```\n\n---\n\n## Known Issues Prevention\n\nAll 10 documented errors prevented:\n1. ✅ Wrong shard key (hotspots) → Test distribution first\n2. ✅ Missing shard key in queries → Code review, linting\n3. ✅ Cross-shard transactions → Use 2PC or Saga pattern\n4. ✅ Sequential ID hotspots → Use hash-based sharding\n5. ✅ No rebalancing strategy → Consistent hashing from day 1\n6. ✅ Timestamp sharding hotspots → Hybrid hash+range approach\n7. ✅ Mutable shard key → Choose immutable keys (user_id)\n8. ✅ No routing layer → Abstract with router from start\n9. ✅ No monitoring → Track per-shard metrics\n10. ✅ Weak hash function → Use MD5, MurmurHash3, xxHash\n\n**See**: `references\u002Ferror-catalog.md` for detailed fixes\n\n---\n\n## Resources\n\n**Templates**:\n- `templates\u002Fhash-router.ts` - Hash-based sharding\n- `templates\u002Frange-router.ts` - Range-based sharding\n- `templates\u002Fdirectory-router.ts` - Directory-based sharding\n- `templates\u002Fcross-shard-aggregation.ts` - Aggregation patterns\n\n**References**:\n- `references\u002Fsharding-strategies.md` - Strategy comparison\n- `references\u002Fshard-key-selection.md` - Key selection guide\n- `references\u002Fimplementation-patterns.md` - Router implementations\n- `references\u002Fcross-shard-queries.md` - Query patterns\n- `references\u002Frebalancing-guide.md` - Migration strategies\n- `references\u002Ferror-catalog.md` - All 10 errors documented\n\n**Production Examples**:\n- Instagram: Range sharding for media\n- Discord: Hash sharding for messages\n- Salesforce: Directory sharding for orgs\n\n---\n\n**Production-tested** | **10 errors prevented** | **MIT License**\n","# database-sharding\n\nComprehensive database sharding patterns for horizontal scaling with hash, range, and directory-based strategies.\n\n---\n\n## Quick Start (10 Minutes)\n\n**Step 1**: Choose sharding strategy from templates:\n```bash\n# Hash-based (even distribution)\ncat templates\u002Fhash-router.ts\n\n# Range-based (time-series data)\ncat templates\u002Frange-router.ts\n\n# Directory-based (multi-tenancy)\ncat templates\u002Fdirectory-router.ts\n```\n\n**Step 2**: Select shard key criteria:\n- ✅ **High cardinality** (millions of unique values)\n- ✅ **Even distribution** (no single value > 5%)\n- ✅ **Immutable** (never changes)\n- ✅ **Query alignment** (in 80%+ of WHERE clauses)\n\n**Step 3**: Implement router:\n```typescript\nimport { HashRouter } from '.\u002Fhash-router';\n\nconst router = new HashRouter([\n  { id: 'shard_0', connection: { host: 'db0.example.com' } },\n  { id: 'shard_1', connection: { host: 'db1.example.com' } },\n  { id: 'shard_2', connection: { host: 'db2.example.com' } },\n  { id: 'shard_3', connection: { host: 'db3.example.com' } },\n]);\n\n\u002F\u002F Query single shard\nconst user = await router.query('user_123', 'SELECT * FROM users WHERE id = $1', ['user_123']);\n```\n\n---\n\n## Critical Rules\n\n### ✓ Always Do\n\n| Rule | Reason |\n|------|--------|\n| **Include shard key in queries** | Avoid scanning all shards (100x slower) |\n| **Monitor shard distribution** | Detect hotspots before they cause outages |\n| **Plan for rebalancing upfront** | Cannot easily add shards later |\n| **Choose immutable shard key** | Changing key = data migration nightmare |\n| **Test distribution with production data** | Synthetic data hides real hotspots |\n| **Denormalize for data locality** | Keep related data on same shard |\n\n### ✗ Never Do\n\n| Anti-Pattern | Why It's Bad |\n|--------------|--------------|\n| **Sequential ID with range sharding** | Latest shard gets all writes (hotspot) |\n| **Timestamp as shard key** | Recent shard overwhelmed |\n| **Cross-shard transactions without 2PC** | Data corruption, inconsistency |\n| **Simple modulo without consistent hashing** | Cannot add shards without full re-shard |\n| **Nullable shard key** | Special NULL handling creates hotspots |\n| **No shard routing layer** | Hardcoded shards = cannot rebalance |\n\n---\n\n## Top 7 Critical Errors\n\n### Error 1: Wrong Shard Key Choice (Hotspots)\n**Symptom**: One shard receives 80%+ of traffic\n**Fix**:\n```typescript\n\u002F\u002F ❌ Bad: Low cardinality (status field)\nshard_key = order.status; \u002F\u002F 90% are 'pending' → shard_0 overloaded\n\n\u002F\u002F ✅ Good: High cardinality (user_id)\nshard_key = order.user_id; \u002F\u002F Millions of users, even distribution\n```\n\n### Error 2: Missing Shard Key in Queries\n**Symptom**: Queries scan ALL shards (extremely slow)\n**Fix**:\n```typescript\n\u002F\u002F ❌ Bad: No shard key\nSELECT * FROM orders WHERE status = 'shipped'; \u002F\u002F Scans all 100 shards!\n\n\u002F\u002F ✅ Good: Include shard key\nSELECT * FROM orders WHERE user_id = ? AND status = 'shipped'; \u002F\u002F Targets 1 shard\n```\n\n### Error 3: Sequential IDs with Range Sharding\n**Symptom**: Latest shard gets all writes\n**Fix**:\n```typescript\n\u002F\u002F ❌ Bad: Range sharding with auto-increment\n\u002F\u002F Shard 0: 1-1M, Shard 1: 1M-2M, Shard 2: 2M+ → All new writes to Shard 2!\n\n\u002F\u002F ✅ Good: Hash-based sharding\nconst shardId = hash(id) % shardCount; \u002F\u002F Even distribution\n```\n\n### Error 4: No Rebalancing Strategy\n**Symptom**: Stuck with initial shard count, cannot scale\n**Fix**:\n```typescript\n\u002F\u002F ❌ Bad: Simple modulo\nconst shardId = hash(key) % shardCount; \u002F\u002F Adding 5th shard breaks ALL keys\n\n\u002F\u002F ✅ Good: Consistent hashing\nconst ring = new ConsistentHashRing(shards);\nconst shardId = ring.getNode(key); \u002F\u002F Only ~25% of keys move when adding shard\n```\n\n### Error 5: Cross-Shard Transactions\n**Symptom**: Data inconsistency, partial writes\n**Fix**:\n```typescript\n\u002F\u002F ❌ Bad: Cross-shard transaction (will corrupt)\nBEGIN;\nUPDATE shard_1.accounts SET balance = balance - 100 WHERE id = 'A';\nUPDATE shard_2.accounts SET balance = balance + 100 WHERE id = 'B';\nCOMMIT; \u002F\u002F If shard_2 fails, shard_1 already committed!\n\n\u002F\u002F ✅ Good: Two-Phase Commit or Saga pattern\nconst txn = new TwoPhaseCommitTransaction();\ntxn.addOperation(shard_1, 'UPDATE accounts SET balance = balance - 100 WHERE id = ?', ['A']);\ntxn.addOperation(shard_2, 'UPDATE accounts SET balance = balance + 100 WHERE id = ?', ['B']);\nawait txn.execute(); \u002F\u002F Atomic across shards\n```\n\n### Error 6: Mutable Shard Key\n**Symptom**: Records move shards, causing duplicates\n**Fix**:\n```typescript\n\u002F\u002F ❌ Bad: Shard by country (user relocates)\nshard_key = user.country; \u002F\u002F User moves US → CA, now in different shard!\n\n\u002F\u002F ✅ Good: Shard by immutable user_id\nshard_key = user.id; \u002F\u002F Never changes\n```\n\n### Error 7: No Monitoring\n**Symptom**: Silent hotspots, sudden performance degradation\n**Fix**:\n```typescript\n\u002F\u002F ✅ Required metrics\n- Per-shard record counts (should be within 20%)\n- Query distribution (no shard > 40% of queries)\n- Storage per shard (alert at 80%)\n- Latency p99 per shard\n```\n\n**Load** `references\u002Ferror-catalog.md` for all 10 errors with detailed fixes.\n\n---\n\n## Sharding Strategies\n\n| Strategy | Best For | Pros | Cons |\n|----------|----------|------|------|\n| **Hash** | User data, even load critical | No hotspots, predictable | Range queries scatter |\n| **Range** | Time-series, logs, append-only | Range queries efficient, archival | Recent shard hotspot |\n| **Directory** | Multi-tenancy, complex routing | Flexible, easy rebalancing | Lookup overhead, SPOF |\n\n**Load** `references\u002Fsharding-strategies.md` for detailed comparisons with production examples (Instagram, Discord, Salesforce).\n\n---\n\n## Shard Key Selection Criteria\n\n| Criterion | Importance | Check Method |\n|-----------|------------|--------------|\n| **High cardinality** | Critical | `COUNT(DISTINCT shard_key)` > shard_count × 100 |\n| **Even distribution** | Critical | No value > 5% of total |\n| **Immutable** | Critical | Value never changes |\n| **Query alignment** | High | 80%+ queries include it |\n| **Data locality** | Medium | Related records together |\n\n**Decision Tree**:\n- User-focused app → `user_id`\n- Multi-tenant SaaS → `tenant_id`\n- Time-series\u002Flogs → `timestamp` (range sharding)\n- Product catalog → `product_id`\n\n**Load** `references\u002Fshard-key-selection.md` for comprehensive decision trees and testing strategies.\n\n---\n\n## Configuration Summary\n\n### Hash-Based Router\n\n```typescript\nimport { HashRouter } from '.\u002Ftemplates\u002Fhash-router';\n\nconst router = new HashRouter([\n  { id: 'shard_0', connection: { \u002F* PostgreSQL config *\u002F } },\n  { id: 'shard_1', connection: { \u002F* PostgreSQL config *\u002F } },\n]);\n\n\u002F\u002F Automatically routes to correct shard\nconst user = await router.query('user_123', 'SELECT * FROM users WHERE id = $1', ['user_123']);\n```\n\n### Range-Based Router\n\n```typescript\nimport { RangeRouter } from '.\u002Ftemplates\u002Frange-router';\n\nconst router = new RangeRouter(shardConfigs, [\n  { start: Date.parse('2024-01-01'), end: Date.parse('2024-04-01'), shardId: 'shard_q1' },\n  { start: Date.parse('2024-04-01'), end: Date.parse('2024-07-01'), shardId: 'shard_q2' },\n  { start: Date.parse('2024-07-01'), end: Infinity, shardId: 'shard_q3' },\n]);\n\n\u002F\u002F Range queries target specific shards\nconst janEvents = await router.queryRange(\n  Date.parse('2024-01-01'),\n  Date.parse('2024-02-01'),\n  'SELECT * FROM events WHERE created_at BETWEEN $1 AND $2'\n);\n```\n\n### Directory-Based Router\n\n```typescript\nimport { DirectoryRouter } from '.\u002Ftemplates\u002Fdirectory-router';\n\nconst router = new DirectoryRouter(directoryDBConfig, shardConfigs);\n\n\u002F\u002F Assign tenant to specific shard\nawait router.assignShard('tenant_acme', 'shard_enterprise');\n\n\u002F\u002F Route automatically\nconst users = await router.query('tenant_acme', 'SELECT * FROM users');\n```\n\n---\n\n## When to Load References\n\n### Choosing Strategy\n**Load** `references\u002Fsharding-strategies.md` when:\n- Deciding between hash, range, directory\n- Need production examples (Instagram, Discord)\n- Planning hybrid approaches\n\n### Selecting Shard Key\n**Load** `references\u002Fshard-key-selection.md` when:\n- Choosing shard key for new project\n- Evaluating existing shard key\n- Testing distribution with production data\n\n### Implementation\n**Load** `references\u002Fimplementation-patterns.md` when:\n- Building shard router from scratch\n- Implementing consistent hashing\n- Need transaction handling (2PC, Saga)\n- Setting up monitoring\u002Fmetrics\n\n### Cross-Shard Operations\n**Load** `references\u002Fcross-shard-queries.md` when:\n- Need to aggregate across shards (COUNT, SUM, AVG)\n- Implementing cross-shard joins\n- Building pagination across shards\n- Optimizing scatter-gather patterns\n\n### Rebalancing\n**Load** `references\u002Frebalancing-guide.md` when:\n- Adding new shards\n- Migrating data between shards\n- Planning zero-downtime migrations\n- Balancing uneven load\n\n### Error Prevention\n**Load** `references\u002Ferror-catalog.md` when:\n- Troubleshooting performance issues\n- Reviewing shard architecture\n- All 10 documented errors with fixes\n\n---\n\n## Complete Setup Checklist\n\n**Before Sharding**:\n- [ ] Tested shard key distribution with production data\n- [ ] Shard key in 80%+ of queries\n- [ ] Monitoring infrastructure ready\n- [ ] Rebalancing strategy planned\n\n**Router Implementation**:\n- [ ] Shard routing layer (not hardcoded shards)\n- [ ] Connection pooling per shard\n- [ ] Error handling and retries\n- [ ] Metrics collection (queries\u002Fshard, latency)\n\n**Shard Configuration**:\n- [ ] 4-8 shards initially (room to grow)\n- [ ] Consistent hashing or virtual shards\n- [ ] Replicas per shard (HA)\n- [ ] Backup strategy per shard\n\n**Application Changes**:\n- [ ] All queries include shard key\n- [ ] Cross-shard joins eliminated (denormalized)\n- [ ] Transaction boundaries respected\n- [ ] Connection pooling configured\n\n---\n\n## Production Example\n\n**Before** (Single database overwhelmed):\n```typescript\n\u002F\u002F Single PostgreSQL instance\nconst db = new Pool({ host: 'db.example.com' });\n\n\u002F\u002F All 10M users on one server\nconst users = await db.query('SELECT * FROM users WHERE status = $1', ['active']);\n\u002F\u002F Query time: 5000ms (slow!)\n\u002F\u002F DB CPU: 95%\n\u002F\u002F Disk: 500GB, growing\n```\n\n**After** (Sharded across 8 servers):\n```typescript\n\u002F\u002F Hash-based sharding with 8 shards\nconst router = new HashRouter([\n  { id: 'shard_0', connection: { host: 'db0.example.com' } },\n  { id: 'shard_1', connection: { host: 'db1.example.com' } },\n  \u002F\u002F ... 6 more shards\n]);\n\n\u002F\u002F Query single user (targets 1 shard)\nconst user = await router.query('user_123', 'SELECT * FROM users WHERE id = $1', ['user_123']);\n\u002F\u002F Query time: 10ms (500x faster!)\n\n\u002F\u002F Query all shards (scatter-gather)\nconst allActive = await router.queryAll('SELECT * FROM users WHERE status = $1', ['active']);\n\u002F\u002F Query time: 800ms (parallelized across 8 shards, 6x faster than single)\n\n\u002F\u002F Result: Each shard handles ~1.25M users\n\u002F\u002F DB CPU per shard: 20%\n\u002F\u002F Disk per shard: 65GB\n\u002F\u002F Can scale to 16 shards easily (consistent hashing)\n```\n\n---\n\n## Known Issues Prevention\n\nAll 10 documented errors prevented:\n1. ✅ Wrong shard key (hotspots) → Test distribution first\n2. ✅ Missing shard key in queries → Code review, linting\n3. ✅ Cross-shard transactions → Use 2PC or Saga pattern\n4. ✅ Sequential ID hotspots → Use hash-based sharding\n5. ✅ No rebalancing strategy → Consistent hashing from day 1\n6. ✅ Timestamp sharding hotspots → Hybrid hash+range approach\n7. ✅ Mutable shard key → Choose immutable keys (user_id)\n8. ✅ No routing layer → Abstract with router from start\n9. ✅ No monitoring → Track per-shard metrics\n10. ✅ Weak hash function → Use MD5, MurmurHash3, xxHash\n\n**See**: `references\u002Ferror-catalog.md` for detailed fixes\n\n---\n\n## Resources\n\n**Templates**:\n- `templates\u002Fhash-router.ts` - Hash-based sharding\n- `templates\u002Frange-router.ts` - Range-based sharding\n- `templates\u002Fdirectory-router.ts` - Directory-based sharding\n- `templates\u002Fcross-shard-aggregation.ts` - Aggregation patterns\n\n**References**:\n- `references\u002Fsharding-strategies.md` - Strategy comparison\n- `references\u002Fshard-key-selection.md` - Key selection guide\n- `references\u002Fimplementation-patterns.md` - Router implementations\n- `references\u002Fcross-shard-queries.md` - Query patterns\n- `references\u002Frebalancing-guide.md` - Migration strategies\n- `references\u002Ferror-catalog.md` - All 10 errors documented\n\n**Production Examples**:\n- Instagram: Range sharding for media\n- Discord: Hash sharding for messages\n- Salesforce: Directory sharding for orgs\n\n---\n\n**Production-tested** | **10 errors prevented** | **MIT License**\n",{"name":5,"license":15,"metadata":24,"description":7},{"keywords":25},"database sharding, horizontal partitioning, shard key, consistent hashing, hash sharding, range sharding, directory sharding, cross-shard queries, shard rebalancing, scatter-gather pattern, multi-tenant sharding, shard router, distributed database, database scalability, shard migration, hotspot shards, shard key selection, cross-shard aggregation, two-phase commit, saga pattern, virtual shards","main","c475fc64e94e803b50d14a791dfee8853fbb2c5c","integrations\u002Fclaude-skills-secondsky\u002Fplugins\u002Fdatabase-sharding\u002Fskills\u002Fdatabase-sharding","https:\u002F\u002Fgithub.com\u002FElogic360\u002Fsoftware-factory","https:\u002F\u002Fgithub.com\u002FElogic360","2026-11-08 22:21:22",{"source":8,"skillName":5,"commands":33,"prompt":43,"zipAvailable":44},[34,37,40],{"tool":35,"command":36},"npx","npx skills add Elogic360\u002Fsoftware-factory --skill database-sharding",{"tool":38,"command":39},"bunx","bunx skills add Elogic360\u002Fsoftware-factory --skill database-sharding",{"tool":41,"command":42},"pnpm","pnpm dlx skills add Elogic360\u002Fsoftware-factory --skill database-sharding","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FElogic360\u002Fsoftware-factory\u002Fblob\u002Fmain\u002Fintegrations\u002Fclaude-skills-secondsky\u002Fplugins\u002Fdatabase-sharding\u002Fskills\u002Fdatabase-sharding\u002FSKILL.md",true,[46,52,56,60,64,68,72,78,82,86],{"path":47,"resourceType":48,"resourceTypeDesc":49,"sizeBytes":50,"sourceHtmlUrl":51},"references\u002Fcross-shard-queries.md","REFERENCE","参考文档",8451,"https:\u002F\u002Fgithub.com\u002FElogic360\u002Fsoftware-factory\u002Fblob\u002Fmain\u002Fintegrations\u002Fclaude-skills-secondsky\u002Fplugins\u002Fdatabase-sharding\u002Fskills\u002Fdatabase-sharding\u002Freferences\u002Fcross-shard-queries.md",{"path":53,"resourceType":48,"resourceTypeDesc":49,"sizeBytes":54,"sourceHtmlUrl":55},"references\u002Ferror-catalog.md",16134,"https:\u002F\u002Fgithub.com\u002FElogic360\u002Fsoftware-factory\u002Fblob\u002Fmain\u002Fintegrations\u002Fclaude-skills-secondsky\u002Fplugins\u002Fdatabase-sharding\u002Fskills\u002Fdatabase-sharding\u002Freferences\u002Ferror-catalog.md",{"path":57,"resourceType":48,"resourceTypeDesc":49,"sizeBytes":58,"sourceHtmlUrl":59},"references\u002Fimplementation-patterns.md",13100,"https:\u002F\u002Fgithub.com\u002FElogic360\u002Fsoftware-factory\u002Fblob\u002Fmain\u002Fintegrations\u002Fclaude-skills-secondsky\u002Fplugins\u002Fdatabase-sharding\u002Fskills\u002Fdatabase-sharding\u002Freferences\u002Fimplementation-patterns.md",{"path":61,"resourceType":48,"resourceTypeDesc":49,"sizeBytes":62,"sourceHtmlUrl":63},"references\u002Frebalancing-guide.md",8279,"https:\u002F\u002Fgithub.com\u002FElogic360\u002Fsoftware-factory\u002Fblob\u002Fmain\u002Fintegrations\u002Fclaude-skills-secondsky\u002Fplugins\u002Fdatabase-sharding\u002Fskills\u002Fdatabase-sharding\u002Freferences\u002Frebalancing-guide.md",{"path":65,"resourceType":48,"resourceTypeDesc":49,"sizeBytes":66,"sourceHtmlUrl":67},"references\u002Fshard-key-selection.md",14312,"https:\u002F\u002Fgithub.com\u002FElogic360\u002Fsoftware-factory\u002Fblob\u002Fmain\u002Fintegrations\u002Fclaude-skills-secondsky\u002Fplugins\u002Fdatabase-sharding\u002Fskills\u002Fdatabase-sharding\u002Freferences\u002Fshard-key-selection.md",{"path":69,"resourceType":48,"resourceTypeDesc":49,"sizeBytes":70,"sourceHtmlUrl":71},"references\u002Fsharding-strategies.md",13584,"https:\u002F\u002Fgithub.com\u002FElogic360\u002Fsoftware-factory\u002Fblob\u002Fmain\u002Fintegrations\u002Fclaude-skills-secondsky\u002Fplugins\u002Fdatabase-sharding\u002Fskills\u002Fdatabase-sharding\u002Freferences\u002Fsharding-strategies.md",{"path":73,"resourceType":74,"resourceTypeDesc":75,"sizeBytes":76,"sourceHtmlUrl":77},"templates\u002Fcross-shard-aggregation.ts","SCRIPT","脚本",6265,"https:\u002F\u002Fgithub.com\u002FElogic360\u002Fsoftware-factory\u002Fblob\u002Fmain\u002Fintegrations\u002Fclaude-skills-secondsky\u002Fplugins\u002Fdatabase-sharding\u002Fskills\u002Fdatabase-sharding\u002Ftemplates\u002Fcross-shard-aggregation.ts",{"path":79,"resourceType":74,"resourceTypeDesc":75,"sizeBytes":80,"sourceHtmlUrl":81},"templates\u002Fdirectory-router.ts",5015,"https:\u002F\u002Fgithub.com\u002FElogic360\u002Fsoftware-factory\u002Fblob\u002Fmain\u002Fintegrations\u002Fclaude-skills-secondsky\u002Fplugins\u002Fdatabase-sharding\u002Fskills\u002Fdatabase-sharding\u002Ftemplates\u002Fdirectory-router.ts",{"path":83,"resourceType":74,"resourceTypeDesc":75,"sizeBytes":84,"sourceHtmlUrl":85},"templates\u002Fhash-router.ts",2537,"https:\u002F\u002Fgithub.com\u002FElogic360\u002Fsoftware-factory\u002Fblob\u002Fmain\u002Fintegrations\u002Fclaude-skills-secondsky\u002Fplugins\u002Fdatabase-sharding\u002Fskills\u002Fdatabase-sharding\u002Ftemplates\u002Fhash-router.ts",{"path":87,"resourceType":74,"resourceTypeDesc":75,"sizeBytes":88,"sourceHtmlUrl":89},"templates\u002Frange-router.ts",3066,"https:\u002F\u002Fgithub.com\u002FElogic360\u002Fsoftware-factory\u002Fblob\u002Fmain\u002Fintegrations\u002Fclaude-skills-secondsky\u002Fplugins\u002Fdatabase-sharding\u002Fskills\u002Fdatabase-sharding\u002Ftemplates\u002Frange-router.ts",[91,99,106,113,120,127],{"skillNo":92,"name":93,"nameZh":6,"description":94,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":95,"licenseFileUrl":6,"sourceHtmlUrl":96,"categories":97,"keywords":98,"publishedAt":19},"01M79G206MT3J6S0GY3C45P2KV","vss-summarize-video","Use to summarize a recorded video via the LVS summarization microservice (HITL-gated) with a VLM fallback. Not for report generation or live RTSP captioning.","Apache-2.0","https:\u002F\u002Fgithub.com\u002FElogic360\u002Fsoftware-factory\u002Fblob\u002Fmain\u002Fskills\u002Fnvidia\u002Fvss-summarize-video\u002FSKILL.md",[],[],{"skillNo":100,"name":101,"nameZh":6,"description":102,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":95,"licenseFileUrl":6,"sourceHtmlUrl":103,"categories":104,"keywords":105,"publishedAt":19},"01M79G1WN63PGRE8CKD47WEBQ5","vss-setup-video-analytics-api","Use to deploy the vss-video-analytics-api REST service standalone (config-source, data-log bind, Elasticsearch, optional Kafka). Not for full warehouse deploy.","https:\u002F\u002Fgithub.com\u002FElogic360\u002Fsoftware-factory\u002Fblob\u002Fmain\u002Fskills\u002Fnvidia\u002Fvss-setup-video-analytics-api\u002FSKILL.md",[],[],{"skillNo":107,"name":108,"nameZh":6,"description":109,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":95,"licenseFileUrl":6,"sourceHtmlUrl":110,"categories":111,"keywords":112,"publishedAt":19},"01M79G1S9F7VY3EF6H53PRP5AN","vss-setup-behavior-analytics","Use to deploy the vss-behavior-analytics service standalone (entrypoint, config-source, optional calibration). Not for the full warehouse deploy.","https:\u002F\u002Fgithub.com\u002FElogic360\u002Fsoftware-factory\u002Fblob\u002Fmain\u002Fskills\u002Fnvidia\u002Fvss-setup-behavior-analytics\u002FSKILL.md",[],[],{"skillNo":114,"name":115,"nameZh":6,"description":116,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":95,"licenseFileUrl":6,"sourceHtmlUrl":117,"categories":118,"keywords":119,"publishedAt":19},"01M79G1N1S1Y27PFZPYMNK1MTQ","vss-search-archive","Use this skill to run top-level VSS fusion search on archived video, or to ingest video files \u002F RTSP streams for search. Do NOT use for ad-hoc visual Q&A (use vss-ask-video), live captioning (use vss-deploy-dense-captioning), or video summarization and reports (use vss-summarize-video).","https:\u002F\u002Fgithub.com\u002FElogic360\u002Fsoftware-factory\u002Fblob\u002Fmain\u002Fskills\u002Fnvidia\u002Fvss-search-archive\u002FSKILL.md",[],[],{"skillNo":121,"name":122,"nameZh":6,"description":123,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":95,"licenseFileUrl":6,"sourceHtmlUrl":124,"categories":125,"keywords":126,"publishedAt":19},"01M79G1H6WN0Q6C0VCAXCZX6B7","vss-query-analytics","Use this skill when reading video-analytics metrics, incidents, alerts, and sensor data via the VA-MCP server (port 9901). Not for live VLM or incident-range narrative reports.","https:\u002F\u002Fgithub.com\u002FElogic360\u002Fsoftware-factory\u002Fblob\u002Fmain\u002Fskills\u002Fnvidia\u002Fvss-query-analytics\u002FSKILL.md",[],[],{"skillNo":128,"name":129,"nameZh":6,"description":130,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":95,"licenseFileUrl":6,"sourceHtmlUrl":131,"categories":132,"keywords":133,"publishedAt":19},"01M79G1DYPNXQS7QHZ0AAF5FX5","vss-manage-video-io-storage","Use to call the VIOS REST API (sensor list, timelines, clip extraction, snapshots, add\u002Fdelete sensors and streams). Not for VLM inference or search.","https:\u002F\u002Fgithub.com\u002FElogic360\u002Fsoftware-factory\u002Fblob\u002Fmain\u002Fskills\u002Fnvidia\u002Fvss-manage-video-io-storage\u002FSKILL.md",[],[]]