CodingNodes Space play · ←→ step · R restart

The problem

A key-value store is the quiet workhorse underneath a surprising number of products: sessions, leaderboards, feature flags, the cache layer, and the primary store of a large fraction of the web. The interface is almost insultingly small — give it a key, it gives you a value back — and that is exactly what makes it hard: all the difficulty moves out of the interface and into where the key lives, how the value is kept, and what it means for a read to be 'correct'.

We will pin down the contract first, then walk the key space out onto a ring of shards, look at the two ways to keep the data on disk, add replication so no single machine is the last copy, choose how strong a read should be, and finally put the hot keys in memory with an expiry. By the end, one get("session:42") has a whole machine behind it, and we know exactly which piece of that machine each part of the story is owned by.

Requirements

Functional — what it must do

  • Set: a client stores a value under a key, optionally with a time-to-live; the value is returned by later reads until it expires or is overwritten.
  • Get: a client reads a key and receives its value, or a clean miss if the key is absent or has expired.
  • The key space is the contract — a key is an opaque string, the store keeps no schema, and two keys that differ are two unrelated values.

Non-functional — how well it must do it

  • Single-key reads answer in a few milliseconds at the 99th percentile when the key is hot, and remain under a few tens of milliseconds when it is not.
  • A write is durable before it is acknowledged: the value must survive the loss of any one machine in its replica set.
  • The service stays available at 99.99% — a replica or a shard may fall, and the remaining copies must keep serving.

Scale — how much it must take

  • On the order of ten billion keys, an average value of about 1 KB, and a peak of roughly one million operations per second — most of them reads.

Assumptions — the numbers this design is sized for

A rate limit means nothing without a scale. These are the figures every later part relies on: how much traffic arrives, how much work the limiter has to do per second, and how much latency and memory it may spend doing it.

Key count
~10 billion
The 'billions of keys' bar. Drives how many shards the key space must be cut into.
Avg value
~1 KB
Sessions, counters, short blobs. Small values keep the hot tier in RAM and the disk tier cheap.
Total data
~10 TB
Ten billion keys at about 1 KB. Big enough to shard, small enough that three copies still fit a normal cluster.
Operations
~1M / s
About 800K reads and 200K writes at peak. The read-heavy ratio is what justifies the memory tier.
Read latency
< 5 ms p99 (hot)
Hot keys answered from RAM. Cold keys may take a disk read but stay under a few tens of ms.
Replication
factor 3
Each key is held on three machines, so any single loss is absorbed. Quorum is two of three.
Consistency
tunable
The client asks per call for strong or eventual. The store must be able to do both.

Takeaways

Part 1

The whole API

The interface is deliberately tiny. Getting the contract right — what a miss is, what a TTL means, what a write promises — removes most of the later ambiguity.

  1. 1
    Set and get

    There are two verbs. Set writes a value under a key; get reads a key and returns the value or a miss. Everything else in the system exists to make those two calls fast, durable and correct at the same time.

  2. 2
    A key is an opaque string

    The store does not parse the key and does not know what it means. 'session:42' and 'cart:9' are unrelated strings as far as the engine is concerned. That opacity is a feature: the client owns the meaning, so the store can be dumb, uniform and fast.

  3. 3
    What a set actually promises

    A set is not just 'write to memory'. The promise is that once the call returns, the value is durable — it survives the death of any single machine — and that a later get sees it, subject to the consistency level the caller asked for. That sentence is most of this chapter.

Part 2

Cut the key space into shards

Ten billion keys will not fit on one machine and one machine is not fast enough. The first structural decision is how to divide the key space and route each key to its shard.

  1. 1
    Hash the key, land it on a shard

    A router in front of the cluster hashes each key and sends it to the shard that owns the resulting range. The same key always hashes to the same shard, so a get and a set for 'session:42' always find the same owner — with no directory lookup in the hot path.

  2. 2
    Why a ring, not a modulus

    A naive 'key mod N' re-homes a huge fraction of keys every time N changes, because every key's remainder shifts. A consistent-hash ring maps both keys and shards onto the same circle; adding a shard only moves the arc of keys between it and its predecessor — a small, bounded slice of the key space.

  3. 3
    Rebalance by moving a slice

    Because only one arc migrates, scaling out is a steady stream of key-range moves rather than a full re-shard. The ring is what turns 'add a machine' from a big-bang migration into a background trickle of range hand-offs.

Part 3

Two ways to keep it on disk

The value has to survive a reboot. There are two dominant answers — append to a log and compact later, or keep a balanced tree — and they trade write throughput against read shape.

  1. 1
    Log-structured: append, then compact

    The log-structured approach writes new values by appending to a memory buffer that is later flushed as an immutable file. Writes are fast because they are sequential, but a read may have to check the newest file first and fall back through older ones until the value is found.

  2. 2
    Tree: seek, in place

    A balanced tree keeps sorted pages on disk and updates values in place. Reads are a single seek and very predictable, but a write may touch several pages and pays for random I/O — the mirror image of the log-structured trade.

  3. 3
    Pick by the workload

    Write-heavy stores with many expiring keys lean log-structured, because the append is cheap and compaction can drop the expired values for free. Read-heavy, update-heavy keys lean tree. There is no winner — there is a match to the mix of reads and writes.

