InterviewDryRun
Lesson 4 · 21 min video · free

Design a Distributed Key-Value Store

The distributed key-value store is the question where interviewers check that you understand the building blocks every other design relies on: partitioning, replication, quorums, conflicts and failure handling. This lesson builds one from the ground up, explaining each choice the way you would in a 45-minute interview.

What you will learn

  • Decide between consistency and availability during partitions before designing anything else.
  • Consistent hashing with virtual nodes spreads keys evenly and moves few keys when nodes change.
  • Replicate each key to N nodes; read and write quorums R and W tune consistency against latency.
  • With R + W greater than N, a read always overlaps the latest write.
  • Concurrent writes need a conflict rule: last writer wins, version vectors, or merge.
  • Hinted handoff, read repair and Merkle-tree anti-entropy keep replicas converging after failures.

In this lesson

  1. The question
  2. Step 1: Requirements and the big trade-off
  3. Step 2: Back-of-the-envelope estimates
  4. Step 3: The interface
  5. Step 4: Splitting the data
  6. Step 5: Copying the data
  7. Step 6: Quorums and tunable consistency
  8. Step 7: When two writes collide
  9. Step 8: Detecting and healing failures
  10. Step 9: One write and one read, end to end
  11. Step 10: Storing data on one machine
  12. Step 11: The follow-up questions
  13. Recap

Short on time? Read the answer outline for design a Distributed Key-Value Store.

Practice this question with Max

The question

Welcome to lesson four of the InterviewDryRun system design course. Today we design a distributed key-value store: a database with just two operations, put a value under a key, and get the value back, spread across many machines so that it can hold more data and survive failures.

This question is different from the others. It is not about a product. It is about the machinery underneath every product. Partitioning, replication, quorums, conflicts, failure detection: every other design in this course leans on these ideas. So if you understand this lesson well, you will reuse it in every interview you do.

Max asks

“Design a distributed key-value store with tunable consistency, replication and failure handling.”

That is how Max, our AI interviewer, asks it. Notice the word tunable. The interviewer is telling you that there is no single right answer for consistency, and that they want a system where each caller can choose how strict to be. Keep that word in mind: it points straight at quorums, which will be the centre of our design.

The plan: requirements and the fundamental trade-off, then sizing and the interface. Then we will build the system one problem at a time: how to split the data, how to copy it, how reads and writes find agreement, what to do when two writes conflict, how to notice failures and heal from them, and how each machine stores data on disk. Then the follow-up questions.

Step 1: Requirements and the big trade-off

Requirements
  1. 01
    put(key, value), get(key)Values up to about 10 KB; keys are strings
  2. 02
    Huge and growingTerabytes to petabytes, so many machines
  3. 03
    Highly availableWrites keep working through failures
  4. 04
    Low latencySingle-digit milliseconds at the 99th percentile
  5. 05
    Tunable consistencyEach request chooses strict or fast

Start with the interface and its limits. Two operations: put and get, maybe delete. Ask about value sizes. Small values, say under ten kilobytes, are typical. If someone wants to store videos, that is an object store, which is a different design, and we will see it later in the course.

Then the qualities. The data is too big for one machine, so it must be partitioned. Machines fail every day at this scale, so the store must keep working through failures. And it must be fast, single-digit milliseconds, because it usually sits underneath a user-facing service.

And tunable consistency, straight from the question. Some callers need to read their own latest write, for example a shopping cart. Others are fine with slightly stale data in exchange for speed, for example a view counter. Our store should let each request choose.

CAP: what happens during a network partition
ChooseDuring a partitionGood for
Consistency (CP)some requests failbalances, locks, metadata
Availability (AP)all requests answer, maybe stalecarts, sessions, feeds

Now the trade-off every interviewer expects you to name. When the network splits the cluster into two halves that cannot talk to each other, a system has to choose. It can refuse requests on one side to stay consistent, or answer on both sides and risk them disagreeing. That is the CAP theorem in one sentence: during a partition, choose consistency or availability.

For this question, I would design for availability, with consistency that callers can tighten when they need it. That is the classic design for a large key-value store, and it matches the word tunable. Say clearly that this is a choice, and that a system for bank balances would choose differently. Also mention that even without partitions there is a trade-off between consistency and latency, because agreeing with more replicas takes longer.

