Logo: Architecture Database Scaling

Architecture Database Scaling

Communautéit
j4flmao
architecture-database-scaling

Use this skill when the user says 'scale the database', 'sharding', 'shard key', 'consistent hashing', 'read replicas', 'partitioning', 'Citus', 'Vitess', 'resharding', 'hot partition'. Walks the scaling ladder from query/index fixes through vertical scaling, caching, read replicas, and partitioning to horizontal sharding, and designs shard keys, routing, and resharding. Do NOT use for: PostgreSQL engine internals (architecture/databases/postgresql-internals), algorithm-level sharding theory drills (system-design/database-sharding), or NoSQL product selection (data/nosql-database).

Iwwersiicht

Editeurj4flmao
Repositoryagent-skills
Skill-Nummarchitecture-database-scaling
Stären
41
Forks
6
Matgeliwwert Dateien
Nëmmen Instruktiounen
LizenzMIT
Linken
  • Instruktiounen am Markdown-Format

    Eng SKILL.md-Datei, déi de Modell bei Bedarf luet, soudatt nëmmen Token ufalen, wann eng Ufro tatsächlech dozou passt.

  • Funktionéiert mat all LLM

    KI-Skills si reng Markdown, keen ubidderspezifesche Code. Dofir funktionéiert dëse Skill mat GPT, Claude, Gemini, Grok oder engem lokale Modell.

  • Alles an den Instruktiounen

    Alles, wat de Modell brauch, steet an den Instruktiounen — keng zousätzlech Dateien ze synchroniséieren.

  • Open Source

    j4flmao huet de Skill op GitHub verëffentlecht. Liest de Quelltext, ier Dir de Skill installéiert.

Installatioun

Installéiert de KI-Skill Architecture Database Scaling an TypingMind, fir e mat all LLM ze benotzen, oder setzt en an en anere KI-Agent an, deen SKILL.md liest.

1

An TypingMind installéieren

TypingMind installéiert e Skill direkt aus sengem GitHub-Dossier — dobäi gëtt SKILL.md gelies, d'Ressourcedateie gi gebëndelt an d'Resultat gëtt lokal gespäichert.

  1. Maacht d'App op a gitt op Plugins → Skills.
  2. Wielt „Vu GitHub installéieren“.
  3. Pecht d'URL vum Skill-Dossier, déi hei drënner steet, an a bestätegt d'Installatioun.
    https://github.com/j4flmao/agent-skills/tree/main/skills/architecture/databases/scaling-and-sharding
  4. Aktivéiert de Skill an all Chat, an deem Dir e benotze wëllt.
Plugins → Skills → Skill derbäisetzen → Iwwer eng GitHub-URL. Pecht dann d'URL vum Dossier an a klickt op Weider.
2

An engem anere KI-Agent installéieren

All KI-Agent, deen d'Format Agent Skills liest, kann dëse Skill benotzen — kopéiert den Dossier an d'Skill-Verzeechnes vun deem KI-Agent.

Claude Code — .claude/skills
git clone --depth 1 https://github.com/j4flmao/agent-skills.git /tmp/agent-skills
mkdir -p .claude/skills
cp -r /tmp/agent-skills/skills/architecture/databases/scaling-and-sharding .claude/skills/architecture-database-scaling
Start Claude Code nom Kopéieren nei, fir datt den neie Skill erkannt gëtt.

An TypingMind benotzen

Aktivéiert Architecture Database Scaling an engem Chat vun TypingMind, an de Modell iwwerhëlt de Rescht. Den Numm an d'Beschreiwung stinn am System-Prompt. Soubal eng Ufro dozou passt, luet de Modell déi komplett Instruktioune selwer — Dir musst de Skill ni manuell opruffen, an et fale keng Token un, bis en tatsächlech benotzt gëtt.

De Modell luet Architecture Database Scaling automatesch, soubal eng Ufro dozou passt.

Funktionéiert mat all KI-Modell

KI-Skills si reng Markdown-Instruktiounen amplaz vun ubidderspezifeschem Code. Dofir ass Architecture Database Scaling net un de Modell gebonnen, fir deen de Skill geschriwwe gouf. Installéiert en eemol an TypingMind a benotzt e mat GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama oder engem lokale Modell, deen Dir selwer bedreift — alles mat Ären eegenen API-Schlësselen.

  • Gëtt nëmme gelueden, wann et néideg ass

    De System-Prompt enthält nëmmen den Numm an d'Beschreiwung. D'Instruktioune gi bei der éischter passender Ufro gelueden, soudatt en onbenotzte Skill näischt kascht.

  • De Modell am lafende Chat wiesselen

    Well de Skill aus Instruktiounen amplaz vu Code besteet, funktionéiert en och no engem Modellwiessel — den nächste Modell liest déi selwecht SKILL.md-Datei.

