SDSystem DesignConcepts to case studies
System DesignDSA
x
0/311
Part 1: Foundations
Part 2: APIs and Communication
Part 3: Caching
Part 4: Data and Storage
Part 5: Architecture
Part 6: Distributed Systems
Part 7: Advanced Data Topics
Part 8: Operations and Security
Part 9: Estimation and Interview Method
Part 10: Case Studies
  • Design a URL Shortener
  • Design Pastebin
  • Design a Rate Limiter
  • Design a Unique ID Generator
  • Design a Key-Value Store
  • Design a Scalable Parking System (Smart Parking)
System Design/Case Studies/Easy
Interview case study

Design a Key-Value Store

Build a simple, fast, always-on store like Dynamo or Redis: partitioning, replication and consistency.

⏱ 32 min readEasy case studyIntermediate23 cross-questionsHas visualizer
Prompt60-sec answer45-min plan1 Clarify2 Estimate3 API + Data4 Design5 Deep dives6 Scale7 Wrap upCross-questionsVariationsScoringMistakesCheat-sheet

StartThe prompt and what is really being tested

The interviewer says

“Design a key-value store.”

It is short on purpose. Your first job is to make it specific.

What they checkWhy it matters
Starting simple, then distributingA strong candidate builds one server first (hash table, log, snapshot), says exactly why it stops working, and only then spreads it out.
Knowing the building blocksPartitioning (consistent hashing), replication, quorums, gossip, a storage engine. The question is about assembling known parts in a sensible order.
The consistency and availability trade-offYou must pick a side (CAP), explain it with N, R and W, and say what a client may see when things go wrong.
Failure handling in layersTemporary failure, permanent failure, and stale replicas each have a different fix: hinted handoff, anti-entropy, read repair.
Conflict handlingTwo writers, one key, no shared clock. Last-write-wins, vector clocks and CRDTs each lose something, and you should say what.

TL;DRThe whole design in 60 seconds

Think of a giant, always-on dictionary spread over many machines. Any node can act as the coordinator for a request. It hashes the key onto a consistent-hashing ring and sends the request to the next N = 3 nodes on the ring, which hold the copies. You choose how many of those must answer: W for a write and R for a read.

  • Partitioning: consistent hashing with virtual nodes, so adding a node moves only about 1/N of the data.
  • Replication and consistency: N = 3 copies in different zones, tunable R and W. R + W > N gives overlap and fresh reads in the normal case. W = 1 is fast, W = N is durable.
  • Conflicts: concurrent writes are possible, so each value carries a version (a vector clock, or a timestamp for last-write-wins). Reads merge versions and write the winner back (read repair).
  • Failures: gossip finds dead nodes. A short outage is covered by a sloppy quorum and hinted handoff. A long one is repaired by comparing Merkle trees (anti-entropy).
  • On one node: a commit log for durability, an in-memory table, and sorted files on disk (an LSM tree) with Bloom filters so a read skips files that cannot hold the key.
  • The choice: this is an AP design. It stays available during a partition and reconciles later, so reads can be briefly stale.
💡How to use this page
Read the 60-second answer first. Then work through steps 1 to 7 in order, and try each step yourself before reading the model answer. Finish with the cross-questions: say your answer out loud, then open the model one.

PlanA 45-minute plan

4
3
4
8
16
7
3
Minutes per step (total 45). A guide, not a rule: move time to the part the interviewer cares about.
StepMinutesWhat to get done
1. Clarify4Value size, consistency needs, availability, scale. Rule out range queries and transactions.
2. Estimate3Data size, node count, operations per second per node, ring tokens.
3. API and data4get, put, delete. The version or context that travels with each value.
4. High-level design8Ring, coordinator, N replicas, gossip, and the storage engine on each node.
5. Deep dives16Partitioning, quorums and conflicts, failure handling, then the single-node write and read path.
6. Scale and failures7Hot keys, rebalancing, zone loss, monitoring, security.
7. Wrap up3Recap, trade-offs, what you would add next.

Step 1Clarify requirementsabout 4 min

🤔
Pause. Try it yourself first
You have 60 seconds. Write down five questions that would change the design. Hint: think about how big a value is, how fresh a read must be, what happens when two people write at once, and whether anyone wants range queries or transactions.

Questions to ask, and why