Step 2: Back-of-the-envelope estimates

Sizing the cluster
Data100 TBbefore replication
Replicas3300 TB stored in total
Per nodeabout 3 TBso about 100 nodes
Traffic1 M ops / s70% reads, 30% writes
Per nodeabout 10,000 ops / scomfortable on SSDs

Let us size it, so the numbers guide the design.

Say one hundred terabytes of data. With three copies of everything, that is three hundred terabytes on disk. If each machine holds about three terabytes on fast SSDs, we need around a hundred machines. So the data is definitely partitioned, and we will regularly add and remove machines. That is going to matter for how we split the keys.

And traffic: a million operations a second, mostly reads. Spread over a hundred machines, and counting the replica reads and writes, each machine handles some tens of thousands of operations a second. Modern SSDs and a good storage engine handle that easily. So no single machine is special, and the challenge is coordination, not raw speed.

One more consequence of these numbers. With a hundred machines, and each one failing on average once every few years, something in the cluster fails every couple of weeks, and disks, network cards and whole racks fail on top of that. So failure is not an edge case for this design. It is the normal state of the system, and the design must treat a dead node as a routine event rather than an emergency.

Step 3: The interface

Client interface
put(key, value, context, consistency = QUORUM)
  → ok | timeout

get(key, consistency = QUORUM)
  → [ (value, context), ... ]   // usually one

delete(key, context)

consistency: ONE | QUORUM | ALL

Before the internals, pin down the interface, because two small details in it shape everything else. Put takes a key, a value and a consistency level. Get takes a key and a consistency level. So far, obvious.

The first detail is the context. Every get returns, along with the value, an opaque version context, and the client passes it back on its next put. That is how the store knows which version the client was looking at when it made its change, and so whether the new write replaces the old one or happens alongside a different change. We will use this when we talk about conflicts.

The second detail: get can return more than one value. Usually it returns one, but if two clients wrote at the same time and the store cannot tell which should win, it returns both and lets the client merge them. Putting this in the interface early tells the interviewer you already know where the design is heading, and it avoids having to change the interface halfway through the interview.

Step 4: Splitting the data

How to choose a key's machine
ApproachProblem
hash(key) mod Nchange N and almost every key moves
Key rangeshot ranges; needs rebalancing
Consistent hashingfew keys move; virtual nodes even it out

First problem: given a key, which machine stores it? The naive answer is to hash the key and take it modulo the number of machines. It spreads keys evenly, but the moment we add a machine, N changes, and nearly every key maps somewhere new. At a hundred terabytes, moving nearly everything because one machine was added is unacceptable.

Splitting by key ranges, a to c on one machine, d to f on the next, is great for range scans, but sequential keys pile onto one range, and you need a component that splits and moves ranges. It is a valid design, used by several databases. But for a pure key-value store with random access, there is a simpler answer.

Consistent hashing. Picture the output of a hash function as a ring, from zero all the way round back to zero. Each machine is placed on the ring at the hash of its name. Each key is hashed onto the ring too, and it belongs to the first machine you meet walking clockwise. When a machine is added, it takes over only the keys between itself and its neighbour. About one N-th of the data moves, and nothing else.

Virtual nodes
  1. 01
    Many points per machineEach machine appears 100 to 256 times on the ring
  2. 02
    Even loadRandom gaps average out
  3. 03
    Spread recoveryA dead node's keys move to many machines, not one
  4. 04
    Weighted capacityA bigger machine gets more points

Plain consistent hashing has one flaw. With few machines, the gaps on the ring are uneven, so some machines own far more keys than others. The fix is virtual nodes: each machine appears at many points on the ring, a hundred or more, so the random gaps average out.

Virtual nodes give us two more gifts. When a machine dies, its many small slices are taken over by many different machines, so the recovery work is spread across the cluster instead of landing on one neighbour. And a machine with twice the disk can simply get twice the virtual nodes. Say all three benefits, because each one is a reason interviewers like this answer.

Step 5: Copying the data

