Command Palette

Search for a command to run...

Назад к скиллам
скилл № 17168

architecture-database-scaling

Use when the user asks how to scale the database, read replicas, table partitioning, sharding, choosing a shard key, Citus, Vitess, resharding or hot…

БесплатноБез исполняемых скриптов
j4flmaoот j4flmao★ 47 звёзд на GitHub

Установить architecture-database-scaling в Claude Code и Claude Desktop

Зарегайся, чтобы установить скилл

Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.

  • Открой команду установки в одну строку
  • Сохраняй скиллы в синхронизируемую библиотеку
  • Уведомления, когда скиллы обновляются
Зарегаться бесплатноУ меня уже есть аккаунт

Об этом скилле

Database Scaling & Sharding

Purpose

Sharding is the most expensive scaling step: it complicates queries, transactions, schema changes, and operations forever. Exhaust cheaper steps first, then, if write volume or data size truly exceeds one node, pick a shard key that keeps most queries single-shard and plan resharding from day one.

Agent Protocol

Trigger

"database scaling", "sharding", "shard key", "consistent hashing", "read replica", "table partitioning", "Citus", "Vitess", "resharding", "hot shard".

Input Context

  • Current size, growth rate, read/write QPS, p99 latency, top queries.
  • Bottleneck evidence: CPU, I/O, storage, connections, lock contention.
  • Access patterns: which key most queries filter by; cross-entity queries/transactions.
  • Consistency needs (read-your-writes, cross-entity transactions).

Output Artifact

Scaling plan: next step on the ladder with evidence, or shard design (key, strategy, routing, resharding, cross-shard handling).

Response Format

Bottleneck: {resource} evidence: {metric}
Step: {index/query|vertical|cache|replicas|partitioning|sharding}
Shard key: {column} (cardinality, distribution, query coverage {x}%)
Strategy: {hash|range|directory|geo}  Routing: {app lib|proxy (Vitess/Citus)}
Cross-shard: {fan-out|denormalize|saga}  Resharding: {virtual buckets → move}

Completion Criteria

  • Bottleneck proven with metrics before choosing a step.
  • Shard key covers the dominant queries and distributes load evenly.
  • Resharding approach defined (logical buckets, online move).
  • Cross-shard queries and transactions explicitly handled.

The Scaling Ladder

Step Fixes Cost
1. Query + index tuning Most "DB is slow" cases Low
2. Connection pooling (PgBouncer, RDS Proxy) Connection exhaustion Low
3. Vertical scaling CPU/RAM/IOPS limits Money; has a ceiling
4. Caching (cache-aside) Read-heavy hot keys Invalidation complexity
5. Read replicas Read throughput Replication lag: stale reads
6. Partitioning (single node) Huge tables, retention (drop old partitions) Partition key in queries
7. Functional split Separate DBs per domain/service Cross-domain joins move to app
8. Horizontal sharding Write throughput, data beyond one node High, permanent

Read replicas: route reads that tolerate lag; for read-your-writes, read from the primary for a short window after a user's write or wait for the replica LSN.

Sharding Strategies

Strategy How Pros Cons
Hash bucket = hash(key) mod B → bucket-to-shard map Even distribution Range scans hit all shards
Range Key ranges per shard Range queries efficient Hotspots on monotonic keys (time, sequential ids)
Directory Lookup table key → shard Flexible moves, tenant placement Lookup service is critical path
Geo By region Data residency, latency Uneven sizes

Never map keys directly with hash(key) % N_servers: changing N remaps almost every key. Use a fixed, large number of logical buckets (e.g. 1024-4096) mapped to physical shards, consistent hashing with virtual nodes, or rendezvous/jump hashing.

Consistent Hashing with Virtual Nodes

from __future__ import annotations

import bisect
import hashlib


def _h(value: str) -> int:
    return int.from_bytes(hashlib.sha256(value.encode()).digest()[:8], "big")


class HashRing:
    """Adding/removing a node moves only ~1/N of keys. Virtual nodes smooth the distribution."""

    def __init__(self, nodes: list[str], vnodes: int = 200) -> None:
        if not nodes:
            raise ValueError("HashRing needs at least one node")
        self.vnodes = vnodes
        self._ring: list[tuple[int, str]] = []
        for node in nodes:
            self.add(node)

    def add(self, node: str) -> None:
        for i in range(self.vnodes):
            bisect.insort(self._ring, (_h(f"{node}#{i}"), node))

    def remove(self, node: str) -> None:
        self._ring = [(h, n) for h, n in self._ring if n != node]
        if not self._ring:
            raise ValueError(f"removing {node} left the ring empty")

    def node_for(self, key: str) -> str:
        idx = bisect.bisect(self._ring, (_h(key), "")) % len(self._ring)
        return self._ring[idx][1]

Choosing a Shard Key

  1. Query coverage: the key appears in the WHERE clause of most hot queries (tenant_id, user_id, account_id).
  2. Cardinality and distribution: many distinct values, no single value dominating (watch "whale" tenants; give them dedicated shards via a directory).
  3. Transaction locality: entities updated together share the key (co-locate orders with their customer).
  4. Not monotonic for range strategies (avoid raw timestamps or sequential ids as range keys).
  5. Stable: a row whose key changes must move between shards; pick a key that never changes.

Cross-Shard Operations

Need Approach
Q
Полный SKILL.md на GitHub

Разрешённые инструменты

Инструменты, которые скиллу разрешено вызывать.

Без ограничений — скилл может использовать любой инструмент.

Вложенные файлы

  • references/merged-system-design-database-sharding.md

FAQ

Что делает скилл architecture-database-scaling?

Use when the user asks how to scale the database, read replicas, table partitioning, sharding, choosing a shard key, Citus, Vitess, resharding or hot partitions. Produces a scaling ladder plan, shard key and routing design. Not for PostgreSQL engine internals (use architecture-postgresql-internals) or NoSQL selection (use data-nosql-database).

Как установить скилл architecture-database-scaling?

Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.

Скилл architecture-database-scaling запускает скрипты?

Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.

Похожие скиллы

Сравнить architecture-database-scaling с