AskWhy you ask itTypical answerHow it changes the design
What do we store: how big is a key and how big is a value?Small values fit a simple design. Big values (megabytes) need chunking and a different path.Keys up to 256 bytes. Values up to a few hundred KB, about 1 KB on average.Small values: store them inside the LSM files. Cap the size, and send blobs to object storage instead.
Is it read-heavy or write-heavy?Decides cache use, compaction cost, and which quorum values make sense.About 80% reads and 20% writes.Reads matter most: Bloom filters, row cache, and a read-friendly compaction strategy.
Must a read always see the latest write (strong consistency), or is a short delay fine?This single answer picks the whole family of designs: leader and consensus, or leaderless and eventual.A short delay is fine. Availability matters more. Let callers tune it per request.Leaderless replication with tunable quorums (Dynamo style), not a consensus group per key.
What happens when two clients write the same key at the same time?Forces the conflict question: lose one, or keep both and merge.It is rare. Do not lose data silently if we can help it.Version every value. Last-write-wins is the simple default, vector clocks or CRDTs where merging matters.
What availability and latency do we need?Sets the replica count, zone spread, and how many nodes must answer.99.99% available. p99 under 10 ms for a read inside one region.Three replicas across three zones. The coordinator must not wait for the slowest node.
How much data, and how fast does it grow?Decides the node count, and whether adding nodes must be easy.About 100 TB now, growing 10% a month.Hundreds of nodes. Adding capacity must be a routine, online job.
Do we need range scans, secondary indexes, or multi-key transactions?Hash partitioning scatters neighbouring keys, so range scans and joins are hard.No. Only get, put and delete by exact key.Hash partitioning is fine. Say clearly what we give up.
Single region or multi-region?Cross-region latency changes how many copies you wait for.One region with three zones first. Multi-region is a later phase.Replicas spread across zones now. Design the preference list so a data-centre layer can be added.
How durable must a write be once it is acknowledged?Decides whether an ack means ‘in memory’, ‘on disk’ or ‘on several disks’.A successful write must survive the loss of one node.Write to the commit log on W replicas before acknowledging. W is at least 2 for important data.
Do keys ever expire? Do we need TTLs?Expiry means tombstones and cleanup in the storage engine.Optional TTL per key.Store an expiry time with the value. Expired data is dropped during compaction.

Write the scope on the board

Functional (must do)
  • •get(key) returns the value (and a version)
  • •put(key, value) creates or replaces a value
  • •delete(key) removes a key
  • •Optional TTL per key
  • •Per-request choice of consistency level (how many replicas must answer)
Non-functional (how well)
  • •Highly available: 99.99%, reads and writes keep working when a node or a zone is down
  • •Low latency: p99 under 10 ms for get and put inside one region
  • •Scales out: add nodes online, and about 100 TB of data growing 10% a month
  • •Durable: an acknowledged write survives the loss of one node
  • •Eventual consistency by default, with tunable consistency per request
Out of scope (say it)
  • •Range queries and secondary indexes
  • •Multi-key transactions and joins
  • •Multi-region replication (a later phase)
  • •Authentication and billing details
🎤
Say it out loud
“Let me confirm the scope. We store keys up to 256 bytes and values around 1 KB, with a cap of a few hundred KB. It is read-heavy, about 80 to 20. We want 99.99% availability, p99 under 10 ms, and about 100 TB of data growing 10% a month. A read may be briefly stale, and callers can ask for stronger consistency per request. We only do get, put and delete by exact key. No range queries, no transactions, single region for now. Does that match?”

Step 2Estimate the scaleabout 3 min

🤔
Pause. Try it yourself first
On paper: how many items is 100 TB? How many nodes with 3 copies? How many operations per second does each node see once every write goes to three nodes?

Assumptions (say them first)

AssumptionValue
Data stored (one copy)100 TB
Average item (key + value + overhead)1 KB
Replicas per key (N)3
Usable data per node2 TB (disks kept about half full so compaction has room)
Peak client operations1 million per second, 80% reads and 20% writes
Read quorum / write quorumR = 2, W = 2
Bloom filter size10 bits per key (about 1% false positives)
Virtual nodes per machine256
Data growth10% a month

The arithmetic, line by line

WhatMathsResult
Items stored (one copy)100 TB ÷ 1 KB = 10^14 ÷ 10^3100 billion items
Data with 3 copies100 TB × 3300 TB
Nodes needed for the data300 TB ÷ 2 TB per node150 nodes
Peak reads and writes per second1M × 80% and 1M × 20%800,000 reads and 200,000 writes
Replica operations per secondwrites × 3 replicas + reads × 2 (R = 2)600,000 + 1,600,000 = 2.2 million
Replica operations per node2.2M ÷ 150 nodesabout 14,700 per second (client ops: 6,700)
Write bandwidth, client side200,000 × 1 KB200 MB per second
Write bandwidth inside the cluster200 MB/s × 3 copies, ÷ 150 nodes600 MB/s total, about 4 MB/s per node
Read bandwidth out800,000 × 1 KB800 MB/s, about 6.4 Gbit/s
Items held by one node100 billion × 3 ÷ 1502 billion items
Bloom filter memory per node2 billion × 10 bits ÷ 8about 2.5 GB
Ring tokens150 nodes × 256 virtual nodes38,400 tokens
Data moved when adding one node300 TB ÷ 151about 2 TB (0.66% of the data)
Growth to plan for10% of 100 TB = 10 TB raw; × 3; ÷ 2 TB30 TB, about 15 new nodes a month
Availability of one key with R = W = 23p²(1−p) + p³, with p = 0.999 per nodeabout 99.9997% (if failures are independent)
What the numbers tell us about the design
  • •150 machines is a real cluster. Adding and removing nodes is a daily job, so the design must make it cheap (consistent hashing).
  • •Each client write becomes 3 replica writes. Replication multiplies the write load, so storage engine write speed matters most. That points to an LSM tree.
  • •Each node holds 2 billion keys. Without Bloom filters, one read could touch many files on disk. With them, most reads touch one.
  • •At 99.9% per node, R = W = 2 still gives about four nines for a key. That is why quorums work, if copies sit in different failure domains.
  • •Growth of about 15 nodes a month means rebalancing is constant. Moving 0.66% of the data per new node is the number that makes it safe.