Each key lives on N = 3 nodes
replica 1replica 2replica 3CLIENTClientSERVICECoordinatorany nodeSTORENode Aowner on ringSTORENode Bnext on ringSTORENode Cnext after that

Second problem: machines die, so every key must live on more than one. The standard approach: a key is stored on the first N distinct machines clockwise from its position on the ring. N is usually three. That list of machines is called the key's preference list.

Skip virtual nodes that belong to a machine already on the list, so the three copies are on three different physical machines. Better still, make them land in three different racks or availability zones, so one power failure cannot destroy all three copies at once.

Who handles a request? In this design there is no leader. Any node can receive a request from a client and act as the coordinator for it. It looks up the key's preference list, which every node knows, and sends the request to those replicas. This is called leaderless replication, and it is what lets us stay available: there is no single leader whose failure blocks writes.

Contrast it with leader-based replication, where one replica takes all the writes for a partition and copies them to followers. That gives simpler consistency, but if the leader fails, writes stop until a new one is elected. For an availability-first store, leaderless fits better. Mention both, and say why you chose.

Step 6: Quorums and tunable consistency

Quorums with N = 3
Wwrites must reachW replicas before we say OK
Rreads must hear fromR replicas before we answer
R + W > Noverlapa read always sees the latest write
W = 2, R = 2balancedconsistent, tolerates 1 failure
W = 1, R = 1fastestmay read stale data
W = 3, R = 1fast readswrites fail if any replica is down

Now the heart of the question: how do we make consistency tunable? With quorums. There are three numbers. N is how many replicas each key has. W is how many replicas must confirm a write before we tell the client it succeeded. And R is how many replicas we wait for on a read.

The key rule: if R plus W is greater than N, then every read overlaps with every successful write on at least one replica. With N of three, W of two and R of two, any two replicas you read must include at least one of the two that accepted the latest write. Draw three boxes and show the overlap, because it makes the idea obvious.

The two-and-two setting is the balanced default. It reads the latest value, and still works with one replica down. With W of one and R of one, everything is fastest, but a read can miss a recent write. That is fine for a view counter. And W of three, R of one makes reads fast but writes fail whenever any replica is down.

So tunable consistency simply means letting each request choose its R and W. A shopping cart asks for quorum reads and writes. A cache of recommendations asks for one and one. Same cluster, different guarantees. That is exactly what the question asked for.

How does a read pick the latest value when replicas disagree? Every value is stored with a version. The coordinator collects R answers and returns the newest. Which raises the obvious question: what does newest mean, and what if two writes happened at the same time? That is the next step.

One honest caveat interviewers appreciate: quorums with R plus W above N are not the same as strict linearisability. With sloppy quorums, concurrent writes and replicas that fail mid-write, there are edge cases where a read can still see an older value. If a caller needs strict guarantees, like a lock or a compare-and-set, it needs consensus on a single leader, not just quorums. Saying that shows you know where the model ends.

Step 7: When two writes collide

Resolving concurrent writes
ApproachHowCost
Last writer winshighest timestamp winssilently loses a write; clocks skew
Version vectorstrack versions per replicaclients merge siblings
Mergeable types (CRDTs)counters, sets that mergeonly for some data types

In a leaderless system, two clients can write the same key at nearly the same time, through two different coordinators, and the replicas can end up with different values. We need a rule for which one wins, or how to combine them.

The simplest rule is last writer wins: attach a timestamp to each write, and keep the highest. Many systems do this, and it is fine for data where losing one of two concurrent writes does not matter, like a user's last-seen time. But it does lose data silently, and machine clocks are never perfectly in sync, so the write that really came last can lose. Say both problems.

The more careful approach is version vectors. Each value carries a small list of counters, one per replica that has coordinated a write to it. Comparing two vectors tells you whether one value descends from the other, in which case the newer simply wins, or whether they were written concurrently, in which case neither should win automatically.

When writes are concurrent, the store keeps both versions, called siblings, and returns both on the next read. The client, which understands the data, merges them and writes the result back. The classic example is a shopping cart: if two devices added different items at the same time, merge by taking both sets of items. Nothing is lost.

The third option is to store data types that merge automatically, like counters where each replica tracks its own increments, or sets with add and remove markers. These are called conflict-free replicated data types. They are elegant, but only work for certain shapes of data. A good answer: last writer wins by default, version vectors and sibling merging for data that cannot lose writes.

