System design · Partitioning, replication, quorums

How to design a key-value store

A key-value store has the smallest API in system design: get, put and delete. Everything interesting happens underneath: spreading keys across machines, keeping copies in sync, staying writable when a node dies, and deciding which value wins when two writes collide. This design follows Amazon's 2007 Dynamo paper, which also shaped Cassandra and Riak.

Updated · 5 min read

Any node coordinates a request, forwarding it to the key's N = 3 replicas and waiting for W acks or R replies. If a replica is down, a hint holder takes the write.

Key-Value Store architecture diagram

Any node coordinates a request, forwarding it to the key's N = 3 replicas and waiting for W acks or R replies. If a replica is down, a hint holder takes the write.

The short version

  • Consistent hashing with virtual nodes places keys on a ring. Adding a node moves only about 1/N of the keys.
  • Each key lives on 3 nodes. A put waits for W acks, a get for R replies, and R + W > N makes them overlap.
  • Last-write-wins is simple but clock skew drops writes. Vector clocks detect concurrent versions and make the client merge.
  • Hinted handoff covers short outages. Merkle trees find the few keys that drifted apart.
  • Hashing spreads keys, not traffic. A hot key needs a cache or splitting.

Clarifying questions to ask first

  • What operations are needed? (Assume get, put and delete only. Range scans, secondary indexes and multi-key transactions are out of scope.)
  • How large are keys and values? (Assume short string keys and opaque values up to about 1 MB, with 1 KB on average.)
  • What consistency does the caller need? (Assume tunable per request: the caller picks between faster, possibly stale reads and slower, up-to-date ones.)
  • Must writes succeed during a node failure or a network split? (Assume yes: the store stays writable, and conflicts are resolved afterwards.)
  • What scale and latency? (Assume 10B keys, 600,000 requests a second at peak, and single-digit millisecond p99.)

Numbers that shape the design

QuantityAssumptionResult
Data10B keys × 1 KB average value≈ 10 TB, ≈ 30 TB with N = 3
Nodes≈ 2 TB usable disk per node, kept half full for compaction and growth≈ 30 nodes
Traffic500,000 gets/s and 100,000 puts/s at peak600,000 client requests/s
Replica workeach put goes to 3 replicas; each quorum get reads 2≈ 300,000 replica writes/s and 1M replica reads/s ≈ 43,000 operations/s per node

Partitioning is mandatory, replication triples write load, and with 30 nodes something is always failing.

API

The client talks to any node, which coordinates that request. Consistency is chosen per request.

PUT /kv/{key}?w=2
  If-Match: {context}
  body: <bytes>
→ 200 OK  { "context": "vc:[A:3,B:1]" }

GET /kv/{key}?r=2
→ 200 OK  { "values": ["<bytes>"], "context": "vc:[A:3,B:1]" }

DELETE /kv/{key}?w=2
  If-Match: {context}
→ 204 No Content

The context is the version the client last saw. When replicas conflict, a get returns several values and the client writes back a merge.

Storage engine

Each node runs an LSM tree. Writes go to an append-only log and a sorted in-memory table, which is flushed to immutable sorted files when full. Every write is a sequential append, which suits a replicated, write-heavy load.

commit log        append-only, fsync'd, replayed on restart
memtable          in memory, sorted by key, ≈ 64 MB
SSTable files     immutable, sorted by key, on disk
  data block      key | version | timestamp | tombstone flag | value
  index block     first key of each data block → offset
  bloom filter    "is this key possibly in this file?"

record version    vector clock [(node, counter), ...] or a timestamp

A delete writes a tombstone. It must live long enough to reach every replica, or repair copies the deleted value back from a stale one.

High-level design

  • No master: any node can coordinate any request. Each physical node owns many virtual nodes on the ring, so load spreads evenly and a new node takes small slices from everyone. Modulo hashing would move almost every key.
  • A key is stored on the first N distinct physical nodes clockwise from its hash, its preference list. Database replication compares this leaderless scheme with leader-follower.
  • Nodes gossip with a few random peers every second, so ring changes spread without a central registry.

Quorums and conflicts

N = 3, R = 2, W = 2 is the common default. R = 1, W = 1 is fastest but may be stale; W = 3 fails writes when any replica is down. Cassandra exposes this as per-request levels such as ONE, QUORUM and ALL. A quorum is not linearizability: concurrent writes, clock skew and sloppy quorums still cause anomalies. Eventual consistency covers the levels in between.

For two writes to one key on different replicas, last-write-wins keeps the highest timestamp. Cassandra uses it, but clock skew can silently drop a newer write. Vector clocks keep a counter per writing node, so the store can tell descent from concurrency. The original Dynamo returned concurrent versions to the client to merge; a shopping cart takes the union.

Failures and repair

  • Cassandra's phi accrual failure detector outputs a suspicion level rather than yes or no.
  • Hinted handoff: if a replica is down, the next healthy node takes the write with a hint naming the owner, replayed on recovery. This sloppy quorum keeps writes available but breaks the R + W > N overlap.
  • Anti-entropy: replicas build Merkle trees over key ranges, compare root hashes and walk down only differing branches, copying the few divergent keys.

Common traps

  • Ignoring hot keys. One celebrity profile lands on the same N replicas, and adding nodes doesn't help. DynamoDB limits a partition to about 3,000 reads and 1,000 writes a second. Cache hot reads, read any one replica when staleness is fine, and split hot write keys into key#1 ... key#10.
  • Counting virtual nodes on one physical machine as separate replicas. They fail together.
  • Acking a put after changing only the memtable. A restart loses it; return success only after the commit log is durable.
  • Sizing nodes from client requests alone. Quorums and replication multiply internal operations.
  • Filling disks with live data. An LSM engine needs room to merge files during compaction.

Follow-up questions interviewers ask

  • "Why can a deleted key come back?" A stale replica missed the delete. The tombstone has to outlive that gap.
  • "LSM tree or B-tree?" An LSM tree suits write-heavy loads; Cassandra, RocksDB and LevelDB use one. A B-tree updates pages in place and gives more predictable reads.

Frequently asked questions

Why use consistent hashing instead of hash modulo the number of nodes?

+

With hash(key) mod N, changing N moves almost every key. Consistent hashing moves only the keys between the new node and its neighbour, roughly 1/N of the data. Virtual nodes keep the ranges even.

What does R + W > N mean?

+

N is the number of replicas, W how many must acknowledge a write, and R how many must answer a read. If R + W > N, the read set always overlaps the set that took the latest write.

How does a Dynamo-style store stay available when a node is down?

+

Writes go to the next healthy node with a hint and are handed back when the owner returns. Reads succeed while R replicas answer. Merkle-tree anti-entropy and read repair fix copies that drift.

Now fix it yourself.

Run the design under real traffic and see what breaks first. No signup.