🎤
Say it out loud
“100 TB at 1 KB is 100 billion items. With three copies that is 300 TB, and at 2 TB per node, 150 nodes. At a peak of a million operations a second, 80% reads, every write becomes three replica writes and every read touches two, so the cluster does about 2.2 million replica operations a second, roughly 15,000 per node. Each node holds about 2 billion keys, so a Bloom filter at 10 bits per key costs 2.5 GB. These are assumptions. The point is that we need a few hundred machines, write-friendly storage, and cheap rebalancing.”

Step 3Define the API and the data modelabout 4 min

🤔
Pause. Try it yourself first
Write the three calls. What must travel with a value so that two concurrent writes can be told apart? What does a read return if replicas disagree?

Endpoints

MethodPathRequestResponseNotes
GET/v1/kv/{key}?consistency=quorumnone200 { value(s), context }context is an opaque version (a vector clock). If versions conflict, several values are returned. 404 if missing. consistency can be one, quorum or all.
PUT/v1/kv/{key}{ value, context?, ttl?, consistency? }200 { context }Send back the context from the read you based this write on. 503 if fewer than W replicas answered in time. Idempotent: the same body and context can be retried.
DELETE/v1/kv/{key}{ context? }204Writes a tombstone (a marker), it does not erase the data at once. Idempotent.

Data model

Stored per keyTypeNotes
keybytes, up to 256Hashed to a 128-bit position on the ring. The hash decides placement.
valuebytes, up to a few hundred KBOpaque to the store. Big blobs belong in object storage.
version (context)vector clock, or a timestampLets the store tell ‘newer’ from ‘concurrent’.
tombstone flagbooleanA delete is a write that says ‘this key is deleted’. Needed so a delete wins over an old copy.
expires_attimestamp, optionalDropped during compaction after it passes.
Other stateHoldsWhere
Ring membershipWhich nodes exist, their tokens, and who is upEvery node, spread by gossip
Commit logEvery write, in order, for crash recoveryOne log per node, on its own disk
HintsWrites held for a node that was downThe stand-in node, for a limited time
Merkle treesHashes of key ranges, for comparing replicasEach node, per range it owns
What a get returns when two writes conflicted
GET /v1/kv/cart:42
200 {
  "values": [
    { "value": "milk, eggs",  "context": "[A:2, B:1]" },
    { "value": "milk, bread", "context": "[A:1, C:1]" }
  ]
}
// The client merges them (milk, eggs, bread) and PUTs the result
// with the combined context, which settles the conflict.
📝Which store, and why
The data model is just key to value, so there is nothing to choose between SQL and NoSQL. The thing to choose is the storage engine on each node. Writes are three times as heavy as client writes (replication), so use an LSM tree: append to a log and a memory table, flush to sorted files, merge later. A B-tree would do random disk writes for each update and is a poorer fit here. Say the choice and move on.
🎤
Say it out loud
“Three calls: get, put and delete by key. A get returns the value and an opaque context, which is a version. If replicas held conflicting versions, it returns all of them. A put sends back the context it read, so the store can tell an update from a conflicting write. A delete writes a tombstone. Each node stores data in an LSM tree, because every client write becomes three replica writes and an LSM tree turns them into sequential disk writes.”

Step 4Draw the high-level designabout 8 min

🤔
Pause. Try it yourself first
Draw the ring, one client request, and the three nodes that hold a key. Then draw what is inside one node. Where does gossip fit?
Key-value store: high-level design
👤Clientlibrary or any node
→↓get / put
🎛️Coordinatorhashes key, picks replicas
→↓N = 3 in parallel
Replicas (3 zones)
🗄️Node A (zone 1)copy 1
🗄️Node B (zone 2)copy 2
🗄️Node C (zone 3)copy 3
The ring
🔄Consistent hashing256 virtual nodes each
key → position → next 3 distinct nodes
Membership and repair
🗣️Gossipwho is alive, who owns what
🩹Hinted handoffshort outages
🌳Merkle treeslong outages, anti-entropy
Inside one node
📝Commit logdurable, append-only
↓
⚡Memtablesorted, in memory
↓flush
📚SSTablessorted files + Bloom filters
Any node can be the coordinator. The key picks 3 replicas on the ring. Gossip keeps every node's view of the ring up to date.
ComponentWhat it does
Client library or coordinatorAny node can coordinate a request. It hashes the key, finds the replicas, sends the request to all of them, and answers when enough have replied.
Consistent-hashing ringDecides which nodes own which keys. Virtual nodes spread each machine over many small pieces of the ring, so load is even and moving data is cheap.
Replicas (N = 3)The next 3 distinct machines on the ring, picked from different zones. Together they are the preference list for the key.
Quorum settings (R and W)How many replicas must answer a read or a write. Tunable per request.
GossipEvery second or so, each node tells a few random peers what it knows about the cluster. News of a join or a failure spreads to everyone in a few seconds, with no central server.
Hinted handoffIf a replica is down, another node holds the write and a note, and hands it over when the replica returns.
Anti-entropy with Merkle treesA background job compares hashes of key ranges between replicas and copies only what differs.
Storage engine (per node)Commit log for durability, memtable for speed, SSTables on disk, Bloom filters to skip files, compaction to merge them.
Write path (follow one request)
  1. The client sends put(key, value, context) to any node, which becomes the coordinator.
  2. The coordinator hashes the key to a position on the ring and finds the preference list: the next 3 distinct nodes in different zones.
  3. It stamps the value with a new version (it bumps its own entry in the vector clock, or adds a timestamp).
  4. It sends the write to all 3 replicas in parallel.
  5. Each replica appends the write to its commit log (durable), then puts it into its memtable, and replies.
  6. If a replica is down, the coordinator hands the write to a stand-in node with a hint (a sloppy quorum).
  7. When W replicas (or stand-ins) have replied, the coordinator answers success. The rest finish in the background.