Part 4

Replicate so no one is the last copy

Each shard is really a small group of machines. The leader takes the writes, the followers keep a copy, and a quorum barrier is what makes a write durable rather than merely fast.

  1. 1
    One leader, two followers

    A key's shard is a group of three machines. All writes go to the leader, which forwards the change to the two followers. The leader is the source of truth for that key; the followers exist so that losing any one of the three loses nothing.

  2. 2
    Durable at the quorum

    The leader does not answer the client until two of the three machines have the value — the quorum. One copy on the leader is not durable; it is a single point of loss. Two of three means the client's write survives any single death, and the third can be caught up in the background.

  3. 3
    Reads can pick their lane

    A read can go to the leader, which is always current, or to a follower, which is cheaper but may be a moment behind. Which lane a read takes is exactly the consistency choice the caller made — strong reads go to the leader, eventual reads may be answered by a follower.

Part 5

How correct is a read?

A read is only as correct as the copy it lands on. Tunable consistency is the store's way of letting each caller buy exactly the freshness they need, and no more.

  1. 1
    Strong: the latest value, every time

    A strong read is forced onto the leader, so it always sees the most recent committed value. It is the safest answer and the most expensive: every strong read is a round trip to the one machine that is guaranteed current.

  2. 2
    Eventual: a recent-enough value

    An eventual read may be answered by any replica, including one that is a few milliseconds behind the leader. It is cheaper and more available, and it is correct in the sense that, given time and no new writes, every replica converges to the same value.

  3. 3
    The client pays for freshness

    The design point is that consistency becomes a per-call knob rather than a global property. A balance read can be strong; a cached counter can be eventual. The store offers both lanes, and the caller chooses which freshness is worth which latency.

Part 6

The memory tier and expiry

Most of the traffic is a small set of hot keys. Keeping those in RAM and letting the cold keys age out of it is what turns a disk-bound store into a sub-millisecond one.

  1. 1
    Hot keys live in RAM

    A memory tier holds the keys that are read often. A get that lands there is answered from RAM in a fraction of a millisecond and never touches disk. The disk tier still holds every key — the memory tier is a view of the hottest slice, not a second database.

  2. 2
    Keys can expire

    A key set with a time-to-live is scheduled to disappear. When its expiry passes, the next read is a miss and the entry is dropped. TTLs are how sessions, tokens and caches clean themselves up without the client ever issuing a delete.

  3. 3
    Eviction is the last resort

    When the memory tier fills, the store evicts the least-useful entries — typically the least recently used — so the hot keys stay and the cold ones fall back to disk. Eviction is deliberate forgetting: it costs a future miss, but it keeps the present fast.

★ Finale

End to end

The full store, one key at a time: a set is written to the leader, confirmed at the quorum, pushed to the memory tier, and replicated; a get lands on the ring, finds its shard, and answers from RAM.

  1. 1
    The whole store

    Every piece in one frame. The client talks to the router, the router finds the shard on the ring, the leader owns the key with two replicas behind it, and the memory and disk tiers sit between the leader and the answer.

  2. 2
    A set, made durable

    A client sets a key. The router lands it on its shard, the leader writes it to the memory tier and the disk tier, and the write is not acknowledged until two of the three replicas hold it. The client's set is now durable and, if it was hot, already fast to read back.

  3. 3
    A get, answered from RAM

    A client reads the same key. The router finds its shard again, the leader checks the memory tier, and the hot value is returned from RAM. The disk tier and the replicas are not on this path at all — the hot case never touches slow storage.

  4. 4
    A cold key, a strong read

    Now a key that is not in the memory tier, read with strong consistency. The router still finds the same shard, the leader falls through to the disk tier for the value, and because the caller asked for strong, the read was served by the leader rather than a possibly-stale replica.

🌐 In the wild

In the wild

The key-value pattern is one of the most deployed in the world. Here the boxes are anchored to the well-known systems that are known to be built from exactly these pieces — an illustrative mapping, not a claim about any one product's internals.

  1. 1
    The pattern, piece by piece

    Every box in the finale is a standard, named building block. The mapping below anchors each one to a class of well-known production system that runs that piece, so the abstract store reads as 'the pattern that runs a huge share of the web'.

  2. 2
    Why the same shape keeps winning

    Independent systems converge on the same pieces because each one removes a real bottleneck: the ring removes the re-shard, the quorum removes the last-copy risk, the memory tier removes the disk hop, and tunable consistency removes the one-size-fits-all freshness tax. That convergence is the strongest evidence the design is load-bearing.