System design interview: design a key-value store

A distributed key-value store keeps every value on several machines so it survives failures, and lets you choose per request how many replicas must answer before a read or write counts. The interview covers partitioning, replication with quorums, what happens when two writes to the same key race, how a node that was down catches up, and how each node stores data on disk efficiently.

By Published 8 min read

1. Clarify the requirements

Start by asking what the store is for. A shopping cart, a session store and a user-profile store all fit, and each one tolerates different trade-offs between availability and consistency.

  • Functional: put(key, value), get(key), delete(key); keys up to a few hundred bytes, values up to about 1 MB; no queries across keys.
  • Non-functional: stays writable when machines and even a whole zone fail; low single-digit millisecond latency at the median; durable once acknowledged; grows by adding machines; consistency tunable per use case.
  • Out of scope unless asked: range scans and secondary indexes, multi-key transactions, cross-region active-active replication.

2. Estimate the scale

Illustrative figures, stated as assumptions so the interviewer can change them.

Back-of-envelope sizing for a replicated key-value store (assumed figures)
QuantityAssumptionResult
Data100 TB of values, about 1 KB eachabout 100 billion keys
ReplicationN = 3about 300 TB stored
Disk per node4 TB, kept about 70% full for compaction headroomabout 2.8 TB usable, so about 107 nodes
Writes200,000 a second600,000 replica writes a second, about 5,600 per node
Reads600,000 a second with R = 21.2 million replica reads a second, about 11,200 per node
Back-of-envelope sizing for a replicated key-value store (assumed figures). Scroll sideways on a small screen.

Two things follow. The data set needs over a hundred machines, so partitioning and automatic rebalancing are not optional. And with that many machines, some are always failing or being replaced, so recovery has to be routine and automatic, not an incident.

3. Define the API

put(key, value, context=None, w=2)   -> new context (version information)
get(key, r=2)                        -> [ (value, context), ... ]   more than one if versions conflict
delete(key, context, w=2)            -> writes a tombstone

context is opaque to the caller: pass back the one you read when you write,
so the store knows which version your write replaces.
Per-request consistency settings let one cluster serve different needs.

4. Sketch the data model

The store itself knows only bytes, but each stored record carries bookkeeping that the design depends on.

What a node keeps per key, and why
FieldPurpose
keyHashed to find the replicas; stored for lookups and compaction
value or tombstoneThe data; a tombstone marks a delete so older replicas do not resurrect the value
version (timestamp or version vector)Decides which of two copies is newer, or that they conflict
expires_at (optional)TTL support; expired records are dropped during compaction
checksumDetects corruption on disk before a bad value is served
What a node keeps per key, and why. Scroll sideways on a small screen.

5. The core decision: replication and quorums

Place nodes on a hash ring with many virtual points each (the sharding guide explains the ring). A key's replicas are the first N distinct physical nodes clockwise from its hash, chosen so they sit in different racks or zones. Any node can act as coordinator for a request: it forwards the write to all N replicas and answers the client once W of them confirm; for a read it asks the replicas and answers once R reply.

Common settings with N = 3
R / WBehaviorFits
R = 2, W = 2Read and write sets always share a replica; tolerates one replica down for bothA balanced default
R = 1, W = 3Fast reads; a write fails if any replica is unreachableRead-heavy data that changes rarely
R = 3, W = 1Fast, highly available writes; slow readsWrite-heavy logging-style data
R = 1, W = 1Fastest and most available; reads may be staleCaches and data where staleness is harmless
Common settings with N = 3. Scroll sideways on a small screen.

R + W > N means every read quorum overlaps every write quorum, so a read sees at least one copy of the latest acknowledged write. It is not full linearizability: concurrent writes, sloppy quorums during failures and clock-based conflict rules can still surprise you. Say that out loud; interviewers like hearing the limits of a rule.

When two writes race