Step 8: Detecting and healing failures

Failure handling
  1. 01
    GossipNodes share who is alive, every second
  2. 02
    Sloppy quorum + hinted handoffWrite to a stand-in, deliver later
  3. 03
    Read repairFix stale replicas found during reads
  4. 04
    Anti-entropy with Merkle treesCompare and sync replicas in the background

Machines fail, so let us go through how the store notices and heals. First, how do nodes know who is alive, without a central monitor that could itself fail? Gossip. Every second, each node exchanges its view of the cluster with a few random others: who is up, with a heartbeat counter for each. News spreads through the whole cluster in a few rounds, and a node whose heartbeat stops increasing is marked as suspect.

Now, a write arrives and one of the three replicas is down. With a strict quorum, if two of three is enough, we are fine. But to stay available even when more replicas are unreachable, we can use a sloppy quorum: write to the next healthy node on the ring instead, with a note, a hint, saying which node this data really belongs to. When the real owner comes back, the stand-in hands the data over. That is hinted handoff.

Second healing mechanism: read repair. When a coordinator reads from several replicas and notices one of them returned an older version, it writes the newest version back to that replica. Popular keys therefore heal themselves quickly, simply by being read.

But keys that are rarely read could stay stale for ever. So a background process compares replicas. Comparing every key would be far too slow, so each replica builds a Merkle tree: a tree of hashes, where each leaf is the hash of a small range of keys and each parent is the hash of its children. Two replicas compare the root hashes. If they match, they are identical. If not, they walk down only the branches that differ, and sync just those few ranges. This is called anti-entropy.

And a permanent failure, a disk that will never come back, is handled by an operator or an automated system removing the node from the ring. Its virtual nodes are taken over by many other machines, which copy the data from the remaining replicas. Because of virtual nodes, this copying is spread across the whole cluster and finishes quickly.

Step 9: One write and one read, end to end

A quorum write, then a quorum read
  1. 01
    1. Client sends put to any nodeThat node becomes the coordinator
  2. 02
    2. Coordinator finds the preference listHash the key, walk the ring, three nodes
  3. 03
    3. Sends to all three, waits for twoThe third may land later
  4. 04
    4. Read asks all three, waits for twoReturns the newest version
  5. 05
    5. Stale replica gets fixedThe coordinator writes back the newest

Let us put the pieces together and trace one request, because walking through a request end to end is the best way to show the interviewer the design really works. A client sends a put to any node, often chosen by a client library that already knows the ring. That node becomes the coordinator.

The coordinator hashes the key, walks the ring and finds the three replicas. If it is one of them itself, it writes locally too. It also attaches a new version to the value, built from the context the client sent.

It sends the write to all three replicas at once, not just two, and answers the client as soon as two have confirmed. The third usually confirms a moment later. If the third is slow or down, nothing waits for it, and the repair mechanisms we just discussed will bring it up to date.

Now a read with quorum two. The coordinator asks the replicas, takes the first two answers, and compares their versions. If they agree, it returns the value. If one is older, it returns the newer one and, in the background, writes the newer version to the stale replica. A useful latency trick: ask all three and use the fastest two, so one slow machine never slows down the read.

Step 10: Storing data on one machine

The write and read path on one node
12flush when fullCLIENTWriteSTORECommit logappend only, on diskCACHEMemtablesorted, in memorySTORESSTablessorted files, immutableCACHEBloom filtersskip files without the key

Finally, what happens inside one machine. Our store is write heavy and needs fast writes, so the usual choice is a log-structured merge tree. A write is first appended to a commit log on disk. Appending is the fastest thing a disk can do, and the log makes sure we survive a crash.

Then the write goes into a memtable, a sorted structure in memory. The client gets its acknowledgement at this point. No random disk writes have happened at all.

When the memtable fills up, it is written to disk in one go as a sorted, immutable file, often called an SSTable. Over time there are many such files, so a background process called compaction merges them, keeping only the newest version of each key and dropping deleted ones.

