Skip to content

Design a Key-Value Store

A system design interview walkthrough for a distributed key-value store, covering partitioning, replication, quorums, conflicts and failure repair.

Advanced24 minUpdated 2 December 2026

Before this: Consistent Hashing, Database Replication, CAP Theorem

"Design a key-value store" asks you to build the thing other designs quietly rely on. Interviewers like it because the interface is tiny, get(key) and put(key, value), while every hard problem in distributed systems hides behind it: partitioning, replication, consistency, failure and recovery.

The question is rarely about one clever structure. It tests whether you can make a chain of trade-offs and keep them consistent. If you choose "always writable" in step three, step five cannot quietly assume strict consistency. A strong answer reads like a single story with one stance on the CAP trade-off, and a weak one reads like a list of buzzwords.

This page designs a Dynamo-style store: partitioned by key, replicated on several nodes, tunable per request. It leans on consistent hashing and replication, so read those first if the vocabulary is new.

Clarify the requirements

Functional requirements:

  1. put(key, value) stores a value, get(key) returns it, delete(key) removes it.
  2. Values are opaque blobs up to 1 MB, usually about 1 KB.
  3. Keys are looked up exactly. There are no range scans or secondary indexes.
  4. The cluster grows and shrinks by adding or removing nodes without downtime.

Out of scope, said aloud: multi-key transactions, range queries, SQL, cross-key secondary indexes.

Non-functional requirements:

  • Always writable: a write succeeds even when a node or a whole availability zone is down. This is the stance everything else follows from.
  • Low latency: p99 under 10 ms for single-key operations.
  • Tunable consistency: the caller chooses, per request, between fast and fresh.
  • Horizontally scalable: capacity and throughput grow by adding nodes.
  • Durable: an acknowledged write survives the loss of a node, and of a rack.

Estimate the scale

Assume 10 billion items at an average 1 KB, a replication factor of 3 and a peak of 200,000 operations a second, 80% reads.

Data size: 10 × 10⁹ × 1 KB = 10 TB of unique data, and ×3 replicas = 30 TB on disk.

Node count: a log-structured engine needs free space for compaction, so plan to fill each node's disk only to about 50%. With 4 TB of NVMe, a node holds 2 TB of data, so 30 TB ÷ 2 TB = 15 nodes at least. Round to 16 for even racks.

Peak operations: 200,000 × 0.8 = 160,000 reads and 40,000 writes per second.

Replica work: each write touches all 3 replicas: 40,000 × 3 = 120,000 replica writes per second. A read at quorum 2 contacts 2 replicas: 160,000 × 2 = 320,000 replica reads. Total 440,000 replica operations per second ÷ 16 nodes ≈ 27,500 per node, which is comfortable for NVMe.

Average rates: peak is 3× average, so about 14,000 writes and 56,000 reads a second on average.

"The data is the binding constraint, not the request rate: 30 TB means about 16 nodes before throughput matters. And every client write becomes three replica writes, so replication multiplies the write path. Node count will change often, so partitioning must make adding a node cheap."

You can reproduce the request rates in the capacity estimator. Ignore its storage line: it counts every write as new data, and here most writes overwrite existing keys.

API and data model

PUT    /v1/kv/{key}     { value, context?, w? }     -> { version }
GET    /v1/kv/{key}     ?r=2                        -> { value | siblings[], context }
DELETE /v1/kv/{key}                                 -> { version }
partition map:   token ring, 128 virtual nodes per physical node
record:          (key, value, version, tombstone?, timestamp)
on-node storage: commit log + memtable -> immutable sorted files (SSTables)

context carries the version metadata a client got on its last read, so a later write says which value it is replacing. That is how the store tells a real update from a conflicting one.

High-level design

The slice to simulate is the request path: clients call a stateless coordinator, which routes each key to its replicas on the storage ring.

Clients call a stateless coordinator that routes each key to its replicas in a Dynamo-style ring, with tunable read and write quorums.clientscoordinatorstorage ring
Clients call a stateless coordinator that routes each key to its replicas in a Dynamo-style ring, with tunable read and write quorums.
  • Any coordinator can serve any key, because every node knows the ring layout.
  • The coordinator hashes the key, finds its three replicas and sends the operation to them in parallel.
  • Reads and writes wait for a configured number of replicas (the quorum), not all of them.
Describe this diagram

Components

  • clients (Client)
  • coordinator (Service)
  • storage ring (Cassandra)

Connections

  • clients sends to coordinator
  • coordinator sends to storage ring

Run it, then change the read and write consistency between ONE, QUORUM and ALL, and try shrinking the ring. Watch how latency and errors move as you ask for stronger guarantees.

The write path: the coordinator hashes the key to a position on the ring and takes the next three distinct nodes clockwise. It sends the write to all three and answers the client once W have acknowledged. Each replica appends the write to a commit log (for durability), updates an in-memory table, and later flushes sorted immutable files to disk.