Two clients can update the same key through different coordinators during a partition. Last-write-wins keeps the copy with the higher timestamp: simple, but it silently drops one write and depends on clocks. Version vectors (a counter per coordinating node) let the store tell "newer" from "concurrent". When versions are concurrent, the store returns both and the application merges them, for example by taking the union of two shopping carts.

def compare(a, b):
    """Compare two version vectors (dict node -> counter)."""
    nodes = a.keys() | b.keys()
    a_ahead = any(a.get(n, 0) > b.get(n, 0) for n in nodes)
    b_ahead = any(b.get(n, 0) > a.get(n, 0) for n in nodes)
    if a_ahead and b_ahead:
        return "conflict"  # concurrent writes: keep both, let the reader merge
    if a_ahead:
        return "a newer"
    if b_ahead:
        return "b newer"
    return "equal"

print(compare({"n1": 2, "n2": 1}, {"n1": 1, "n2": 1}))  # a newer
print(compare({"n1": 2}, {"n1": 1, "n2": 1}))           # conflict
Comparing version vectors (run with python3; checked against a brute-force rule in 20,000 random cases)

6. The architecture

  1. Clients
    • Ring-aware client library
    • or load balancer
  2. Coordination
    • Any node acts as coordinator
    • Ring and membership from gossip
  3. Replicas
    • N replica nodes in different zones
  4. Repair
    • Hinted handoff
    • Read repair
    • Merkle-tree anti-entropy
  5. Per-node storage
    • Commit log
    • Memtable
    • Sorted files + Bloom filters
    • Compaction
A leaderless, replicated key-value store. Clients send requests through a load balancer or a ring-aware client library to any node, which coordinates the request. The coordinator hashes the key, finds the N replica nodes from the ring and sends the operation to them, waiting for W or R replies. Every node runs the same software: a request handler, a gossip agent that shares membership and health, a hinted-handoff queue, an anti-entropy process that compares Merkle trees with peers, and an LSM storage engine with a commit log, memtable and sorted files on disk.
  1. Write path on a replicaAppend the record to the commit log and sync it (or batch syncs every few milliseconds), insert into the in-memory sorted table, acknowledge. When the memtable fills, write it to disk as an immutable sorted file.
  2. Read path on a replicaCheck the memtable, then the sorted files from newest to oldest. A small Bloom filter per file says "definitely not here" for most files, so a read touches few of them.
  3. CompactionMerge sorted files in the background, keeping the newest version of each key and dropping tombstones once every replica has seen them.
  4. MembershipNodes gossip their view of who is alive every second or so. A node that stops responding is marked suspect, and requests route around it.

7. Scale it and keep replicas in sync

  • Sloppy quorum and hinted handoff. If a replica is down, the coordinator writes to the next healthy node on the ring with a hint naming the intended owner. When the owner returns, the hint is delivered and deleted. Writes stay available through short outages.
  • Read repair. When a read gets different versions from replicas, the coordinator writes the newest one back to the stale replicas. Hot keys repair themselves this way.
  • Anti-entropy with Merkle trees. For keys nobody reads, replicas periodically compare hash trees over their key ranges. Matching roots mean nothing to do; otherwise they descend only into the branches that differ and exchange those keys.
  • Adding capacity. A new node takes over some virtual points and streams the matching key ranges from the current owners before it starts serving them.
  • Hot partitions. A single very hot key still lands on N nodes. Callers can put a distributed cache in front for reads; for writes, split the key at the application level.

8. What breaks, and what you do about it

Failure modes worth naming
FailureEffectMitigation
One replica down for minutesFewer replicas answerSloppy quorum with hinted handoff keeps writes available; hints delivered on return
Node lost for goodIts ranges have one fewer copyOperator or automation removes it; ranges re-replicate to other nodes from surviving copies
Network partitionBoth sides may accept writes to the same keyVersion vectors expose conflicts after healing; or require strict quorums and refuse writes on the minority side
Deleted value comes backAn old replica missed the delete and repairs othersTombstones kept longer than the longest expected outage, removed only after repair
Clock skewLast-write-wins picks the wrong winnerVersion vectors, or hybrid logical clocks if timestamps are kept
Disk corruptionBad bytes servedChecksums per record; on mismatch, read from another replica and repair
Failure modes worth naming. Scroll sideways on a small screen.