Reads check the memtable first, then the files from newest to oldest. To avoid opening every file, each file has a Bloom filter, a tiny structure that can say for certain that a key is not in that file. So most reads touch only one file on disk. Mention the trade-off: these engines give fast writes and good reads, at the cost of compaction work in the background.

Deletes deserve a sentence. You cannot simply remove a key from immutable files on several replicas, or a replica that missed the delete will bring the key back during repair. So a delete writes a marker, called a tombstone, which wins over older values and is only purged after every replica is known to have it. Forgetting about tombstones is a classic way for deleted data to come back from the dead.

Step 11: The follow-up questions

Max asks

“A single key becomes extremely popular. How does your store cope?”

Reads can be spread across all N replicas, and with R of one, any replica can answer, which triples capacity. For more, a cache in front of the store, or in the calling service, absorbs a hot key. Hot writes are harder, because every replica must take every write. The usual fix is at the data model level: split one hot key into several, for example a counter into ten sub-counters that are summed on read.

Max asks

“How would you add ten new machines to a running cluster without downtime?”

Add them one at a time. Each new node takes over its virtual nodes on the ring, and streams the data for those ranges from the existing replicas while still serving traffic. During the move, writes go to both the old and new owners, so nothing is missed, and only when the copy is complete does the new node start answering reads. Throttle the streaming so it does not hurt live traffic.

Max asks

“A client writes with W of two and gets a timeout. Did the write happen?”

Maybe. A timeout means we did not hear two acknowledgements in time, but one or more replicas might have stored it. So the client must treat the result as unknown. The safe pattern is to make writes idempotent, for example with a request id or a version check, and retry. Repair will spread a partial write to all replicas eventually, so a retried idempotent write and a partial one end in the same state.

Max asks

“How would you run this store across two regions on different continents?”

Keep each key's three replicas spread across zones within a region, and add asynchronous replication to the other region. Quorums stay local, so latency stays low, typically with a consistency level like local quorum. Cross-region copies arrive a fraction of a second later, and conflicts between regions are resolved with the same versions and merge rules as before. A caller that truly needs cross-region agreement can ask for a global quorum, and pay a cross-continent round trip on every request.

Max asks

“When would you not use this design?”

When the data needs transactions across keys, or strict ordering like a bank ledger, or rich queries. Leaderless, eventually consistent stores are great for high-volume, simple lookups like sessions, carts and profiles. For money, I would use a strongly consistent database with consensus on each partition, and accept the latency cost and lower availability during partitions.

Recap

Your 45 minutes
  1. 01
    0 to 5: requirements and CAPPut and get, huge, available; choose AP, tunable
  2. 02
    5 to 10: estimates300 TB on 100 nodes, 1 M ops a second
  3. 03
    10 to 25: partition and replicateConsistent hashing, virtual nodes, N = 3, quorums
  4. 04
    25 to 35: conflicts and failuresVersions, gossip, hinted handoff, repair, Merkle trees
  5. 05
    35 to 45: storage and follow-upsCommit log, memtable, SSTables, tombstones

Let us map it onto forty-five minutes. Five minutes of requirements, ending with the CAP choice: available, with tunable consistency. Five minutes of estimates, showing it is a hundred machines and a million operations a second.

Fifteen minutes on partitioning and replication: consistent hashing with virtual nodes, N copies along the ring, any node as coordinator, and quorums with R plus W greater than N for strong reads.

Ten minutes on conflicts and failures: last writer wins or version vectors, gossip, hinted handoff, read repair and Merkle trees. And the last ten minutes on the storage engine and follow-ups. If you can explain why each mechanism exists, rather than listing them, you have given a strong answer, and you will find these same ideas in almost every other design in this course.

This question has a lot of named mechanisms, and the risk is reciting them without connecting them. Practicing out loud is how you learn to tell it as one story. You can practice this exact question with Max, our AI interviewer, at interview dry run dot com. It is free to start, and you get a scored report with what to fix. The written lesson, with every diagram, is on the site too. See you in lesson five.

Now say it out loud

Watching an answer is not the same as giving one. Max asks this exact question, pushes back when an answer is vague and keeps time, then scores you per skill.

Practice with Max

Free: a 5-minute voice round and unlimited typed drills, with scored feedback. No card, and your camera is never recorded.