The read path: the coordinator asks the replicas, waits for R responses and returns the newest version. If replicas disagree it repairs the stale ones in the background (read repair). A Bloom filter on each file (Bloom filters) lets a node skip files that cannot contain the key.

The interesting problem: staying consistent while staying available

The central decision is how replicas agree. There are three honest answers.

Approach A: one leader per key range, synchronous followers

Each partition has a leader that orders all writes and copies them to followers before answering.

Good: easy to reason about, with one order per partition and no conflicting versions to merge.

Bad: if the leader is unreachable, writes to that partition stop until a new leader is elected. With synchronous followers, one slow follower slows every write. That contradicts "always writable".

Approach B: a consensus group per partition

Each partition runs Raft or Paxos across its three replicas. A write commits when a majority has it, and a leader is re-elected automatically.

Good: linearizable reads and writes, with automatic failover. This is the right design for configuration, metadata and locks, and the subject of distributed coordination.

Bad: every write pays a leader round trip plus a majority. A partition with two of three replicas unreachable cannot write at all. Cross-region deployments pay the cross-region latency on each write.

Approach C: leaderless replication with quorums

Any replica accepts a write. The coordinator sends it to all N, and the call succeeds when W respond. A read asks R replicas. If R + W > N, every read set overlaps every write set in at least one replica, so a read sees the latest acknowledged write.

With N = 3 the useful settings are:

  • W = 2, R = 2: balanced. Tolerates one node down for both reads and writes. R + W = 4 > 3.
  • W = 1, R = 1: fastest, but R + W = 2, so a read can miss the write. Fine for caches and counters that tolerate staleness.
  • W = 3, R = 1: cheap reads, but one down node stops all writes.

Good: no leader to elect, and writes continue through node failures. Latency is set by the second-fastest replica, which cuts the tail.

Bad: concurrent writes to the same key can land on different replicas in different orders, so the store must detect and resolve conflicts, which is the next section. Quorum overlap is also not full linearizability. A failed write that reached one node can show up later.

Conceptual diagramwritewritewriteackackW = 2 acks, reply OKClientCoordinatorReplica 1Replica 2Replica 3
Diagram, as text
  • Client leads to Coordinator
  • Coordinator leads to Replica 1 (write)
  • Coordinator leads to Replica 2 (write)
  • Coordinator leads to Replica 3 (write)
  • Replica 1 leads to Coordinator (ack)
  • Replica 2 leads to Coordinator (ack)
  • Coordinator leads to Client (W = 2 acks, reply OK)

The recommended answer for this requirement list is C, because "always writable" is the first requirement. Say clearly that you would choose B if the stated need were strict consistency, and name what you gave up. This sentence is what separates a reasoned answer from a memorized one.

The second decision: resolving conflicting versions

Leaderless writes can conflict, so you need a rule for the winner.

  • Last write wins (LWW): every write carries a timestamp, and the highest wins. It is simple and needs no client help, but clocks drift. Two concurrent writes 50 ms apart on machines with 100 ms of skew can resolve in the wrong order, and the losing write vanishes silently with no error.
  • Version vectors: each replica keeps a counter per writer, so the store can tell "B happened after A" from "A and B happened independently". For independent updates, it returns both values (siblings) and the client merges and writes back. Nothing is lost, but clients must handle merging.
  • CRDTs: data types (counters, sets) designed so any merge order gives the same answer. They remove the conflict for specific types.

A reasonable stance: LWW by default for simplicity, with version vectors available for keys where lost updates matter, and tombstones for deletes. A delete must be written as a marker (a tombstone) that is kept for longer than any replica can stay offline, or a stale replica will bring the deleted value back from the dead.

Bottlenecks and failures

A node is down for ten minutes. With a strict quorum, writes whose replica set includes it still succeed with W = 2, because two of three remain. A sloppy quorum goes further: the coordinator writes to the next healthy node on the ring with a hint saying "this belongs to node X", and hands it over when X returns (hinted handoff). Availability goes up, but a quorum read may not see the write until the hint is delivered. Say that.

A node is down for a week. Hints are kept for a bounded window (hours, not days). After that, anti-entropy repairs the node: it compares Merkle trees of its key ranges with its replicas and streams only the ranges that differ, instead of scanning everything.

Failure detection. Nodes learn about each other by gossip: each periodically shares what it knows, so a failure spreads across 16 nodes in a few rounds with no central monitor to fail.

Hot keys. Hashing spreads keys evenly, but one celebrity key goes to one replica set. A client-side or coordinator cache absorbs reads, as in a distributed cache. For a hot write counter, shard the logical key into several physical ones.

Compaction and write amplification. An LSM engine writes fast and pays later, merging files in the background. Compaction competes with foreground reads for disk. Throttle it, schedule it by level and keep disk under half full so it never runs out of space mid-merge.

Adding a node. With 128 virtual nodes per host, a new node takes small slices from many neighbors, so about 1/17 of the data moves (with 16 nodes plus one), pulled from many sources in parallel. Throttle the streaming so it does not hurt live traffic.