Skill-Instruktiounen

Dëst ass den Inhalt vu SKILL.md, deen de Modell luet. Liest e virun der Installatioun — e Skill besteet aus Instruktiounen, déi Äre Modell befollegt.

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

StepFixesCost
1. Query + index tuningMost "DB is slow" casesLow
2. Connection pooling (PgBouncer, RDS Proxy)Connection exhaustionLow
3. Vertical scalingCPU/RAM/IOPS limitsMoney; has a ceiling
4. Caching (cache-aside)Read-heavy hot keysInvalidation complexity
5. Read replicasRead throughputReplication lag: stale reads
6. Partitioning (single node)Huge tables, retention (drop old partitions)Partition key in queries
7. Functional splitSeparate DBs per domain/serviceCross-domain joins move to app
8. Horizontal shardingWrite throughput, data beyond one nodeHigh, 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

StrategyHowProsCons
Hashbucket = hash(key) mod B → bucket-to-shard mapEven distributionRange scans hit all shards
RangeKey ranges per shardRange queries efficientHotspots on monotonic keys (time, sequential ids)
DirectoryLookup table key → shardFlexible moves, tenant placementLookup service is critical path
GeoBy regionData residency, latencyUneven 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

python
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).

Cross-Shard Operations

NeedApproach
Query across shardsScatter-gather with limits/timeouts; better: a separate read model (search index, warehouse) fed by CDC
Global uniqueness (email)Dedicated lookup table/service, or unique constraint in a global table
Multi-shard transactionAvoid by key design; otherwise saga with compensation; 2PC only within systems that support it well
Global IDsUUIDv7, ULID, or Snowflake-style ids (not per-shard sequences)
Reference dataReplicate small tables to all shards (Citus reference tables)

Tools

ToolModel
Citus (PostgreSQL extension)Distributed tables by distribution column, co-location, reference tables
Vitess (MySQL)VSchema with vindexes, online resharding, query routing via vtgate
Native partitioning (PostgreSQL)PARTITION BY RANGE/LIST/HASH within one node
Distributed SQL (CockroachDB, YugabyteDB, Spanner, TiDB)Automatic range sharding + distributed transactions; higher per-query latency
sql
-- PostgreSQL range partitioning for retention, single node
CREATE TABLE events (
  id         BIGINT GENERATED ALWAYS AS IDENTITY,
  tenant_id  BIGINT NOT NULL,
  created_at TIMESTAMPTZ NOT NULL,
  payload    JSONB NOT NULL,
  PRIMARY KEY (id, created_at)          -- PK must include the partition key
) PARTITION BY RANGE (created_at);
CREATE TABLE events_2026_10 PARTITION OF events
  FOR VALUES FROM ('2026-10-01') TO ('2026-11-01');

-- Citus: distribute by tenant and co-locate related tables
SELECT create_distributed_table('orders', 'tenant_id');
SELECT create_distributed_table('order_items', 'tenant_id', colocate_with => 'orders');

Resharding

  1. Shard by logical buckets from the start so moves are bucket-granular.
  2. Copy bucket data to the new shard (snapshot + CDC catch-up).
  3. Verify counts/checksums; briefly block writes for the bucket or use dual-write with idempotency.
  4. Flip the routing map; keep the old copy read-only until verified; then delete.

Anti-Patterns

  • Sharding before fixing indexes, queries, and pooling.
  • Shard key absent from most queries → every request fans out.
  • Modulo-by-server-count routing.
  • Per-shard auto-increment ids leaking into global identity.
  • Cross-shard joins in the request path.

Checklist

  • Bottleneck evidence and cheaper steps exhausted.
  • Shard key analysis with query coverage and skew numbers.
  • Logical buckets + routing layer; resharding runbook tested.
  • Global ids, uniqueness, and cross-shard reads designed.
  • Per-shard monitoring (size, QPS, p99, replication lag).
  • Backups and restores per shard and point-in-time consistent where needed.

References

  • Karger et al., "Consistent Hashing and Random Trees" (STOC 1997); Lamping & Veach, "A Fast, Minimal Memory, Consistent Hash Algorithm" (jump hash, 2014).
  • Kleppmann, "Designing Data-Intensive Applications", ch. 5-6.
  • Citus and Vitess documentation (distribution columns, vindexes, resharding).