Read path (follow one request)
  1. The client sends get(key) to any node, which becomes the coordinator.
  2. The coordinator finds the same 3 replicas from the ring and sends the read to all of them.
  3. Each replica checks its memtable, then uses Bloom filters to find which SSTables might hold the key, newest first, and reads them.
  4. The coordinator waits for the first R replies (the rest are ignored if slow).
  5. It compares the versions. One newest version means that is the answer. Conflicting versions are all returned to the client to merge.
  6. If a replica returned an older version, the coordinator writes the newest back to it (read repair), after answering.
🎤
Say it out loud
“Here is the picture. Any node can coordinate. It hashes the key onto a consistent-hashing ring with virtual nodes, and sends the request to the next three nodes in different zones. For a write it waits for W acknowledgements, for a read for R. Gossip tells every node who is alive. If a node is down, a stand-in keeps the write with a hint. In the background, Merkle trees repair what hints missed. Inside each node there is a commit log, a memtable and sorted files with Bloom filters, which is an LSM tree.”

Step 5Deep dive into the hard partsabout 16 min

🧠The pattern for every deep dive
Problem → options → pick one → say why → say what it costs. Interviewers score the reasoning more than the choice.
5.1

Partitioning and replication

The problem: 100 billion keys must be spread over 150 machines so that load is even, a key can be found without asking a central server, and adding or removing a machine moves very little data.

OptionHow it worksGoodBad
hash(key) mod number of nodesTake the hash and the remainder after dividing by the node count.Trivial. Even spread.Adding one node changes the divisor, so almost every key moves. Unusable at this size.
Consistent hashing, one token per nodePut nodes and keys on a ring. A key belongs to the next node clockwise.Adding a node moves only the keys next to it, about 1/N of the data.With few tokens, load is uneven and a new node takes load from just one neighbour.
Consistent hashing with virtual nodesEach machine owns many small tokens (say 256) spread around the ring.Even load. A new node takes a little from many nodes, in parallel. Strong machines can own more tokens.More ring metadata. Replica choice must skip tokens of the same machine.
Fixed partitions assigned by a coordinatorCut the key space into, say, 10,000 fixed partitions and keep a table of which node owns which.Simple to reason about. Used by Kafka, Elasticsearch and others.Needs a metadata service that must be highly available, and a planned move for each change.
Pick
Consistent hashing with virtual nodes, and replicas on the next distinct nodes in different zones

A key is hashed to a position on the ring. The first token clockwise owns it, and the next two distinct machines (skipping tokens of the same machine, and preferring different zones) hold the other copies. That list of three is the preference list. Every node can compute it from the ring it learned by gossip, so there is no central lookup on the hot path.

With 150 machines and 256 tokens each, the ring has 38,400 tokens. Adding a machine adds 256 small pieces, taken a little from many neighbours, so about 2 TB moves (0.66% of 300 TB) and it is pulled from many nodes at once. That is what makes monthly growth of 15 nodes routine. See the Consistent Hashing topic for the basics.

EventWhat happensData moved
Node joins (mod N)Almost every key gets a new ownerabout 99% of the data
Node joins (consistent hashing, virtual nodes)It takes tokens from many neighbours, and streams their key rangesabout 1/151 of the data (2 TB)
Node dies for goodIts ranges are re-copied to the next node on the ring, from the other two replicasits share only (2 TB), from many sources
Zone lostEvery key has a copy in the other two zones (rack and zone awareness)nothing moves at once, repair runs in the background
💡Say this about zones
Placing the three replicas on the next three nodes is not enough: they could all be in one rack. Walk the ring and skip nodes that share a rack or zone with a replica already chosen. This is what lets the system survive losing a whole zone.
🎤
Say it out loud
“I would use consistent hashing with virtual nodes: 256 tokens per machine. The key's position picks the first replica, and I walk clockwise to pick two more, skipping machines in the same zone. So every node can work out where a key lives from the ring it learned by gossip. Adding a machine moves about one 150th of the data, pulled from many nodes at once, so growth is a routine, online job.”
5.2

Consistency, quorums and conflicts

The problem: Three copies of a key can differ. We need to say what a client sees, what happens when two clients write at once, and how copies come back together.

OptionHow it worksGoodBad
One leader per key (consensus)Writes go through a leader, copied to a majority with Raft or Paxos (etcd, Spanner style).Strong consistency. No conflicts to merge.A partition or leader loss makes the minority side unavailable. Higher write latency.
Leaderless with quorums (R + W > N)Write to W of N replicas, read from R. If R + W > N, the sets overlap.Highly available. Tunable per request. No leader to fail over.Not linearizable in the general case (see below). Conflicts must be resolved.
Last-write-wins (a timestamp)Each write carries a timestamp. The highest timestamp wins.Simple. No client work. Used by Cassandra.Clocks differ, so a ‘later’ write can lose to an ‘earlier’ one, and one of two concurrent writes is lost silently.
Vector clocks, client mergesEach value carries a counter per writer. A read returns all concurrent versions, and the client merges them.Nothing is lost silently. Detects true concurrency.More work for clients. Clocks can grow, so they are trimmed. Used by Dynamo and Riak.
CRDTsData types (counters, sets) that merge to the same result on every replica.Automatic, safe merge. No client code.Only for certain data shapes. Metadata overhead.
Pick
Leaderless with tunable quorums (N = 3, R = 2, W = 2 by default), and vector clocks with read repair

