/claude-kit:distributed-systems-patternsfrom Claude Kit SDLC
Designs and reviews distributed data placement, replication, and storage engine choices. Covers consistent hashing, sharding, quorums, gossip failure detection, and B-tree vs LSM engines.
Ships in Claude Kit SDLC. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
Read when SKILL.md points to them.
Design and review distributed data tiers — how keys find nodes, how data survives node loss, how consistency is tuned per workload, and what storage engine each node runs under the hood.
Scope boundary — this skill owns data placement and replication mechanics. Adjacent territory is owned elsewhere:
.claude/rules/resilience-engineering.md (always loaded) — sections below point there instead of restating it.system-design-patterns skill.redis-caching-patterns; single-node transactions and locking belong to python-dao-and-database.Know why the obvious scheme fails before replacing it. hash(key) mod N routes a key to one of N nodes with no lookup table and no coordination — every client computes the owner independently, in constant time. Its hidden assumption is that N never changes. It is acceptable only when membership is genuinely fixed or remapping is free (stateless routing).
The mod-N reshuffle is a cluster wipe. The moment a node joins or dies, the modulo arithmetic reassigns roughly (N−1)/N of all keys — almost the entire keyspace changes owner in one instant. For a cache tier that is equivalent to flushing the cluster: every request misses simultaneously and falls through to the database, and the resulting cold-cache stampede can cascade into a full outage. Any placement scheme that bakes the cluster size into the hash turns node failure — an inevitable event — into a remap-everything event. Design for membership churn as a normal operation, not an exception.
The ring. Consistent hashing maps servers and keys into the same circular hash space (conceptually 0 to 2^32−1, wrapping around). Each server hashes an identifier (hostname/IP/ID) to a ring position; each key hashes to its own position; a key's owner is the first server encountered walking clockwise.
0/2^32
|
S3 ---+--- k1 → owner: S1 (first server clockwise)
/ \
k4 S1
| |
S2 ------ k3 ---- k2 → owner: S2
(k3 → owner: S2)
Implement lookup as a sorted array (or balanced tree) of server positions plus a binary search for the first position ≥ hash(key), wrapping to the smallest position past the top — O(log N) per lookup, no central directory.
Bounded key movement is the whole point. Adding a server claims only the arc between it and its counterclockwise predecessor; removing a server hands its arc to the next clockwise node. With K keys on N servers, a membership change moves roughly K/N keys — every other node is untouched. Compare that to the near-total remap of mod-N: this property is what makes scale-out and failure recovery routine operations instead of incidents.
The basic ring has three predictable defects. Server positions come from hashing a handful of names, so with few points on the circle:
These are geometric consequences of placing few points on a ring, not rare edge cases.
Virtual nodes fix all three. Place each physical server on the ring many times by hashing derived identifiers (node-a#1, node-a#2, …); 100–200 vnodes per physical machine is a common operating point. Each machine then owns many small scattered arcs whose sizes average out:
Tune the vnode count, don't max it. The ring's position index grows by the vnode multiplier — more entries to binary-search and more membership metadata to keep in sync across the cluster. That is why vnode counts are an operating point to tune, not a number to crank arbitrarily high.
Where the pattern shows up. Cassandra's token ring (vnodes included) and DynamoDB's partitioning are direct implementations; CDNs route requests to edge nodes this way with no central lookup table; load balancers use it so sticky sessions survive backend scale-up/down with only the affected arcs remapping. The progression mod-N → basic ring → vnodes is worth internalizing as a method: each design is adequate until scale breaks one of its assumptions, and the successor targets exactly that failure mode.
Climb the scaling ladder in order — sharding is the last rung. A single primary with good indexes and query discipline carries far more traffic than intuition suggests. Exhaust the cheaper rungs first:
| Rung | Move | What it buys |
|---|---|---|
| 1 | Optimize the single node | Indexes, query shape, pooling — often 10× for free |
| 2 | Cache the hot read set | Absorbs the read multiplier before it reaches the DB |
| 3 | Add read replicas | Horizontal read scale; primary handles writes only |
| 4 | Scale vertically | A bigger box is operationally free vs resharding |
| 5 | Shard | Only when write volume or working set exceeds all of the above |
The classic era of URL shorteners and early social platforms served enormous traffic for years on rungs 2–3 alone. Sharding buys write scale at the permanent price of losing cross-shard transactions and joins, complicating every operational procedure, and making key-distribution mistakes expensive — take that deal only when forced.
Read replicas: the workhorse of rung 3. One primary handles all mutations; asynchronous replication fans data out to replicas that serve selects, search, reporting, and analytics. Read-heavy products (feeds, profiles, content platforms, public APIs) scale a long way on this rung. Two costs come with it: replication lag means read-your-writes is not guaranteed (see point 5), and primary failover/promotion is the operationally hard part — rehearse it before you rely on it.
Three ways to split, with distinct failure modes:
| Scheme | How | Strength | Weakness |
|---|---|---|---|
| Hash | Route by hash of partition key | Even key spread | Destroys range scans; adjacent keys scatter |
| Range | Each shard owns a contiguous key range | Cheap range scans, ordered access | Sequential keys hammer the tail shard |
| Directory | Lookup service maps key → shard | Surgical placement and rebalancing | One more critical, consistent, HA component on every request path |
Hash sharding should be combined with consistent hashing so membership churn moves only ~1/N of keys. Range sharding on timestamps or auto-increment IDs aims every insert at the newest shard — a hot partition by construction. Directory sharding is the flexible option for tenant-level placement, but the directory's availability now bounds the whole tier's availability.
Hot partitions come from key choice, not bad luck. A celebrity user, a monotonic key, or a coarse partition key (partition-by-country puts one populous country on one shard) concentrates traffic while other shards idle. Defenses:
Replication lag is a product decision, not a footnote. With async replicas, a user can write to the primary and immediately read stale data from a replica — the "my edit disappeared" bug. Route lag-sensitive reads (a user reading back their own just-written data) to the primary, or to a replica whose reported replication position has passed the client's write; let analytics and search tolerate staleness on any replica. Name the guarantee explicitly ("your own writes are visible immediately; others' writes within X seconds") instead of letting it emerge by accident.
Materialized views are a read-scaling lever that often postpones sharding. When the read bottleneck is an expensive aggregation (dashboards, reports, recommendation summaries) rather than raw row lookups, precompute the query result into its own table and serve reads from that. Three refresh strategies, by staleness budget:
The trade is explicit staleness plus refresh orchestration in exchange for reads that no longer touch the expensive query path. A creator dashboard aggregating views and watch-time periodically — instead of live per page load — is the canonical shape.
Know the cross-shard atomicity cost before you shard. Once related rows live on different shards, "both updates apply or neither" needs a protocol. Two-phase commit is the classic one: a coordinator asks every participant to prepare (validate, lock resources, vote), and only a unanimous yes triggers the global commit — any no triggers global rollback. It delivers real atomicity, and its costs are exactly why modern systems avoid it: participants sit blocked holding locks while the protocol runs, the coordinator is both a bottleneck and a single point of failure, latency stacks with participant count, and partial-failure recovery is genuinely messy. Reserve 2PC for the narrow cases where partial success is unacceptable (the debit-and-credit pair of a funds transfer); prefer sagas, event-driven flows, and compensating transactions everywhere else — and let this cost push you back up the scaling ladder: data that transacts together should live on one shard in the first place.
Replicate at write time, not at failure time. Copying data after a machine dies is a recovery scramble racing the next failure. Instead, every write is sent to the key's primary owner plus its replicas at the moment it happens — a replication factor of 3 (one primary, two replicas) is the standard production setting, so losing the primary leaves two live copies and no emergency. The cost is 3× storage and write fan-out, paid deliberately for durability and read availability during failures.
Choose a topology: leader-follower or leaderless.
N/W/R — the consistency knob, tuned per workload. In a quorum system: N is the replica count, W how many replicas must acknowledge a write, R how many are consulted on a read. When W + R > N, every read set overlaps every write set in at least one replica, so a read is guaranteed to see the latest acknowledged write — read-your-writes by arithmetic, no timestamps involved.
N=3, W=2, R=2:
replicas: [R1] [R2] [R3]
write set: {R1, R2} — acked by 2 of 3
read set: {R2, R3} — queries 2 of 3
overlap: R2 — guaranteed, because 2+2 > 3
| Workload | Setting (N=3) | Leaning |
|---|---|---|
| Funds transfer, inventory decrement | W=3, R=2 (or W=2, R=2) | Consistency — overlap guaranteed |
| Like counter, view counter, presence | W=1, R=1 | Availability/latency — staleness tolerated |
| Balanced default | W=2, R=2 | Overlap, with tolerance for one slow node |
Match the knobs to the data's actual correctness requirement, not one global mode. The engineering skill is recognizing that the funds transfer and the like counter in the same system deserve different settings. Which side of the partition trade-off a workload should sit on — and the vocabulary for making that call (CAP, PACELC) — is owned by .claude/rules/resilience-engineering.md; this section supplies the mechanism that implements the choice, not the decision framework.
Raising W costs write latency; raising R costs read latency. W=N means every write waits for the slowest replica and fails if any replica is down; W=1 acknowledges after one copy and risks serving a stale read from the others unless R compensates. Reads can hedge: query R replicas in parallel and take the first valid quorum of answers, so one slow replica doesn't set the latency floor.
Lag-aware read routing for async topologies. Quorum overlap covers the leaderless path; leader-follower systems with async followers instead need routing discipline: session-sticky reads to the leader after a recent write, or followers that report replication position so the router can exclude any replica behind the client's last write. Either mechanism turns "eventual" into a named, testable guarantee.
Consensus is what sits underneath leader election — use one, never build one. Leader-follower replication begs a question the topology itself cannot answer: who is the leader, especially while the old one may still be alive? Consensus protocols (the Raft/Paxos family) answer it with three interlocked mechanisms — elect a leader by majority vote, replicate every operation into a log, commit an entry only once a majority acknowledges it — so every replica applies the same operations in the same order: the single-copy illusion, held even through leader crashes and partitions, because a majority can exist on at most one side. That strength has a narrow home:
The Dynamo/Cassandra lineage combines the pieces above into a standard machine. Knowing the anatomy lets you evaluate any store's documentation quickly — each mechanism exists to answer one specific failure.
Coordinator and preference list. Any node can accept a request; the receiving node acts as coordinator, hashes the key, and forwards the operation to the key's preference list — the first N distinct physical nodes encountered clockwise on the ring (skipping vnodes that map back to an already-listed machine). There is no central router in the data path.
External coordination service for cluster metadata. The ring mapping, replication factor, quorum settings, and membership list live in a small dedicated coordination service that all nodes watch for changes. Failure information discovered by gossip feeds back into it so coordinators stop routing to dead nodes. The trade-off is explicit: a consistent source of truth for cluster config, at the price of operating one more critical system.
Hinted handoff — write availability through short outages. If a preference-list node is down at write time, the coordinator writes that copy to the next healthy node with a hint naming the intended owner. When the owner returns, the hint-holder hands the data over and deletes its copy. Writes stay available through transient failures without silently reducing the replica count.
Read repair — healing staleness on the read path. When a quorum read fans out to R replicas and the responses disagree, the coordinator returns the newest version to the client and, in the background, writes that version back to the stale replicas. Frequently read data converges automatically, with no separate process.
Anti-entropy with Merkle trees — healing staleness nobody reads. Read repair only fixes what gets read. A background anti-entropy process periodically compares replicas' key ranges using Merkle trees (hash trees over the data): if two replicas' root hashes match, the entire range is identical and the comparison cost one hash exchange; if they differ, descend only into the differing subtrees to locate and sync divergent keys. This makes continuous full-replica comparison affordable.
Conflict resolution — vector clocks, or last-write-wins with eyes open. Wall-clock timestamps cannot order writes across machines — clocks drift; the distributed-time correctness rules live in .claude/rules/resilience-engineering.md (section 2). Vector clocks give causal ordering instead: each replica keeps a per-node logical counter, so version {A:2} provably descends from {A:1} and supersedes it, while {A:1} and {B:1} are incomparable — a true concurrent conflict that must be surfaced, not silently ordered. Resolution options, in increasing effort:
Choosing LWW is choosing data loss under concurrency — make that choice explicitly per dataset, never by default.
Walk the write path end to end. Every box in this flow maps to one mechanism above; a design review that can't walk the path has found its gap.
write: client → any node (coordinator) → hash key to ring position
→ forward to preference list (N replicas)
→ each replica: append WAL → apply to memtable → ack
→ coordinator responds after W acks
→ hinted handoff covers any replica that is down
And the read path. The same flow in reverse is where staleness gets caught and healed:
read: client → coordinator → preference list (R replicas queried)
→ collect responses, compare versions
→ newest version → client
→ background: read-repair any replica that answered stale
Derive the -ilities from the mechanisms, don't assert them. Scalability: add ring nodes; only the affected arcs move. Latency: memory-first writes, sequential-only WAL I/O, reads querying R replicas in parallel and taking the first valid answers. Availability: RF=3 tolerates two simultaneous node losses; gossip plus coordination-service updates reroute around failures automatically. Arguing non-functional requirements as consequences of mechanisms is the template — for your own designs and for evaluating others'.
A cache is a speed layer, never a store of record. Every cached entry is an expiring RAM copy of something durable elsewhere; losing the entire cache tier costs latency, never data. This framing does real work:
If losing a cache node would lose data, the design has quietly become a KV store without a KV store's durability machinery — see the anatomy section above for what that actually requires.
Keep the functional contract narrow. Put with TTL, get returning value-or-miss, eviction under memory pressure, invalidation when the origin changes, and a defined miss path (read DB → populate → return). A narrow contract is what lets every node stay independent and the tier scale horizontally with no cross-node coordination on the hot path.
Placement is consistent hashing again. Cache nodes sit on a hash ring; keys route clockwise; adding or removing a node remaps ~1/N of the keyspace instead of wiping the tier. The mod-N cold-cache stampede from the first section is the canonical cache-cluster outage — the placement scheme is the first thing to check in any cache design review.
Write strategy — one heuristic, three options:
Rule of thumb: read-heavy → cache-aside; write-heavy + consistency → write-through; write-heavy + raw speed and loss tolerance → write-behind.
Eviction: recency vs frequency. When a node's RAM fills, what gets discarded should match the workload's access shape:
Invalidation: three strategies, chosen by staleness budget.
Hot keys break per-node math. Consistent hashing spreads keys evenly, not traffic — one viral key routes its entire load to a single node. Mitigations:
Thundering herd at cluster scale. When a hot entry expires — or a node restarts, or clients reconnect en masse — every concurrent reader misses at once and stampedes the database with identical queries, spiking CPU and latency in lockstep with the TTL. Layered defenses:
Rate limiting as the downstream backstop is owned by .claude/rules/resilience-engineering.md. Single-node lock mechanics and probabilistic early expiration are covered concretely in redis-caching-patterns (convention 14).
Keep the planes separate. Data plane: per-node RAM holding key, value, TTL, version. Control plane: a coordination service holding ring configuration, node-health state fed by gossip, and cluster policy defaults (eviction policy, default TTL, per-node size limits). Event plane: the message bus carrying invalidation events from the DB to cache consumers. Cluster metadata and data payloads travel through entirely separate systems; a design where the data path depends on the control path on every request has a hidden availability coupling.
The failure flow is the design's proof. If you cannot narrate this flow for a proposed design, the design is not finished:
read: client → app → ring routing → owning node → hit (microseconds)
miss → DB fetch → populate with TTL → return
node
failure: gossip detects within seconds → coordination layer updates ring
→ traffic reroutes to new owners
→ interim reads fall through to the DB — degraded, not down
Triage every lock by what a failure costs — the class decides all the machinery downstream:
TTL leases are mandatory and insufficient. The lease must expire or a crashed holder wedges the system forever — but expiry opens the failure window: any client can pause (GC, page fault, CPU starvation, packets stalled in the network) past its own lease, then wake and keep writing in the honest belief that it still holds a lock that has long since been granted to someone else. Re-checking validity just before the write closes nothing; the pause can land between the check and the write. Real production data-corruption incidents trace to exactly this window.
Fencing tokens make the resource the final arbiter. The lock service issues a strictly monotonically increasing token with each acquisition; every write to the protected resource carries the holder's token; the resource rejects any token lower than the highest it has already accepted. The stale holder's late write now bounces harmlessly:
client A acquires lock (token 33) → stalls in a GC pause … lease expires
client B acquires lock (token 34) → writes with 34 → accepted
client A wakes, believing it still holds the lock → writes with 33 → REJECTED (34 already seen)
A coordination service's transaction id or version counter serves as the token. Two hard consequences: a lock service that cannot issue ordered tokens cannot protect correctness no matter how many nodes it runs, and a resource that cannot check tokens should push you toward restructuring the operation (compare-and-set, transactions, idempotency) rather than trusting lease timing.
Fence the old primary before promoting the new one. Failover is the same problem at cluster scale: before clients are repointed, the old primary must be made provably unable to accept writes — stop the machine, flip it read-only, cut its network path. Skip the fence and a partition leaves two writable primaries forking the dataset; production split-brain forks lasting seconds have taken days to reconcile. When a partition makes the old primary's state unverifiable, the disciplined move is to pause the failover and escalate to a human rather than promote — an explicit consistency-over-availability call. Detection timing and the majority-quorum membership rule live in the gossip section below.
The lock-free alternative: idempotent, monotonic writes. Before adding any correctness lock, check whether the operation can stop needing one. When applying a write twice equals applying it once (idempotent) and state only moves forward — set a flag, take a maximum, add to a set (monotonic) — lost updates and stale-writer damage become impossible by construction: a delayed duplicate lands on a state it cannot regress. Compare-and-set on a version column, commutative merges, and append-then-dedupe pipelines are all this move. A lock you can delete beats any lock you have to get right.
Locks compose with retries and timeouts — respect the ownership boundary. Bounded acquisition attempts with jitter, and never holding a lease across a call that can block longer than the lease, are the retry/timeout discipline owned by .claude/rules/resilience-engineering.md; the concrete single-cluster stampede-lock implementation lives in redis-caching-patterns.
Bounded vs unbounded input is the primary fork. Ask "does this input ever finish?" before any tooling question. A finite, predictable dataset — a day of orders, a month of payroll, a table to backfill — suits batch: let records accumulate, then process the whole set as one scheduled unit. A never-ending event flow — clicks, sensor readings, payments to screen — suits stream: process each event as it arrives. Everything else about the two models follows from that one property:
| Property | Batch | Stream |
|---|---|---|
| Input | Bounded — the set completes | Unbounded — events never stop |
| Optimizes for | Throughput, whole-set consistency | Reaction time (seconds or less) |
| Staleness | Built in — the accumulation window | Near zero |
| Failure unit | The run — bounded, rerunnable | The event — recover while consuming |
| Operations | Scheduled window; fixable offline | Continuous; monitored around the clock |
Windowed aggregation is the consequence of unboundedness. A stream never finishes, so "the total" does not exist — every aggregate is scoped to a declared time window: error rate over the last five minutes, per-user spend this hour. Window semantics (length, overlap, how late events count) are product decisions that change what the number means, not framework configuration details.
Failure granularity is where the models truly diverge. A mid-run batch error can force reprocessing the whole unit — but the unit is bounded and rerunnable, which keeps batch recovery operationally simple: fix, rerun, done. A stream must recover per event while continuing to consume, and any computation that spans events (a per-user running total) needs durable per-key state maintained across distributed nodes. That fault-tolerant state management is the genuinely hard part of streaming and the reason stream-processing frameworks exist — use one rather than hand-rolling per-key state recovery.
Micro-batching is the deliberate hybrid. Process small chunks on a short interval: near-real-time latency with batch execution simplicity. Price this option first whenever "fresh within a few seconds" is fresh enough — many requirements stated as "real-time" are micro-batch requirements wearing an urgent hat.
Schedule batch around its resource spike. A batch run concentrates CPU, memory, and IO pressure into its window; aimed at peak interactive hours it becomes a self-inflicted incident. Run heavy jobs off-peak — and note that the materialized-view refreshes in the partitioning section above are small batch jobs deserving the same scheduling discipline.
When the input shape alone doesn't decide, three factors do:
The ingestion buffer is shared territory. The durable broker that decouples producer rate from consumer rate — so a downed consumer loses nothing — is taught in system-design-patterns (Notification fan-out) and is a stream's front door; a batch job consuming event data is just a scheduled drain of the same buffer. Operation-level batching — grouping many small writes into one large one — is this section's trade-off replayed at storage-engine scale (the "batching generalizes buffering" point in the engines section below).
A central health-checker doesn't scale and is its own single point of failure. One process pinging thousands of nodes is a bottleneck, and when it dies the cluster goes blind. Failure detection should be as decentralized as the data it protects.
Gossip dissemination. Each node periodically exchanges its view of membership and health with a small random sample of peers — Cassandra's cadence is 3 random peers once per second. Information spreads epidemically: knowledge of a dead node reaches the whole cluster in seconds, per-node cost stays constant as the cluster grows, and there is no coordinator anywhere. The same channel carries joins and leaves; what gossip learns feeds the coordination service so routing state stays current.
Suspect before you convict. Declaring a node dead on one missed heartbeat causes flapping under GC pauses and network blips; waiting too long delays recovery. The two-stage discipline: roughly 10 seconds of silence marks a node suspected; roughly 30 seconds confirms it dead and triggers rerouting of its keys. Suspected nodes can be deprioritized for reads before the cluster commits to expensive ownership changes.
Phi-accrual, in plain terms. Fixed timeouts encode one guess about network behavior. The phi-accrual approach replaces the binary "dead after T seconds" with a continuously rising suspicion score: track the historical distribution of each peer's heartbeat inter-arrival times and compute, for the current silence, "given this node's history, how improbable is a heartbeat this late?" Consumers act at different thresholds — reroute reads at mild suspicion, trigger expensive recovery only at near-certainty — and the detector self-tunes per link, so a node on a flaky WAN link isn't judged by LAN expectations.
Split-brain awareness. A network partition makes each side see the other as dead — both may elect leaders, claim shard ownership, and accept conflicting writes. Two disciplines keep this survivable:
How a service should behave during the partition — degrade, refuse, or serve stale — is the partition-behavior decision owned by .claude/rules/resilience-engineering.md.
Distributed stores are local storage engines glued together by everything above — and engines differ from one another almost entirely in the storage layer, where hardware costs (seek latency, page size, cache locality) collide with software. Two families dominate; picking between them is a read/write-profile decision, not a fashion choice.
The page abstraction drives everything. Disks and SSDs transfer fixed-size pages (4–16KB), and reading one byte of a page costs about the same as reading the whole page. The right cost metric for any on-disk structure is pages read, not comparisons made.
Why binary search trees fail on disk. A BST's O(log₂ n) assumes uniform access cost — true in RAM, false on disk. A million-entry binary tree is ~20 levels deep; with tiny nodes scattered across the disk, one lookup can cost up to 20 random page reads, potentially milliseconds each. The fix is trading depth for width: make each node fill a page (~100 keys, ~101 children) and the same million keys need ~3 levels.
B+trees — the read-optimized default. Page-sized nodes of sorted keys; all leaves at identical depth, so lookup cost is uniform and predictable. Internal nodes carry only routing keys — maximizing fanout and flattening the tree — while leaves hold the data (or row pointers) and are chained in sorted order, so a range query descends once and then walks leaves sequentially. Why this family won for OLTP:
LSM trees — the write-optimized inversion. Writes land in an in-memory sorted memtable — zero disk I/O on the hot path. Because the memtable is volatile, every mutation is first appended to a write-ahead log: a sequential disk append costing minimal latency, replayed after a crash so no acknowledged write is lost. When the memtable fills, it flushes as an immutable sorted file — an SSTable — in one sequential write. Background compaction merge-sorts SSTables down through levels (each level roughly 10× the previous), dropping overwritten and deleted entries along the way.
write → WAL (sequential append, durability)
→ memtable (in-memory, sorted)
→ [full] flush → SSTable at L0 (immutable, sequential write)
→ background compaction: L0 → L1 → L2 … (merge, dedupe, drop deletes)
The result: all foreground write I/O is sequential appends — memory-speed ingest — where a B-tree pays its reorganization cost inline on every write. This is why write-heavy workloads favor LSM engines (the Cassandra/RocksDB lineage), and why a Dynamo-style KV node runs one locally.
The price is read and rewrite work — the three amplifications. A point lookup may consult the memtable, every L0 file (their key ranges overlap, being independent flushes), and one file per lower level — read amplification. Compaction rewrites each key repeatedly as it migrates down levels — write amplification, routinely underestimated. Superseded versions occupy disk until reclaimed — space amplification. The three trade against each other, and tuning an LSM engine means choosing a point on the triangle:
Read-amplification mitigations are standard equipment. Per-SSTable Bloom filters (no false negatives, rare false positives) skip files that definitely lack the key; sparse in-memory fence pointers jump straight to the relevant block of a file; and compaction itself consolidates files so future reads touch fewer of them. An LSM deployment missing these is paying full read amplification for no reason.
Immutability, buffering, ordering — the triad that explains most engine design. Buffering governs when writes reach disk: accumulate and reorder many small random writes into few large sequential ones (the idea behind both memtables and WAL layout). Immutability governs whether existing bytes change: append-only segments make crash recovery trivial (a segment fully exists or doesn't) and reader/writer concurrency radically simpler — readers cannot race a mutation that never happens — at the cost of background garbage collection (compaction, vacuum). Ordering governs how data is arranged: sorted runs merge linearly and turn range access into sequential I/O. Key reframing: immutability doesn't remove the cost of change — it defers and batches it into background work.
Batching generalizes buffering up the stack. The same amortization that motivates memtables applies at every level: grouping many small operations into one large one spreads connection setup, transaction bookkeeping, fsync, and network round-trips across the whole batch — bulk row inserts instead of per-row statements, consumers polling messages in batches for throughput, settlement jobs processing payments in grouped runs. The costs are symmetrical: the tail item of a batch waits longest, a partially failed batch needs deliberate retry semantics (which items retry, which are poisoned), and batch size becomes an explicit tuning knob between throughput and latency.
Indexes are the same trade in miniature. Every secondary index buys read speed with extra storage plus write amplification — each insert/update/delete must maintain it. Over-indexing a write-heavy table degrades ingest the same way aggressive compaction does; index selection is really a choice about which query shapes to privilege. A clustered index (one per table, usually the primary key) dictates physical sort order and makes range scans on that key cheap; every non-clustered index pays an extra indirection — index lookup, then a second fetch from the data file — unless it is covering. Single-node transaction and locking discipline on top of these engines is covered in python-dao-and-database.
Row vs column layout is the other physical fork. Row stores keep all fields of one record adjacent — right for OLTP, where fetching or inserting a whole record touches one location, and wrong for analytics, where aggregating one column forces reading every full row. Column stores keep each column's values contiguous across all rows — right for OLAP scans over few columns of many rows, and they compress far better because same-column values are homogeneous; the mirror-image weakness is that reconstructing one full row touches many column files. Heuristic: "everything about one entity" → rows; "one attribute across millions of entities" → columns. Needing both at once is why OLTP/OLAP separation and ETL pipelines exist — don't ask one layout to serve both masters.
Disk-based vs in-memory placement is a working-set question. Disk engines keep the authoritative copy on durable storage and cache hot pages in a buffer pool; the entire discipline of indexes, prefetching, and sequential-write design exists to bridge the latency gap between RAM (nanoseconds) and storage (tens of microseconds for SSD random reads, milliseconds for spinning disk). In-memory engines remove disk from the hot path and reach microsecond latencies, but must re-engineer durability with snapshots and/or an append-only operation log replayed at restart — both built on sequential writes because those are the cheap kind. In practice most deployments are hybrids: a disk engine whose buffer pool covers the working set serves hot data at RAM speed anyway, so working-set size relative to available RAM is the first-order tuning question before any engine swap.
B-tree variants exist for specific pain points — recognize them in engine documentation. None replaces the classical B+tree as the general-purpose default; each answers exactly one weakness of in-place updates:
Beware log-on-log stacking. An LSM engine compacts at the logical level; a copy-on-write or log-structured filesystem underneath relocates those "sequential" writes again; the SSD's flash translation layer does its own log-structured remapping and garbage collection for wear-leveling below that. Each layer's cleanup looks efficient in isolation; together their independent GC passes duplicate and interfere, multiplying hidden write amplification. The remedy is mindful stacking: collapse layers where possible, or at minimum count how many log-structured layers the deployment stacks before trusting any write-amplification estimate.
Match the family to the measured read/write mix.
| Profile | Engine family | Why |
|---|---|---|
| Read-heavy / mixed OLTP | B+tree | Predictable 1–2 page reads, cheap ranges, in-place updates |
| Write-heavy ingest (events, telemetry, KV) | LSM | Sequential-only foreground I/O, memory-speed ingest |
| Write-dominated, rarely read (logs) | LSM, relaxed/unordered variants | Even cheaper ingest, reads pay for it |
.claude/rules/resilience-engineering.md on distributed time).Digests (own-words summaries of the sources, in references/):
Attribution: the htn-* digests are synthesized from public X threads by Harshit Khosla (@Harry_The_Nerd); the asdr-* and aea-* digests summarize the public articles named in each file's frontmatter — all own-words summaries, no verbatim text.
Related skills and rules:
system-design-patterns — system-scale building blocks (gateways, queues, fan-out, rate limiting) that sit above this data tierredis-caching-patterns — concrete single-cluster cache implementation: namespacing, SCAN invalidation, stampede locks, in-memory fallbackpython-dao-and-database — single-node transactions, locking, and DAO discipline on top of the storage engines described here.claude/rules/resilience-engineering.md (always loaded) — owns CAP/PACELC partition behavior, distributed-time/clock correctness, retries, circuit breakers, backpressure, and chaos verificationREADME.md (opens in a new tab)references/aea-011-lessons-learned-from-10-years-of-dynamodb.md (opens in a new tab)references/aea-019-scaling-bitbucket-s-database.md (opens in a new tab)references/aea-055-dropbox-s-scalable-consistent-metadata-caching-solution.md (opens in a new tab)references/aea-060-how-ebay-exports-billion-scale-graphs-on-transactional-graph.md (opens in a new tab)references/aea-066-how-ebay-loads-and-updates-over-ten-billion-vertex-graphs.md (opens in a new tab)references/aea-067-ebay-s-real-time-and-performant-index-service-for-its-large-.md (opens in a new tab)references/aea-081-cache-made-consistent-how-meta-handles-cache-invalidation.md (opens in a new tab)references/aea-082-a-highly-available-strongly-consistent-storage-service-using.md (opens in a new tab)references/aea-084-how-we-built-a-general-purpose-key-value-store-for-facebook-.md (opens in a new tab)references/aea-095-how-figma-reduced-potential-instability-by-scaling-to-multip.md (opens in a new tab)references/aea-098-flipkart-s-mysql-highly-available-setup.md (opens in a new tab)references/aea-114-answering-billions-of-reporting-queries-each-day-with-low-la.md (opens in a new tab)references/aea-149-upscaling-linkedin-s-profile-datastore-while-reducing-costs.md (opens in a new tab)references/aea-175-netflix-s-key-value-data-abstraction-layer.md (opens in a new tab)references/aea-176-netflix-s-timeseries-data-abstraction-layer.md (opens in a new tab)references/aea-197-lessons-learned-from-sharding-postgres-at-notion.md (opens in a new tab)references/aea-244-horizontally-scaling-the-rails-backend-of-shop-app-with-vite.md (opens in a new tab)references/aea-263-scaling-datastores-at-slack-with-vitess.md (opens in a new tab)references/aea-312-mysql-at-uber.md (opens in a new tab)What SKILL.md sets; muted values are Claude Code's defaults
npx claudepluginhub ajyadav013/claude-kit --plugin claude-kit127 skills in this plugin
/accessibility-reviewUI accessibility (WCAG) review — keyboard operability, focus, ARIA semantics, color contrast, touch targets. Returns prioritized fixes. Distinct from performance/visual review./alembic-migrationsAlembic migration setup and patterns for async SQLAlchemy — async engine + run_sync in env.py, autogenerate, RLS/multi-tenant migrations. Use for alembic init, writing migrations, or debugging migration errors./anthropic-vertex-integrationClaude on Vertex AI via the AnthropicVertex SDK — lazy ADC client init, env-based project/region resolution, async helpers, backoff retry. Use when calling Claude via GCP Vertex AI (not direct Anthropic API)./api-and-interface-designStable API and interface design patterns. Use when designing REST/GraphQL endpoints, module boundaries, type contracts between modules or frontend/backend, or changing public interfaces./api-integrationWire the app to a backend API — data fetching, caching, error handling, loading states. Use when connecting to an endpoint, adding a fetch layer, or fixing API error and loading behaviour. React-query detail lives in tanstack-react-query-patterns./api-pagination-filtering-sortingHTTP query parameter conventions for pagination, filtering, sorting, and search with standardized response metadata. Use when designing list endpoints or building repositories that turn query params into SQL.Other plugins' skills for the same job