Trade-offs to name aloud

  • Availability over strict consistency: you choose leaderless quorums, so a read can briefly be stale, and you say when you would choose consensus instead.
  • Tunable R and W: every caller can buy speed or freshness, but every caller can also choose badly.
  • LWW versus version vectors: simplicity and silent loss against merge logic in clients.
  • Sloppy quorums: more writes succeed, but the quorum overlap guarantee is weakened.
  • LSM storage: fast writes and compact files, paid for in read amplification and compaction work.

What interviewers listen for

  • A working answer: consistent hashing for placement, three replicas and a get/put API over a storage engine.
  • A strong answer: states R + W > N with concrete settings, chooses a stance on CAP and defends it, and handles node failure with hinted handoff or read repair.
  • A standout answer: also explains why LWW loses data under clock skew and when version vectors are worth it, why tombstones outlive replica downtime, how Merkle trees make repair cheap, and where you would use consensus instead.

Check your understanding

Common mistakes

Describing a database, not a distributed system. Spending the hour on B-trees and the on-disk format skips the interesting part. One paragraph on the LSM engine is enough.

Quoting quorum math without stating a stance. "R + W > N" is a formula, not an answer. Say whether this store is available or consistent when a partition happens, and why.

Forgetting deletes. Removing a key from three replicas is easy until one of them is offline and later returns the old value. Tombstones and their retention are part of the design.

Relying on timestamps without discussing skew. Any design with LWW should mention clock drift and say how you bound it.

No repair story. A store that never reconciles replicas drifts apart. Read repair for hot keys and Merkle-tree anti-entropy for the rest are the standard pair.

Practice

A node's disk dies and the node is gone for good. Walk through how the cluster recovers and what the clients see.

Write your own answer first, on paper or in a note. Then compare.

Show a hint

Think about which keys lived on that node, where the other replicas are, and what you must not do to live traffic.

Show a strong answer

Clients see little. Every key on the dead node has two other replicas, and with W = 2 and R = 2 reads and writes proceed on the survivors. Latency rises slightly because the remaining replicas of those ranges take more work.

Replace the node with a new empty one that takes over the same ring positions (its virtual nodes). It must not serve reads for those ranges until it is caught up, or it would answer "not found" for keys that exist.

Stream the data from the surviving replicas. Because the dead node's 128 virtual nodes were spread across the ring, its ranges are replicated on many different peers, so the new node pulls from many sources in parallel. At 2 TB, streaming at 200 MB/s from many peers takes about 10,000 seconds, under three hours.

Throttle the stream so the donors' foreground latency stays within the p99 target, and run anti-entropy afterward to catch writes that arrived during the copy.

The pattern worth keeping: recovery should be many small transfers from many peers, not one large copy from one, which is exactly what virtual nodes give you.

One team needs compare-and-set (set a key only if its current value is X) with strict correctness, for about 1% of keys. Everything else stays as is. What do you change?

Write your own answer first, on paper or in a note. Then compare.

Show a hint

Quorums alone do not give you atomic compare-and-set. What can order the competing writes?

Show a strong answer

Explain why quorums fall short. Two clients can each read value X from a quorum, each write a new value with W = 2, and both succeed on different replica pairs. A quorum orders nothing, so atomic conditional updates need a single agreed order per key.

Run consensus for those keys. Use a per-key (or per-range) Paxos or Raft round for conditional writes: propose the new value with the expected old value, and a majority must agree on one winner. Cassandra's lightweight transactions work this way.

Route only the 1% through it. The consensus path costs several round trips, so keep ordinary keys on the fast path. Mark them in the schema or by a per-request flag.

Name the cost. Conditional writes are several times slower and unavailable if a majority of that key's replicas is down.

The pattern worth keeping: use the expensive guarantee only on the data that needs it, and keep the cheap path for everything else.

Key takeaways

  • Pick a stance on CAP first. "Always writable" leads to leaderless quorums, and "strict consistency" leads to consensus.
  • R + W > N makes reads overlap writes, and tuning R and W trades speed for freshness.
  • Virtual nodes make rebalancing and recovery many small transfers.
  • Concurrent writes need a conflict rule: LWW is simple but can lose data, and version vectors keep both.
  • Repair has layers: hinted handoff, read repair and Merkle-tree anti-entropy.
  • Deletes are writes: a tombstone must outlive any replica's downtime.

Further reading

  • G. DeCandia et al., "Dynamo: Amazon's Highly Available Key-Value Store", SOSP (2007): the origin of leaderless quorums, hinted handoff and version vectors.
  • A. Lakshman and P. Malik, "Cassandra: A Decentralized Structured Storage System", ACM SIGOPS Operating Systems Review (2010).
  • F. Chang et al., "Bigtable: A Distributed Storage System for Structured Data", OSDI (2006): the memtable, commit log and SSTable design.
  • D. Ongaro and J. Ousterhout, "In Search of an Understandable Consensus Algorithm" (Raft), USENIX ATC (2014).

Check yourself

3 questions in this lesson. Answer each once to complete it.

Practice this

Lessons in this track