Architecture Database Scaling logo

Architecture Database Scaling

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

Overview

Publisherj4flmao
Repositoryagent-skills
Skill namearchitecture-database-scaling
Stars
41
Forks
6
Bundled files
Instructions only
LicenseMIT
Links
  • Markdown instructions

    A SKILL.md file the model loads on demand, so it only costs tokens when a request actually matches.

  • Works with any LLM

    AI skills are plain Markdown, not provider-specific code, so this works with GPT, Claude, Gemini, Grok, or a local model.

  • Self-contained

    Everything the model needs lives in the instructions — no extra files to sync.

  • Open source

    Published by j4flmao on GitHub. Read the source before you install it.

Installation

Install the Architecture Database Scaling AI skill in TypingMind to use it with any LLM, or drop it into another agent that reads SKILL.md.

1

Install in TypingMind

TypingMind installs a skill straight from its GitHub folder — it reads SKILL.md, bundles the resource files, and stores the result locally.

  1. Open the app and go to Plugins → Skills.
  2. Choose "Install from GitHub".
  3. Paste the skill folder URL below and confirm.
    https://github.com/j4flmao/agent-skills/tree/main/skills/architecture/databases/scaling-and-sharding
  4. Enable the skill in any chat where you want it available.
Plugins → Skills → Add skill → From GitHub URL, then paste the folder URL and press Continue.
2

Install in another agent

Any agent that reads the Agent Skills format can use this skill — copy the folder into that agent's skills directory.

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
Restart Claude Code after copying so it picks up the new skill.

Use it in TypingMind

Enable Architecture Database Scaling in any TypingMind chat and the model takes it from there. Its name and description sit in the system prompt, and the moment a request matches, the model loads the full instructions itself — you never invoke it by hand, and it costs no tokens until it is actually used.

The model loads Architecture Database Scaling on its own as soon as a request matches it.

Works with any AI model

AI skills are plain Markdown instructions rather than provider-specific code, so Architecture Database Scaling is not tied to the model it was written for. Install it once in TypingMind and use it with GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama, or a local model you run yourself — all on your own API keys.

  • Loaded only when it is needed

    The system prompt carries just the name and description. The instructions are fetched on the first matching request, so an idle skill costs nothing.

  • Switch models mid-chat

    Because the skill is instructions rather than code, changing model does not break it — the next model reads the same SKILL.md.

Skill instructions

This is the SKILL.md content the model loads. Read it before installing — a skill is instructions your model will follow.

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

Frequently asked questions

What does the Architecture Database Scaling AI skill do?

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

Why use Architecture Database Scaling on TypingMind?

Because you install it once and use it with any model. Architecture Database Scaling is plain Markdown rather than provider-specific code, so the same skill runs on GPT-5, Claude, Gemini, Grok, or a local model — and you can switch model mid-chat without it breaking. TypingMind runs on your own API keys, so you pay providers directly instead of a per-seat subscription, and your skills and chats stay in your own storage.

How do I install Architecture Database Scaling in TypingMind?

Open Plugins → Skills → Install from GitHub in TypingMind and paste https://github.com/j4flmao/agent-skills/tree/main/skills/architecture/databases/scaling-and-sharding. TypingMind reads its SKILL.md and installs it as a skill you can enable per chat.

Which AI models can use Architecture Database Scaling?

Any model you connect in TypingMind. AI skills are plain Markdown instructions rather than provider-specific code, so GPT, Claude, Gemini, Grok, and local models can all load this skill when a request matches it.

How many AI models can I use with Architecture Database Scaling?

As many as you like. As long as a model supports skills, you can use Architecture Database Scaling with it — GPT, Claude, Gemini, Grok, DeepSeek, Mistral, Llama and more — all on TypingMind with your own API keys.

Is the Architecture Database Scaling AI skill free?

Yes. It is published on GitHub by j4flmao under the MIT license. You only pay your own AI provider for the tokens you use.

What are AI skills?

An AI skill is a reusable instruction bundle that teaches an AI model how to do one specific task. It follows the open Agent Skills format: a SKILL.md file with a name and description, plus any scripts, templates or reference files the model may need. The model reads the instructions only when your request matches the skill, so an installed skill costs nothing until it is used.

How are AI skills different from plugins or MCP servers?

A plugin or MCP server gives a model new tools to call — code that runs somewhere and returns a result. An AI skill gives the model knowledge and process instead: how to approach a task, which steps to follow, what good output looks like. Skills are plain Markdown, so they need no server, no API key and no runtime, and they work with any model.

View all

Set up your own AI workspace now

Get notified about new features and future giveaways by subscribing to our newsletter 👇