9. Trade-offs to discuss

  • Leaderless or leader per partition. Leaderless replication (any replica accepts writes) stays available during failures but needs conflict handling. A leader per partition with consensus gives simple, consistent semantics at the cost of a failover pause and a write path through one node.
  • LSM tree or B-tree. LSM storage turns random writes into sequential ones and suits write-heavy loads, but reads may check several files and compaction uses disk bandwidth. B-trees read faster and more predictably but write in place.
  • Conflict rule. Last-write-wins is easy for callers and loses data under concurrency; version vectors keep everything and push merging to the application.
  • Strict or sloppy quorums. Sloppy quorums keep writes available during failures but weaken the overlap guarantee until hints are delivered.
  • Durability versus latency. Syncing the log on every write is safest; batching syncs every few milliseconds is much faster and risks the last few milliseconds of writes on a power loss of all replicas at once.

10. How to talk through it in the interview

Fictional example

Explaining what R + W > N really buys
Interviewer
You said N = 3, R = 2, W = 2. So reads are always up to date?
Candidate
A read always overlaps the replicas of the last write that was acknowledged, so it sees that version. But if two writes are concurrent, the read can see both, and if we used a sloppy quorum during an outage, the overlap can be with a stand-in node. So I would call it read-your-acknowledged-writes in normal operation, not linearizable.
Interviewer
What does the client do with two versions?
Candidate
For a cart, merge them and write back with both contexts, which tells the store the conflict is resolved.

A 45-minute plan for this prompt: 5 minutes on the API and the availability question, 5 on sizing, 5 on partitioning, 15 on replication, quorums and conflicts, 10 on recovery (hinted handoff, read repair, Merkle trees) and the storage engine, and 5 on trade-offs. If the interviewer cares more about the storage engine, swap the recovery time for LSM details such as compaction strategies.

  • Name N, R and W explicitly and say what each setting buys.
  • Never claim R + W > N makes the store strictly consistent.
  • Mention tombstones before the interviewer asks how deletes survive repair.

Practicing this design with Natively

Rehearse the quorum explanation until it is short and exact. During a mock interview on a call, Natively listens to both sides, writes the transcript as you talk and can offer points to cover when a question arrives; comparing them with your answer quickly shows whether you mentioned tombstones or sloppy quorums. It can also draw the ring and replica layout as a diagram when you ask. The transcript and notes are saved, so you can go back to the minute where the conflict explanation fell apart.

Questions people ask

What does R + W > N mean in a key-value store?

With N replicas, a write waits for W acknowledgements and a read for R replies. If R + W is greater than N, every read set overlaps every write set, so a read sees at least one copy of the latest acknowledged write. It does not make the store linearizable on its own.

How does a distributed key-value store handle conflicting writes?

Either last-write-wins, which keeps the copy with the higher timestamp and can silently drop a write, or version vectors, which detect concurrent writes and return both versions so the application can merge them. The choice depends on whether losing a write is acceptable.

What is hinted handoff?

When a replica is down, the coordinator writes to another healthy node with a hint naming the intended owner. When the owner comes back, the hint is delivered and deleted. It keeps writes available during short outages, at the cost of a weaker overlap guarantee until hints arrive.

Why do key-value stores use LSM trees?

An LSM tree appends writes to a log and an in-memory table, then flushes sorted immutable files and merges them in the background. That turns random writes into sequential ones, which suits write-heavy workloads. Bloom filters per file keep reads from checking every file.

Where to go next

Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.

Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.

Keep reading

Put it on your own machine.

A live-conversation assistant that runs locally. Your conversations stay on your machine.

macOS 12+ · Windows 10/11

© 2026 Natively AI Private Limited

Source-available under the Natively Personal Use Source License v1.0 · IP geolocation by DB-IP