We chose availability. With N = 3, W = 2 and R = 2, R + W = 4 > N = 3, so any read set of 2 and any write set of 2 share at least one node. A read that meets a replica holding the latest write sees it. A client can ask for W = 1 (fastest, may lose data if that one node dies), W = 3 (every copy, an unavailable write if any node is down), or R = 1 (fastest, may be stale). See Quorum (R + W > N) for the maths.

Be honest that quorum overlap is not linearizability. A write that fails after reaching only one replica can still show up in later reads. A sloppy quorum (writes accepted by a stand-in) can break the overlap until the hint is handed over. Two concurrent writes can both succeed. Reads may see them in different orders on different replicas. Each version carries a vector clock, so the coordinator can tell "this one is newer" from "these two are concurrent", and it returns both in the second case.

SettingMeaningUse it for
N = 3, W = 2, R = 2Overlap guaranteed in the normal case. Survives one node down for reads and writes.The default
N = 3, W = 1, R = 1Fastest. Reads can be stale. A write can be lost if its one node dies before copying.Caches, view counters, anything you can recompute
N = 3, W = 3, R = 1Every copy gets each write, so a read from any one node is fresh. Writes fail if any node is down.Read-heavy data that must be fresh
N = 3, W = 1, R = 3Fast writes, slow and thorough reads.Write-heavy data that is rarely read
Vector clocks: two concurrent writes
start         value "milk"            clock [A:1]
client 1 via A   adds eggs  -> "milk, eggs"    clock [A:2]
client 2 via B   adds bread -> "milk, bread"   clock [A:1, B:1]

[A:2] and [A:1,B:1]: neither includes the other => concurrent.
A read returns BOTH. The client merges: "milk, eggs, bread"
and writes it back with clock [A:2, B:1] + its own bump.
⚠️The last-write-wins trap
Timestamps come from clocks that can differ by milliseconds or more. If node B's clock is 50 ms behind, a write made later on B can carry a smaller timestamp than an earlier write on A, and be thrown away without any error. That is why systems that cannot lose updates use vector clocks or CRDTs. See Vector Clocks and CRDTs.
🎤
Say it out loud
“I pick availability, so leaderless replication with N = 3 and tunable R and W. With R = 2 and W = 2, the read and write sets overlap. I would be honest that this is not linearizable: sloppy quorums and partial failed writes can still give stale reads. For concurrent writes I would attach a vector clock, return both versions when they conflict, and let the client merge, like a shopping cart. For data where losing one write is fine, last-write-wins is simpler, but I would warn about clock skew.”
5.3

Handling failures: hinted handoff, read repair and anti-entropy

The problem: Machines fail all the time at this size. A failure can last seconds or forever, and a node can come back with stale data. One fix does not cover all three cases.

OptionHow it worksGoodBad
Strict quorum onlyWrite only to the 3 home replicas. Fail if fewer than W answer.Simple. Keeps the overlap guarantee.Less available: two nodes in the preference list down means no writes for that key.
Sloppy quorum + hinted handoffIf a home replica is down, send the write to the next healthy node with a hint, and hand it back when the replica returns.Writes keep succeeding. A short outage heals by itself.Weakens the overlap guarantee until the hint is delivered. Hints are kept only a limited time, and the stand-in can fail too.
Read repairWhen a read sees a stale replica, write the newest version back to it.Free: uses data already read. Heals hot keys quickly.Only fixes keys that are read. Cold keys can stay stale for a long time.
Anti-entropy with Merkle treesReplicas compare trees of hashes over key ranges, walk down the differing branches, and copy only the keys that differ.Catches everything, including cold keys and brand-new nodes. Cheap when almost all data matches.Background work and disk reads. Trees must be kept up to date.
Pick
All of them, in layers: hints for short outages, read repair for hot keys, Merkle anti-entropy for the rest

Each layer covers what the one before cannot. Hinted handoff handles a node that is down for minutes. Read repair fixes the keys people actually read, at no extra cost. Anti-entropy is the safety net: it guarantees that replicas converge even for keys nobody reads, and it is how a replacement node gets its data. The visualizer below lets you turn each layer on and off and watch what is left stale.

For failure detection, nodes gossip a heartbeat counter. If a node's counter has not grown for a while, others mark it suspect, and use an adaptive detector (phi accrual) instead of one fixed timeout, so a slow network does not cause false alarms. A false alarm is expensive here: it starts hinted writes and sometimes data movement for a healthy node. For permanent loss, an operator (or a long timeout) removes the node and its ranges are rebuilt from the other replicas. See Gossip Protocol, Heartbeats, Failure Detectors and Merkle Trees.