Heefeg gestallte Froen

Wat mécht de KI-Skill Architecture Database Scaling?

Use this skill when the user says 'scale the database', 'sharding', 'shard key', 'consistent hashing', 'read replicas', 'partitioning', 'Citus', 'Vitess', 'resharding', 'hot partition'. Walks the scaling ladder from query/index fixes through vertical scaling, caching, read replicas, and partitioning to horizontal sharding, and designs shard keys, routing, and resharding. Do NOT use for: PostgreSQL engine internals (architecture/databases/postgresql-internals), algorithm-level sharding theory drills (system-design/database-sharding), or NoSQL product selection (data/nosql-database).

Firwat Architecture Database Scaling op TypingMind benotzen?

Well Dir en eemol installéiert a mat all Modell benotze kënnt. Architecture Database Scaling besteet aus einfachem Markdown amplaz vun ubidderspezifeschem Code. Dee selwechte Skill funktionéiert also mat GPT-5, Claude, Gemini, Grok oder engem lokale Modell – an Dir kënnt de Modell matzen am Chat wiesselen, ouni datt de Skill ophält ze funktionéieren. TypingMind benotzt Är eegen API-Schlësselen, sou datt Dir d'Ubidder direkt bezuelt, amplaz en Abonnement pro Benotzerplaz ze bezuelen. Är Skills a Chats bleiwen an Ärem eegene Späicher.

Wéi installéieren ech Architecture Database Scaling an TypingMind?

Maacht an TypingMind Plugins → Skills → Vu GitHub installéieren op a setzt https://github.com/j4flmao/agent-skills/tree/main/skills/architecture/databases/scaling-and-sharding an. TypingMind liest d'Datei SKILL.md an installéiert de Skill, deen Dir pro Chat aktivéiere kënnt.

Wéi eng KI-Modeller kënnen Architecture Database Scaling benotzen?

All Modell, deen Dir an TypingMind verbënnt. KI-Skills sinn einfach Markdown-Instruktiounen an net ubidderspezifesche Code. Dofir kënne GPT, Claude, Gemini, Grok a lokal Modeller dëse Skill lueden, wann eng Ufro dozou passt.

Wéi vill KI-Modeller kann ech mat Architecture Database Scaling benotzen?

Esou vill wéi Dir wëllt. Soulaang e Modell Skills ënnerstëtzt, kënnt Dir Architecture Database Scaling domat benotzen – zum Beispill mat GPT, Claude, Gemini, Grok, DeepSeek, Mistral oder Llama – alles op TypingMind mat Ären eegenen API-Schlësselen.

Ass de KI-Skill Architecture Database Scaling gratis?

Jo. j4flmao huet de Skill ënner der Lizenz MIT op GitHub publizéiert. Dir bezuelt nëmmen Ären eegene KI-Ubidder fir d'Token, déi Dir benotzt.

Wat si KI-Skills?

E KI-Skill ass e weiderverwendbare Pak vun Instruktiounen, deen engem KI-Modell bäibréngt, wéi en eng bestëmmt Aufgab erfëllt. E follegt dem oppenen Agent Skills-Format: eng Datei SKILL.md mat engem Numm an enger Beschreiwung, plus all Scripten, Virlagen oder Referenzdateien, déi de Modell eventuell brauch. De Modell liest d'Instruktiounen eréischt, wann Är Ufro zum Skill passt. En installéierte Skill kascht also näischt, bis e benotzt gëtt.

Wéi ënnerscheede sech KI-Skills vu Plugins oder MCP-Serveren?

E Plugin oder MCP-Server gëtt engem Modell nei Tools, déi en opruffe kann – Code, deen iergendwou leeft an e Resultat zeréckgëtt. E KI-Skill gëtt dem Modell dogéint Wëssen an eng Virgoensweis: wéi en eng Aufgab ugeet, wéi eng Schrëtt e maache soll a wéi eng gutt Ausgab ausgesäit. Skills bestinn aus einfachem Markdown, brauche kee Server, keen API-Schlëssel a kee Lafzäitëmfeld a funktionéiere mat all Modell.

Alleguer weisen

Elo Ären eegene KI-Aarbechtsberäich ariichten

Abonnéiert Iech op eisen Newsletter, fir iwwer nei Funktiounen an zukünfteg Gewënnspiller informéiert ze ginn 👇