SituationLayer that handles itHow long it takes
Node down for 5 minutesHinted handoffSeconds after it returns
Node down for 5 hours (hints expired)Merkle anti-entropy, plus read repair on hot keysMinutes to hours, depending on the gap
Node lost, empty replacementStreaming plus anti-entropyHours, bounded by disk and network
One replica missed a write, nobody noticedRead repair if the key is read, otherwise anti-entropyNext read, or the next anti-entropy run
Network partition, both sides keep writingVector clocks show conflicts, merged on readWhen the partition heals
📝CP or AP, say it out loud
During a partition this design stays available on both sides (AP) and reconciles later. If the interviewer wants strong consistency, the alternative is a consensus group (Raft or Paxos) per partition: writes go through a leader and a majority, and the minority side refuses requests (CP). Say what you would pay: lower availability and higher write latency. See CAP Theorem.
🎤
Say it out loud
“Failures come in three sizes, so I use three repairs. For a short outage, a stand-in node keeps the write with a hint, and hands it over when the node returns. For hot keys, read repair writes the newest version back to a stale replica during a read. For everything else, including a brand-new node, anti-entropy compares Merkle trees and copies only the ranges that differ. Failures are detected by gossip with an adaptive detector, so slow is not mistaken for dead.”
5.4

Inside one node: the write and read path

The problem: Every client write becomes three replica writes, so each node takes a heavy stream of small writes. It must survive a crash, write fast, and still read a key from billions of items in a few milliseconds.

OptionHow it worksGoodBad
In-memory hash table onlyKeep everything in RAM.Very fast.2 TB per node does not fit in RAM. A crash loses everything.
B-tree on diskUpdate pages in place, with a write-ahead log.Predictable reads. Good for read-heavy workloads.Each update is a random disk write, and pages are rewritten. Weak for a write-heavy replicated load.
LSM tree (commit log, memtable, SSTables)Append to a log, keep recent writes in a sorted memory table, flush to immutable sorted files, merge them in the background.Mostly sequential writes: very fast and cheap on SSDs and disks. Easy to compress.A read may look in several files (read amplification). Compaction costs CPU and I/O (write amplification).
Pick
An LSM tree with Bloom filters and background compaction

The write is: append to the commit log (one sequential write, so a crash cannot lose it), insert into the memtable, and reply. When the memtable is full it is flushed as a new sorted file (an SSTable). The read is: check the memtable, then, for each SSTable from newest to oldest, ask its Bloom filter "could the key be here?" and only read files that say yes. With 10 bits per key, about 1% of the files that cannot hold the key get read by mistake, so a typical read touches one or two files.

Compaction merges SSTables, keeps only the newest version of each key, and drops expired data and old tombstones. That keeps reads fast and reclaims space. See LSM Trees, Write-Ahead Log (WAL) and Bloom Filters.

One node: put and get (sketch)
put(key, value, version):
    commitLog.append(key, value, version)     // sequential, fsync per batch
    memtable.put(key, value, version)          // sorted in memory
    if (memtable.size > 64MB) flushToSSTable() // new immutable sorted file
    reply

get(key):
    best = memtable.get(key)
    for sst in sstables.newestFirst():
        if (!sst.bloom.mightContain(key)) continue   // skip: definitely not here
        v = sst.read(key)                            // index lookup + one block
        best = newer(best, v)
    return best      // may be a tombstone => "deleted"
⚠️Deletes are tricky: tombstones
A delete writes a tombstone. It must stay long enough to reach every replica (a grace period, for example 10 days). If it is dropped too early, a replica that missed the delete can bring the old value back from the dead (a resurrected delete). So: keep tombstones past the longest outage you tolerate, and run repair within that time.
CostWhyWhat you can do
Read amplificationA key may be in several SSTablesBloom filters, a row cache, and compaction to merge files
Write amplificationCompaction rewrites data several timesPick a strategy that fits the load (size-tiered for writes, leveled for reads)
Space amplificationOld versions stay until compactionKeep disks about half full, as in the estimate
Hot readsA few keys get most readsA row cache in memory in front of the SSTables
🎤
Say it out loud
“On each node I use an LSM tree. A write is appended to a commit log and put in a sorted memtable, then acknowledged, so it is one sequential write. When the memtable fills, it is flushed to an immutable sorted file. A read checks the memtable, then uses a Bloom filter on each file to skip files that cannot hold the key, so most reads touch one or two files. Background compaction merges files and drops old versions. Deletes are tombstones, kept longer than the longest outage, so a stale replica cannot bring a deleted key back.”
VisualizerFailure handling: hinted handoff, read repair and Merkle anti-entropyPick which replica fails and whether it returns or is lost. Set W and R, turn hinted handoff and read repair on or off, then step through six moments and see what the client saw and which layer fixed the stale replica.
Which replica fails?
What happens to it?
Hinted handoff
Read repair
Client write
OK
W = 2 of N = 3
Client read
stale (v0)
R = 1, worst case
Replica fixed by
Merkle anti-entropy
first layer that worked
replica
Node A
v0
replica
Node B
v0
replica
Node C
v0
stand-in
Node D
no copy
not involved
Node E
no copy
Ring order: A → B → C → D → E → back to A. The key lives on A, B and C (its preference list). D is the next node after them.
All replicas agree.
Step 1 of 6
1. Everything in sync
The key k hashes to a point on the ring. Its preference list is the next 3 nodes: A, B and C, and all three hold v0. Node D is the next node on the ring, and will stand in for a replica that is down.

A simplified model of one key with fixed rules (no random numbers). The read picks the replicas that are behind first, to show the worst case. Real systems contact all N replicas and use the first R answers, and hints are kept only for a limited time.

Step 6Scale, bottlenecks and failuresabout 7 min

🤔
Pause. Try it yourself first
If data doubles, what breaks first? If a whole zone disappears, what do clients see? If one key gets a million requests a second, what happens?

What breaks first, and the fix

BottleneckFix
A hot key (one key gets most of the traffic)Cache it in the client library or in front of the store for a few seconds. For reads, spread them over all replicas. For counters, split the key into several sub-keys and add them up on read.
Uneven load on the ringUse many virtual nodes, give bigger machines more tokens, and watch per-node load and size, then move tokens.
Compaction using all the disk bandwidthThrottle compaction, schedule it off-peak, keep disks about half full, and pick the strategy to match the workload.
Rebalancing and adding nodes slow the clusterStream data from many sources at a limited rate, one node at a time, and never rebalance during an incident.
Read latency tail (p99) from slow replicas or garbage collectionSend reads to all replicas and use the first R answers, or send a backup request after a short delay (hedged requests).
Large valuesCap the value size. Store big blobs in object storage and keep only a pointer in the store.
Gossip traffic and ring size at thousands of nodesGossip a few peers per round, send only changes, and keep the ring metadata small. Beyond a few hundred nodes, consider splitting into several clusters.

What if a part fails?

FailureHow the design copes
One node failsGossip marks it down. Reads and writes use the other two replicas. Hints are stored for it. It catches up on return.
A whole zone is lostEvery key has a copy in the other two zones, so R = W = 2 still works. Repair copies data to the survivors once the zone is declared lost.
The coordinator crashes during a writeThe client times out and retries on another node. Writes are idempotent (same value and version), so a retry is safe.
A network partition splits the clusterBoth sides keep working with sloppy quorums. Conflicts are found by vector clocks and merged after healing.
A node returns with an old disk (stale data)Anti-entropy and read repair bring it up to date. Do not let it serve as the only source until it has caught up.
Disk corruptionChecksums on every block detect it. The node drops the bad file and re-copies the range from other replicas.
What to monitor
  • •Latency p50, p95 and p99 for get and put, per node and per consistency level
  • •Hint backlog and age, read-repair rate, and anti-entropy lag: how far replicas are from agreeing
  • •Load and data size per node, to spot an uneven ring and hot keys
  • •Compaction backlog, number of SSTables per read, and Bloom filter false-positive rate
  • •Gossip: number of nodes marked down, flapping nodes, and failure-detector suspicion level
  • •Tombstone count and the oldest repair time, versus the tombstone grace period
Security and abuse
  • •Authenticate clients and nodes, and encrypt traffic between them with TLS (mutual TLS between nodes).
  • •Authorise per key prefix or per tenant, so one team cannot read another team's keys.
  • •Encrypt data at rest, with keys held in a key management service.
  • •Rate limit and set quotas per tenant, so one noisy tenant cannot take all the capacity.
  • •Audit who read or wrote sensitive key prefixes, and protect the admin API that adds or removes nodes.

Step 7Wrap upabout 3 min

A Dynamo-style store: consistent hashing with virtual nodes spreads keys over about 150 machines, each key lives on 3 replicas in different zones, and R and W are tunable per request. Concurrent writes are detected with vector clocks and merged on read. Failures are repaired in layers: hinted handoff, read repair and Merkle-tree anti-entropy. Each node uses an LSM tree with Bloom filters, because every client write becomes three replica writes.

Trade-offs you made

DecisionWhat we gainWhat it costs
Availability over strong consistency (AP)Reads and writes keep working during failures and partitions.Stale reads and conflicts are possible. The application may need to merge.
R = W = 2 with N = 3 by defaultOverlap in the normal case, and survives one node down.Slower than W = 1. Still not linearizable in every failure.
Sloppy quorum and hinted handoffWrites succeed through short outages.Overlap is weaker until hints are delivered. Hints use space and expire.
Vector clocks instead of last-write-winsNo silent loss of concurrent writes.Clients must merge, and clock metadata grows.
LSM tree storageFast sequential writes, which suits a replicated write load.Read amplification and compaction I/O.
Hash partitioningEven load and cheap rebalancing.No range scans and no secondary indexes.
If we had more time, we would…
  • •Multi-region: local quorums per data centre (LOCAL_QUORUM) and asynchronous replication between regions.
  • •Secondary indexes and range queries, with a different partitioning scheme such as ordered tokens.
  • •A strongly consistent mode for selected keys, using a consensus group per partition.
  • •Automatic hot-key detection and splitting, and automatic rebalancing.
  • •Fault-injection testing in the style of Jepsen, run continuously.
🎤
Say it out loud
“To recap: consistent hashing with virtual nodes, three replicas in three zones, tunable R and W, vector clocks for conflicts, and three layers of repair: hinted handoff, read repair and Merkle anti-entropy. Each node is an LSM tree with Bloom filters. I chose availability, so the cost is that reads can be stale and the application may have to merge conflicts. If I had more time I would add multi-region and an optional strongly consistent mode.”

Q&ACross-questions (23)

💡How to practise
Cover the answer. Say yours out loud in 30 to 60 seconds. Then open the model answer, the follow-up, and the weak answer to see what to avoid. Use Open all at the top for a quick read.
Warm-upProbingCurveballWarm-up = basics. Probing = tests depth. Curveball = changes the problem.

Consistency and conflicts

Where interviewers push hardest. Be precise about what quorums do and do not guarantee.

Failures and repair

Scale, storage and data

Curveballs and comparisons

What ifIf the interviewer changes the problem

A change in requirements is a test of whether you understand why your design looks the way it does.

New requirementWhat changes in the design
Strong consistency is required for all keysReplace leaderless writes with a consensus group per partition (Raft). Writes and reads go through the leader. The minority side of a partition becomes unavailable. Latency is a majority round trip.
Range queries by key prefix are requiredUse ordered (range) partitioning or a partition key plus a sorted clustering key. Watch for hot ranges. Add rebalancing by splitting ranges.
Multi-region, active in every regionLocal quorums per region and asynchronous cross-region replication. Version with region ids, merge conflicts, and define what a client sees after failover.
Values are large (megabytes)Store blobs in object storage and keep a pointer, or chunk values with a manifest. Cap the size in the API.
Read-heavy workload, 99% readsAdd a cache in front, use leveled compaction to keep reads cheap, add more replicas and send reads to the nearest.
Transactions across several keysNot natural here. Add a coordination layer (two-phase commit or a consensus-based transaction manager), or move to a database built for it. Say what it costs.
Counters that must be exactUse a CRDT counter (a per-node count that is summed), or route all updates for one counter through one leader. Last-write-wins loses increments.
Strict data deletion rules (for example privacy requests)Shorter tombstone grace and a repair schedule that meets it, a way to find all copies, and a plan for backups. Encryption with per-tenant keys lets you delete by destroying the key.

ScoreHow answers are judged

AreaWeakGoodGreat
RequirementsStarts with ‘use a hash table’. Never asks about consistency, size or scale.Asks about value size, consistency, availability, scale. Rules out range queries.Ties each answer to a design decision, and names the consistency choice before drawing anything.
Building upJumps straight to Dynamo with no reason for each part.Starts with one node, then explains why it must be distributed.Adds each part (partitioning, replication, quorums, gossip) only when a problem demands it.
EstimationNo numbers, or a node count with no basis.Items, data size with replicas, node count, operations per node.Uses numbers for decisions: tokens, Bloom filter memory, data moved per new node, and growth.
Consistency depthSays ‘eventual consistency’ and stops.Explains N, R, W, overlap, and picks AP with a reason.Explains what quorums do not guarantee, compares last-write-wins, vector clocks and CRDTs, and names the CP alternative.
Failure handling‘We have replicas’ with no detail.Covers gossip detection, hinted handoff and anti-entropy.Matches each repair to a failure size, and explains tombstones and resurrected deletes.
CommunicationLists buzzwords without explaining.Follows the 7 steps and explains.States the trade-off for each choice, checks in, and handles curveballs calmly.

AvoidCommon mistakes on this question

MistakeDo this instead
Starting with the distributed design before the single-node oneDescribe one server first (hash table, log, snapshot), say where it breaks, then distribute.
Saying ‘eventual consistency’ without N, R and WShow the quorum numbers, the overlap rule, and what a client sees when it fails.
Claiming R + W > N gives linearizabilitySay it gives overlap in the normal case, and list what breaks it: sloppy quorums, partial writes, concurrent writes.
Using hash mod N for partitioningUse consistent hashing with virtual nodes, and show how little data moves when a node joins.
Last-write-wins with no mention of clock skewName the risk, and say where you would use vector clocks or CRDTs instead.
Putting all three replicas in one zone or rackChoose replicas from different zones by walking the ring and skipping the same zone.
Forgetting how deletes workExplain tombstones, the grace period, and the resurrected-delete risk.
Promising range scans on a hash-partitioned storeSay it is not supported, and what you would change to support it.

Revise60-second revision sheet

  • ✔Scale: 100 TB, 1 KB items = 100 billion items. With 3 copies, 300 TB, about 150 nodes at 2 TB each.
  • ✔Partitioning: consistent hashing with virtual nodes (256 per machine). A new node moves about 1/N of the data.
  • ✔Replication: N = 3, next distinct nodes on the ring, in different zones (the preference list).
  • ✔Quorum: R + W > N means overlap. N = 3, R = 2, W = 2 is the default. W = 1 fast, W = N durable.
  • ✔Not linearizable: sloppy quorums, partial writes and concurrent writes can still give stale reads.
  • ✔Conflicts: vector clocks (return siblings, client merges), last-write-wins (clock skew loses writes), CRDTs (auto merge).
  • ✔Failures: gossip + phi detector; hinted handoff (short), read repair (hot keys), Merkle anti-entropy (everything else).
  • ✔Storage: commit log, memtable, SSTables, Bloom filters, compaction. Deletes are tombstones kept past the grace period.
  • ✔CAP: AP by default. CP means a Raft group per partition, and the minority side refuses requests.
  • ✔One line: “Hash it onto a ring, copy it three times, let R and W tune freshness, and repair in layers.”

Read these topics next

Consistent Hashing→

The ring and virtual nodes used for partitioning.

Quorum (R + W > N)→

The overlap rule behind tunable consistency.

Vector Clocks→

How the store tells newer from concurrent writes.

Merkle Trees→

How anti-entropy finds differences cheaply.

Gossip Protocol→

How membership and failures spread with no central server.

LSM Trees→

The storage engine inside each node.

Bloom Filters→

How a read skips files that cannot hold the key.

CAP Theorem→

The availability versus consistency choice behind this design.

← Previous
Design a Unique ID Generator
Next →
Design a Scalable Parking System (Smart Parking)