System Design

Problem Breakdowns

Design a Key-Value Store

Most answers recite the Dynamo paper: a ring, quorums, vector clocks and hinted handoff. Amazon's own successor kept the partitions and dropped most of the rest. The design turns on one question: when two writes to one key race, who decides which one wins?

"Design a key-value store" usually gets the Dynamo paper recited back. A hash ring with virtual nodes. Three replicas, with reads and writes that wait for two of them. Vector clocks, sloppy quorums, hinted handoff, Merkle trees and gossip. Each piece works, and each one answers a question the candidate never asked out loud.

Amazon published that paper in 2007. Its successor, DynamoDB, kept the partitions and changed most of the rest. Each partition has one leader, elected with Multi-Paxos, a consensus protocol, and the leader puts every write in order. The 2022 DynamoDB paper says the new service shared most of the old one's name "but little of its architecture."

The part both designs share is the easy part. Hash the key, map the hash to a partition, and keep three copies of each partition on three machines. Consistent hashing and partitioning cover it. The two designs part ways at the moment two clients write the same key.

Placing keys is the solved part. The design of a key-value store is the answer to one question: when two writes to the same key race, who decides which one wins?

There are three answers. The clock can decide, by keeping the write with the later timestamp. The client can decide, by getting both values back and merging them. Or a leader for each partition can decide, by putting the writes in order and refusing the second one if it was based on an old version. Each answer loses something different, and the rest of the design follows from which loss you accept.

Two writes, three deciders
Both clients read the cart at version 7, holding shoes. A adds a book and B adds a pen. When the clock decides, the later timestamp keeps B's cart and A's book is gone, in red, though A was told the write succeeded. When the client decides, the key-value store keeps both carts and the next reader merges them. When a leader decides, A's write becomes version 8, B's write fails because it was based on version 7, and B reads version 8 and writes version 9 with all three items, in green.Both clients read the cart at version 7, holding shoes. A adds a book and B adds a pen. When the clock decides, the later timestamp keeps B's cart and A's book is gone, in red, though A was told the write succeeded. When the client decides, the key-value store keeps both carts and the next reader merges them. When a leader decides, A's write becomes version 8, B's write fails because it was based on version 7, and B reads version 8 and writes version 9 with all three items, in green.
Each design decides who picks the winner, and loses something different. Both clients read the cart at version 7, holding shoes. A adds a book and B adds a pen. When the clock decides, the later timestamp keeps B's cart and A's book is gone, in red, though A was told the write succeeded. When the client decides, the key-value store keeps both carts and the next reader merges them. When a leader decides, A's write becomes version 8, B's write fails because it was based on version 7, and B reads version 8 and writes version 9 with all three items, in green.

Understanding the problem

The general method for this part of the interview is in The First Five Minutes: Requirements.

A key-value store keeps a value under a key and gives it back. A service puts a shopping cart under user:42, a session under its token, or a flag under its name, and reads it back by the same key. There's no query language, no join, and nothing that writes two keys at once.

Four kinds of system go by this name, and each one is designed differently.

  1. An in-memory cache cluster, such as Redis or Memcached in front of a database. Losing data is allowed, because the database behind it still has every value. Distributed cache designs that one.
  2. An embedded storage engine, such as RocksDB, a library that keeps sorted keys on one machine's disk. This design runs one on every node. It doesn't build one.
  3. A coordination service, such as etcd or ZooKeeper. It holds a small amount of configuration and locks, and every write goes through one consensus group. This design uses one for its own metadata.
  4. A durable, partitioned, replicated key-value database, such as Dynamo, Cassandra, Riak or DynamoDB. It holds terabytes on many machines, and an acknowledged write must not be lost. This is the one we're designing.

Functional requirements

Core:

  1. Put, get and delete a value by key. Values are up to 1 MB, and most are about 1 KB.
  2. Conditional writes. A put or a delete can say "only if the current version is v", or "only if the key doesn't exist yet". If the condition fails, nothing changes, and the client is told the current version.
  3. A consistency choice on every read. A strong read sees every write that was acknowledged before it started. An eventual read may be slightly behind, and costs less.
  4. Add and remove capacity while serving traffic. Nodes join and leave without a maintenance window.

Out of scope, deliberately:

  • Range scans and secondary indexes. Keys are hashed, so neighbouring keys sit on different machines.
  • Transactions across several keys.
  • A cache in front of the key-value store, and what to evict from it. That's the distributed cache.
  • Authentication, billing and quotas per tenant.

Non-functional requirements

  1. Scale. 100 billion keys of about 1 KB each, so 100 TB before replication. At peak, 1,000,000 reads and 200,000 writes a second. These are assumptions, sized for a platform that many services share.
  2. Latency. A p99 under 10 ms for a get or a put inside one region. The p99 is the latency that 99 percent of requests beat.
  3. Durability. An acknowledged write survives losing any one machine or any one availability zone.
  4. Availability. 99.99 percent, the figure the DynamoDB paper gives for tables in one region. Losing a zone doesn't stop the service.
  5. No write is lost without its writer being told. If two writes to one key race, either both survive, or the loser gets an error that names the current version.

Requirement 5 carries the design, so write it in those words. If it says "eventually consistent" instead, the key-value store may keep one of two acknowledged writes and drop the other with no error. Then requirement 2 can't be built at all.

How often do two writes to one key race? Dynamo's paper measured it on the shopping cart service.

Back of envelopeRare per request, common per day
The question is whether racing writes are rare enough
to ignore. Dynamo's paper counted how many versions its
cart service got back from reads over 24 hours.

  requests that saw exactly one version          99.94%
  requests that saw 2, 3 or 4 versions
    0.00057% + 0.00047% + 0.00009%          =  0.00113%
  the paper doesn't account for the other         0.06%

Assume our tables race as often as Amazon's carts did
  average reads, with the course's 5x peak
                   1,000,000 / 5             = 200,000/s
  reads that meet two or more versions
                   200,000 × 0.0000113       ≈     2.3/s
  in a day         2.26 × 86,400             ≈   195,000
  ─────────────────────────────────────────────────────────
About 200,000 reads a day would find two versions of one
key. Under last-write-wins, each of them would see one
version instead, and the write behind the other would be
gone, with no error to the client that sent it.

The paper also says where the races came from. The number of divergent versions grew with concurrent writers, usually automated clients, not with failures. So races happen on a healthy cluster, every day, and 200,000 is a floor for a platform whose callers are mostly other programs.


The set up

Core entities

  • Item. A key, a value and a version. The version is a number the key-value store gives each write, and it grows with every write to the key. The version is the only interesting field: a conditional write compares against it, and every read returns it.
  • Partition. A fixed range of hashed keys, about 10 GB of them. It's the unit that is copied, moved and split.
  • Replica. One copy of one partition on one node. Each partition has three, in three availability zones, and the three form its replication group.
  • Node. A machine with a disk. It holds a few hundred replicas from different partitions.
  • Partition map. Which hash range belongs to which partition, and which nodes hold its replicas. It changes when a partition moves or splits, and it has a version number of its own.

System interface

PUT /v1/tables/carts/items/user:42
If-Match: "1041"
Request-Id: 6f1c0e2a-93b4-4d71-8a5e-2c07f9b41d36
<value bytes, up to 1 MB>

→ 200 { "version": "1042" }
→ 412 { "current_version": "1045" }

PUT /v1/tables/carts/items/user:43
If-None-Match: *
Request-Id: b84d1f07-5c2e-4a9b-9e63-71d0a5c8f214
<value bytes>

→ 200 { "version": "1046" }
→ 412 { "current_version": "998" }

GET /v1/tables/carts/items/user:42?consistency=strong
GET /v1/tables/carts/items/user:42?consistency=eventual&min_version=1042

→ 200 { "version": "1042", "value": "..." }

DELETE /v1/tables/carts/items/user:42
If-Match: "1042"
Request-Id: 9d07b3f1-4e2a-4c88-b1f5-0a63d27e9c45

→ 200 { "version": "1043" }

Four things to note.

Every write returns a version, and so does every read. The client sends it back in If-Match on its next conditional write, and in min_version on an eventual read. If-None-Match: * is the create-only put from requirement 2: it fails if the key exists at all.

A failed condition is a normal answer. 412 Precondition Failed carries the current version, so the client knows it lost a race. It reads the new value, applies its change to that, and tries again. This is requirement 5 in the API.

A retry carries the same request ID. Say a conditional put commits, and then its response is lost. The retry still says If-Match: "1041", but the item is at 1042 now, so the client would get a 412 for its own write. So each partition keeps a table of the request IDs it has committed in the last 24 hours, with the version each one produced. A retry whose ID is in it gets back the original 200 and version.

min_version keeps an eventual read from going backwards. The client library sends the highest version it has seen for the key. A replica that hasn't applied that version yet doesn't answer from its old copy. It sends the read to the partition's leader instead.

All of that is the data plane. The control plane creates tables, splits and moves partitions, and replaces failed replicas. The two share only the partition map, which the control plane writes and the data plane reads from a cache. If the control plane is down, moves and splits wait, and gets and puts carry on.


High-level design

1. Put and get: how does a key find its replicas?

Every request names a table and a key, and something has to turn that into three machines. That mapping has to survive machines joining and leaving.

Hashing the key isn't in dispute. A good hash spreads keys evenly, and every client computes the same one. The decision is how ranges of hash values are assigned to machines.

Naive

Take the hash modulo the node count

hash(key) % N names a node in one line, with no map to keep, and it's perfectly balanced.

Then a 101st node joins a cluster of 100. A key stays where it was only if its hash leaves the same remainder when divided by 100 and by 101, and that's true for about 1 key in 101. So 99 percent of the data moves to make room for one machine. Consistent hashing measures it.

Senior

A ring of tokens, several per node

Each node takes several random positions, called tokens, on a ring of hash values. A key belongs to the first token clockwise from its hash, and its other replicas are the next distinct nodes along the ring. A new node takes over the ranges just before its tokens, so only about 1/N of the data moves. Dynamo and Cassandra work this way, and it's the standard answer.

Its cost is that tokens do two jobs. They set the balance, and they decide which nodes share replicas. Cassandra's documentation says each token adds up to 2 × (RF − 1) neighbours, where RF is the replication factor, so more tokens mean more pairs of nodes whose failure together costs some range its quorum. Consistent hashing works through the numbers.

The ring also moves range boundaries every time a node joins. Dynamo's paper describes what that cost. Donors had to scan their local data for the keys in each new range, so a join took almost a day in the busy season, and every changed range needed its Merkle tree rebuilt.

Staff

Fixed partitions, placed by a map

Question the premise that placement must be computed without coordination. A ring lets clients agree on placement without asking anyone. But section 2 gives every partition a replication group with a leader, and something has to track those groups anyway. That's a control plane, and once you have one, a map is simpler than a ring.

So cut the hash space once into fixed ranges: 10,000 partitions of about 10 GB, a size deep dive 1 justifies. A boundary changes only when a partition splits in two. The partition map, kept in the metadata service, records which three nodes hold each partition. A new node receives whole partitions, and moving a partition means copying its files.

What a new node takes
On the left, new node E takes three random tokens, so three ranges on three nodes are cut in two, in red. Each donor has to find the keys in its cut range and each changed range needs a new Merkle tree. On the right, the boundaries are fixed. E receives three whole partitions, P3, P7 and P11, each copied as files, and no boundary moves.On the left, new node E takes three random tokens, so three ranges on three nodes are cut in two, in red. Each donor has to find the keys in its cut range and each changed range needs a new Merkle tree. On the right, the boundaries are fixed. E receives three whole partitions, P3, P7 and P11, each copied as files, and no boundary moves.
Tokens redraw ranges, and fixed partitions only change owner. On the left, new node E takes three random tokens, so three ranges on three nodes are cut in two, in red. Each donor has to find the keys in its cut range and each changed range needs a new Merkle tree. On the right, the boundaries are fixed. E receives three whole partitions, P3, P7 and P11, each copied as files, and no boundary moves.

Dynamo's paper got here too. Its third partitioning strategy cut the ring into equal fixed partitions. The paper lists what that bought: a partition moves as a unit by copying its file, archiving goes partition by partition, and the membership data each node keeps shrank by three orders of magnitude. DynamoDB keeps its partition map in a metadata service and caches it in its request routers.

What you give up. The map is on the path of every request, through a cache. A cache that fetches only when it misses floods the metadata service when it starts cold, as DynamoDB's paper found when it added routers. So each cache here asks for the changes since its map_version once a second, warm or cold. The metadata service's load then grows with the number of caches, not with requests. A router with an old map finds out from the node it reaches, which answers with the current membership or an error that makes the router look again.

A get or a put goes from the client to a router. The router hashes the key, finds the partition in its cached map, and sends the request to one of that partition's replicas. The replica it picks depends on the operation, and that's the next decision.

The whole map is small enough to cache everywhere. 10,000 rows of a hash range, three node IDs and a leader hint come to about 100 bytes each, so about 1 MB. A lookup is a binary search over 10,000 boundaries, 14 steps in memory. So the map can live in each router, and in a client library too, which deep dive 4 uses.

2. Conditional writes: who decides which write wins?

Every partition has three replicas. A put has to reach them, and requirement 2 says it can carry a condition. So where is the condition checked? That's the same question as who orders two writes to one key.

The quorum rule doesn't answer it. Write to two of three replicas, read from two, and every read meets the latest completed write. Quorums, Raft and Paxos shows what that leaves out: two writes can each reach two replicas, both clients are told success, and nothing records which came second. Overlap gives you visibility, not order.

Naive

Leaderless quorums, and the later timestamp wins

Any node can coordinate a write. The write carries a timestamp from the client's clock, or from the coordinator's if the client sends none. The coordinator sends it to all three replicas and calls it a success after two answer. A read keeps the newest timestamp and copies it to replicas that were behind. Cassandra works this way, and it's tempting: with no leader there's no failover, and any two replicas can take any write.

It fails requirement 5 in two ways. The first is the clocks. A write stamped by a node whose clock runs 40 ms slow loses to an earlier write stamped by an accurate one, and both clients were told success. Cassandra's documentation says its correctness depends on these clocks, and asks you to run a clock sync such as the Network Time Protocol (NTP).

A slow clock loses the later write
Time runs left to right. Node 1's clock is right, and it stamps A's write 12:00:00.000 (1). 20 ms later, node 2 stamps B's write, but its clock runs 40 ms slow, so the stamp reads 11:59:59.980 (2). Both clients are told success. Every replica keeps the larger stamp, so A's older value survives and B's later write is gone, in red (3).Time runs left to right. Node 1's clock is right, and it stamps A's write 12:00:00.000 (1). 20 ms later, node 2 stamps B's write, but its clock runs 40 ms slow, so the stamp reads 11:59:59.980 (2). Both clients are told success. Every replica keeps the larger stamp, so A's older value survives and B's later write is gone, in red (3).
The write that came second carries the smaller timestamp. Time runs left to right. Node 1's clock is right, and it stamps A's write 12:00:00.000 (1). 20 ms later, node 2 stamps B's write, but its clock runs 40 ms slow, so the stamp reads 11:59:59.980 (2). Both clients are told success. Every replica keeps the larger stamp, so A's older value survives and B's later write is gone, in red (3).

The second failure needs no clock error at all. Two clients read the cart, each adds an item, and each writes the whole cart back. The later timestamp keeps one cart and drops the other client's item. Jepsen ran this race against Riak in last-write-wins mode: concurrent read-modify-write updates to one key lost 71 percent of acknowledged writes, on a healthy cluster.

And requirement 2 can't be built. A conditional write needs one place that can refuse the second writer. Here no replica can, because each one only sees its own copy.

Senior

Keep both versions, and let the client merge

This is the Dynamo paper's own answer. Each version carries a vector clock, a list of (node, counter) pairs that records which writes it descends from. When neither of two versions descends from the other, a read returns both, called siblings. The client merges them and writes the result back. Nothing acknowledged is thrown away. Riak recommends this mode, by setting allow_mult to true.

The cost lands on every team that uses the key-value store. Each one writes a merge function, and the obvious one, a union of the two carts, brings deleted items back. Dynamo's paper says so: an "add to cart" is never lost, but deleted items can resurface.

A union keeps the adds and undoes the delete
The cart holds shoes and a book. One client removes the book (1), and another client, who hasn't seen that, adds a pen (2). The two versions are siblings. A union of them holds shoes, book and pen (3), so the book is back, in red, though its owner removed it.The cart holds shoes and a book. One client removes the book (1), and another client, who hasn't seen that, adds a pen (2). The two versions are siblings. A union of them holds shoes, book and pen (3), so the book is back, in red, though its owner removed it.
Merging two siblings by union brings back the item one of them removed. The cart holds shoes and a book. One client removes the book (1), and another client, who hasn't seen that, adds a pen (2). The two versions are siblings. A union of them holds shoes, book and pen (3), so the book is back, in red, though its owner removed it.

There are two more costs. A write needs the vector clock from an earlier read, so every update costs a read and then a write. Jepsen's analysis says Cassandra skipped vector clocks for this reason: last-write-wins cuts a write from two round trips to one. And requirement 2 is still out of reach, because "put if the version is 1041" means nothing when versions can branch.

Staff

One leader per partition orders the writes

Question the premise that every replica must accept writes. Dynamo needed that, because the shopping cart had to take an "add to cart" even while the network was failing, and the paper calls the design "always writeable". Requirement 5 asks for something else: that a writer learns when it lost. That needs one place where the order is decided, and it costs some availability.

So give each partition one leader. The three replicas form a consensus group, running Raft or Multi-Paxos, and only the leader accepts writes. Each election raises a number called the epoch, and the new leader writes under it. For a put, the leader checks the request ID against the partition's committed request IDs, and If-Match against the newest version of the key. Then it appends the write to the partition's replication log, and the entry's position in the log, its index, becomes the version. Once the entry is on the leader's disk and one follower's, two of three copies exist, and the leader applies it and replies.

The leader checks, numbers and copies
A and B both send a put with If-Match 1041 (1). The leader takes A first: the version matches, so A becomes log entry 1042 (2). The entry goes to the followers in zones b and c, and when it's on the leader's disk and zone b's, A gets 200 with version 1042, in green (3). B's condition is checked against 1042 and fails, so B gets 412 with the current version, in red (4).A and B both send a put with If-Match 1041 (1). The leader takes A first: the version matches, so A becomes log entry 1042 (2). The entry goes to the followers in zones b and c, and when it's on the leader's disk and zone b's, A gets 200 with version 1042, in green (3). B's condition is checked against 1042 and fails, so B gets 412 with the current version, in red (4).
Two racing writes meet at the leader, and only one can match the version. A and B both send a put with If-Match 1041 (1). The leader takes A first: the version matches, so A becomes log entry 1042 (2). The entry goes to the followers in zones b and c, and when it's on the leader's disk and zone b's, A gets 200 with version 1042, in green (3). B's condition is checked against 1042 and fails, so B gets 412 with the current version, in red (4).

Nothing is lost, and the loser knows. DynamoDB works this way. The replicas of each partition elect a leader with Multi-Paxos, and only the leader serves writes and strongly consistent reads. A write is acknowledged once a quorum has the log record in its write-ahead log.

The trade, sized. When a leader dies, its partition takes no writes until a new leader is elected and the old leader's lease, its time-limited right to lead, has run out. DynamoDB's paper puts that wait at a couple of seconds. Each node leads about 93 of the 10,000 partitions (deep dive 1), so one node failure pauses writes on under 1 percent of partitions for a few seconds. Eventual reads carry on from the followers.

What you give up. A replica cut off from the other two can't lead, so the minority side of a network split takes no writes. Every write waits for a copy in a second zone. And you run 10,000 consensus groups, which works only if their heartbeats are combined per pair of nodes, as quorums works out for CockroachDB.

A client that loses re-reads and tries again, so a conditional write is a loop in the client. It reads the item and its version, changes the value, and puts it with If-Match. On a 412 it starts over from the version the error named. With little contention the loop runs once. On a key that many clients update at the same moment, most attempts lose, which is the hot-key problem in deep dive 3. So the loop needs a limit on attempts and a growing wait between them, or a busy key turns into a storm of retries.

The leader also makes three later parts simpler. A strong read is a read at the leader (section 3). A replica that missed writes replays them from the log, so it needs no hints (deep dive 2). And the replication log is the durable log that write-ahead logs builds for a key-value store, so the storage engine doesn't need one of its own.

Which storage engine, and what actually forces it

Each replica applies the log to a storage engine on its node's disk. Both engine families work here. DynamoDB's storage nodes keep a B-tree. Cassandra keeps a log-structured merge tree, or LSM tree, which writes sorted files and merges them in the background, a process called compaction. LSM trees vs B-trees compares the two in full. In this design one number picks the engine, and it isn't the write rate.

Back of envelopeDisk sets the node count
The question is what decides how many nodes we run, and
so what the engine should save. Each node has a 4 TB NVMe
drive, filled to 80%. Per node throughput uses the course's
working figures: 20,000 writes/s and 50,000 reads/s.

Throughput
  replica writes    200,000/s × 3 copies      = 600,000/s
  nodes for writes  600,000 / 20,000          =        30
  nodes for reads   1,000,000 / 50,000        =        20
  at 100% busy                                =        50
  50 to 70% busy at peak, plus one node
  to lose           50/0.7 + 1, 50/0.5 + 1    ≈ 72 to 101

Storage
  replica data      100 TB × 3                =    300 TB
  usable per node   4 TB × 0.8                =    3.2 TB
  levelled LSM, 1.14x space
                    300 × 1.14 / 3.2          ≈       107
  B-tree, pages ~70% full
                    300 / 0.7 / 3.2           ≈       134
  size-tiered LSM, half of each disk kept free
                    300 / 2                   =       150

Disk writes per node, levelled LSM on 107 nodes
  600,000 / 107 × 1 KB × 34x                  ≈  190 MB/s
  ─────────────────────────────────────────────────────────
Storage still needs more nodes than throughput, about
1.1 to 1.5 times as many. So the engine that wastes the
least space saves the most machines, and the levelled LSM
tree's extra writes still fit in the drive's bandwidth.
Naive

A B-tree, as in a relational engine

MySQL's InnoDB keeps its tables this way, as a B-tree on the primary key, and so do DynamoDB's storage nodes, so this isn't a mistake. A get reads one leaf page, and there's no background merging to tune.

Its cost here is space. Under random keys, pages sit about 70 percent full, so 300 TB of replicas need 134 nodes instead of 107. That's 27 more machines, paid for empty space inside pages.

Senior

An LSM tree, because writes are heavy

This is the usual answer. Cassandra and RocksDB collect writes in memory and write them out as sorted files, so no write rewrites a page in place. Cassandra's default compaction, size-tiered, merges files of similar size and rewrites each byte fewer times than the levelled kind below.

Its cost is space again. Its largest merges can need half the disk free, so 300 TB of replicas need at least 150 nodes, 43 more than the answer below.

Staff

Levelled compaction, chosen for space

Question the premise that a write-heavy system picks its engine by write cost. Even with headroom, throughput needs 72 to 101 nodes and disk needs at least 107, so disk is the scarce thing, not writes.

Levelled compaction keeps space to about 1.14 times the data, and pays for it by writing each byte about 34 times. At 107 nodes that's about 190 MB a second per node. Assume a data-centre NVMe drive sustains about 1 GB a second of writes, and compaction uses under a fifth of it.

So each node runs one RocksDB instance with levelled compaction, and gives each partition replica its own column family. Column families share the instance's write-ahead log but keep their own memtables and files, so a partition's files still move as a unit without 280 separate instances on a node. Writes skip RocksDB's own write-ahead log, with its disableWAL option, which exists for systems that keep a log of their own. After a crash, the node replays the replication log from the last index the engine flushed, so each write reaches the disk as one log entry, not two.

What you give up. Each write costs about twice the disk bytes a B-tree write would. And a compaction that falls behind slows every read and then stalls writes, so the bytes waiting for compaction become a number to alert on.

data storewhat goes in itwhat forces it
replication log, one per partitionevery write in order, with its epochrequirement 5, and an acknowledged write on disk in two zones
RocksDB, levelled, one per node, a column family per replicathe current value and version of each key300 TB of replicas, where disk sets the node count
metadata service, etcdthe partition map and the node listsmall and rarely changed, and two versions of it would send one key to two groups
object storage, such as S3archived log segments and partition snapshotsrestoring a table to an earlier time, which replication can't do

The records and the partition map

-- In each partition replica's RocksDB column family
items (
  key          bytes primary key,
  version      bigint not null,   -- log index of the write that set it
  value        bytes,             -- null marks a delete, a tombstone
  expires_at   timestamp          -- optional expiry; never used for order
)

-- In the same column family, written by the same log entry as the write
request_ids (
  request_id   uuid primary key,
  version      bigint not null,   -- the version that write produced
  response     bytes,             -- the reply, sent again to a retry
  committed_at timestamp          -- dropped after 24 hours
)

-- The replication log, one per partition, on each replica
log_entries (
  partition_id bigint,
  log_index    bigint,
  epoch        bigint,            -- the leader's term when it wrote this
  op           bytes,             -- put, delete or increment, and its condition
  primary key (partition_id, log_index)
)

-- In the metadata service
partitions (
  partition_id bigint primary key,
  hash_start   bigint,
  hash_end     bigint,            -- fixed until a split replaces the row
  replicas     text[],            -- three node IDs, one per zone
  leader_hint  text,              -- a guess; the group elects its own leader
  map_version  bigint             -- raised by every change to this table
)

nodes (
  node_id      text primary key,
  zone         text,
  state        text               -- ACTIVE, DRAINING, REMOVED
)

Five things to note.

The version is a log index, not a time. Two writes to one key get versions in the order the leader logged them, whatever any clock says. expires_at and committed_at are the only timestamps, and neither decides order. When a partition splits, each child's log starts after the parent's last index, so a key's version only grows.

Request IDs live in the partition, not on the item. A hot counter can take hundreds of writes a second, so a short list on the item would forget a retry within milliseconds. The request_ids row is written by the same log entry as the write, so every replica has it, and so does any new leader. Kept for 24 hours, the minimum the idempotency keys pattern suggests, that's at most 200,000 × 86,400, about 17 billion rows. At about 100 bytes each, that's at most 1.7 TB before replication, under 2 percent of the data.

The map holds a guess at the leader, not the leader. Each group elects its own leader, and the epoch lives in its log, not in the metadata service. A replica that isn't the leader redirects a write to the one that is, and the router updates its hint.

Expiry is a write, ordered like the others. The leader scans its partitions in the background for items whose expires_at has passed, and logs a delete conditional on each one's version. A put that reached the log first has changed the version, so the delete fails and the new value stays. Until the delete commits, reads hide an expired item and a conditional put treats it as absent, but no replica deletes one by its own clock.

A node's state changes only when someone decides it should. A node that misses heartbeats stops getting requests, but it keeps its partitions until the controller or an operator marks it REMOVED. Consistent hashing explains why a health check must never move data: a pause and a dead machine look the same from outside.

The operations that carry the product

-- 1. Eventual get, at any replica
get(key, min_version):              -- highest version the client has seen
  if applied_index < min_version: forward to the leader
  hide the item if it has expired
  return items[key].value, items[key].version

-- 2. Strong get, at the leader
get(key):
  require lease_valid() and an entry committed in this epoch
  hide the item if it has expired
  return items[key]

-- 3. Conditional put, at the leader
put(key, value, if_version, request_id):
  require lease_valid() and an entry committed in this epoch
  if request_ids[request_id]: return its stored response
  if request_id is in an entry still in flight:
    wait for that entry to commit and return its stored response,
    or return 409
  cur = newest(key)                    -- may be an entry in flight
  if cur.version != if_version:
    wait for cur to commit, or return 409
    return 412, cur.version
  i = log.append(epoch, put(key, value, request_id))
  wait until entry i is on disk on a majority of the voters
  apply(i)                             -- the item and its request_ids row
  return 200, i

-- 4. Router, on a cache miss or a redirect
partition = map.lookup(hash(key)); refresh the map entry

Operation 1 runs most often, because the client library makes eventual reads the default: they skip the leader and usually stay in the client's own zone. Operation 3 is the one an interviewer pushes on, usually by asking what happens if the leader dies after the append and before the reply.

Either the entry reached a second replica or it didn't. If it did, the new leader has it, because Raft only elects a replica whose log holds every committed entry, and the client's retry finds its request ID and gets back version 1042. If it didn't, the write never committed, and the retry applies it for the first time.

The in-flight checks close a smaller gap. Entries commit in log order, so a put appended behind an in-flight entry can only commit if that one does, and checking its condition against the in-flight version is safe. A reply that appends nothing is different. A 412 that names an in-flight version, or a 200 for a retry whose first attempt is still in flight, promises something about an entry that might never commit. That happens if this leader has just been cut off. So those replies wait for the commit, and a leader that loses its lease first returns 409, which the client retries.

3. Strong and eventual reads

A strong read must see every write acknowledged before it started. Only the leader knows the newest committed version, and only while it's still the leader. Quorums, Raft and Paxos gives three ways for a leader to prove that at the moment of a read: put the read through the log, confirm with a majority, or hold a lease.

Take the lease, as DynamoDB does. The leader keeps renewing it with its followers, and while it holds it, it answers from its own state with no extra messages. That's safe only while the nodes' clocks drift less than the lease allows, and that's the assumption to say out loud. A new leader serves nothing until the old leader's lease has run out, so two leaders never answer at once. It also waits until it has committed an entry in its own epoch, a blank one if it has nothing else to write. Until then, it can't tell which entries from earlier epochs are committed.

An eventual read goes to any replica, usually one in the client's own zone. A follower is behind the leader by the time it takes to receive and apply the log, normally milliseconds. The read skips the leader, usually skips a round trip to another zone, and spreads one key's reads over three replicas instead of one, which deep dive 3 uses. DynamoDB passes the same saving on in its prices: an eventually consistent read costs half the read capacity of a strong one.

The cost is the anomalies in consistency models, and the one users notice is their own write missing. min_version fixes that. The client library sends the highest version it has seen for the key, from its own writes and its reads, and a follower that hasn't applied it forwards the read to the leader. That also stops one client's reads going backwards, the monotonic reads guarantee. Reads with no token, or with a token the follower passed long ago, never wait.

4. Add and remove nodes without stopping traffic

Moving a partition is where many designs pause writes. For a while two nodes hold the data, and it's unclear which copy is current. Here the answer comes from section 2: a move is a change to the partition's replication group, and the group keeps one leader all the way through.

The controller, a control-plane process, moves one partition in four steps. Say the partition's group is A, B and C, and C's copy is moving to a new node, D.

  1. Add D as a learner, a member that receives the log but doesn't vote and doesn't count toward the majority a write needs. So a slow new copy can't slow the partition's writes.
  2. Copy a snapshot. The engine's files never change once written, so a snapshot is a list of files plus the log index they cover. The new node copies them as whole files.
  3. Catch up from the log, from the snapshot's index to the newest entry.
  4. Swap the old replica for D in one joint-consensus change. While the change is in effect, a write needs a majority of the old members, A, B and C, and a majority of the new ones, A, B and D. Quorums, Raft and Paxos explains why a change of members needs this, or one member at a time. If the old replica was the leader, it hands leadership on first. Then the controller writes the new replica list to the partition map.

The joint change matters because D goes into C's zone, to keep one replica per zone. Promoting D first would make four voters, with a majority of 3, and losing that one zone would take C and D together and stop writes. In the joint change, A and B alone are a majority of both groups, so the partition still takes writes with that zone gone.

Writes keep committing throughout, on 2 of the 3 voters, and during the swap on 2 of each group. The only pause is a leader handover in step 4, and it's short. DynamoDB's paper says a leader that gives up leadership on purpose, as it does during a deployment, lets the new leader start without waiting for the lease.

Back of envelopeHow long a new node takes to fill
The question is how far ahead to add capacity. Copies
into a new node are throttled to 200 MB/s, an assumed
figure that leaves its disk free for traffic.

Adding one node
  on disk today                    342 TB on 107 nodes
  per node after the join  342 TB / 108     ≈  3.17 TB
  one replica on disk      10 GB × 1.14     ≈  11.4 GB
  time per replica         11.4 GB / 200 MB/s  ≈  57 s
  time to fill the node    3.17 TB / 200 MB/s  ≈  4.4 hours

Adding ten nodes at once
  per node after           342 TB / 117     ≈  2.92 TB
  time to fill each        2.92 TB / 200 MB/s  ≈  4.1 hours
  each old node gives up   3.2 − 2.92       ≈  280 GB,
                           about 19 MB/s over those hours
  ─────────────────────────────────────────────────────────
Ten nodes fill as fast as one, because every old node
gives a little to each. But a node takes most of an
afternoon to fill, so add nodes in batches, hours before
the disks reach the 80 percent target.

A partition splits when it passes 20 GB, or when its traffic stays near its limit. The split is local: the leader picks a split point, and the group becomes two groups on the same three nodes, with new partition IDs. DynamoDB picks the split point for a busy partition from the keys it has seen requested, which works better than cutting the range in the middle. Moving one of the halves is then an ordinary move.

Removing a node uses the same four steps. The controller marks it DRAINING, moves each of its replicas off, and marks it REMOVED. A node that fails without warning is deep dive 2.


Deep dives

Deep dives 1, 2 and 3 come up in most versions of this interview.

1. How many nodes, and what actually needs scaling?

The storage engine section sized the fleet by disk, at 107 nodes. This works out how big a partition should be, and what one node failure touches.

Back of envelopePartitions, replicas and leaders on each node
The question is how big to make a partition, and what
one node failure stops. 107 nodes, 100 TB of data.

Partitions at 10 GB
  partitions               100 TB / 10 GB      =   10,000
  writes per partition     200,000 / 10,000    =    20/s
  reads per partition      1,000,000 / 10,000  =   100/s

Per node
  replicas                 10,000 × 3 / 107    ≈      280
  leaders                  10,000 / 107        ≈       93

Across the cluster, heartbeats combined per pair of nodes
  2 a second               107 × 106 × 2       ≈ 22,700/s

One node fails
  groups down to 2 replicas                    =      280
    that keep their leader   280 − 93          =      187
    that wait for a new one  93 / 10,000       ≈    0.93%
  replacements stay in its zone, one replica per zone
    other nodes there        107 / 3 − 1       ≈       35
    replicas each            280 / 35          =        8
    bytes each               8 × 11.4 GB       ≈    91 GB
    time at 200 MB/s         91 GB / 200 MB/s  ≈    8 min
    copied from the surviving replicas, on the ~71 nodes
    in the other two zones
  ─────────────────────────────────────────────────────────
10 GB keeps a move to about a minute and gives each node a
few hundred groups. A node failure pauses writes on under
1 percent of partitions, and the 35 other nodes in its
zone rebuild its replicas in about 8 minutes.

The partition size is the setting to defend, so check both directions. At 1 GB, there are 100,000 partitions and 2,800 consensus groups per node, and the map and the per-group state grow tenfold for nothing. At 100 GB, one move takes about ten minutes, so a hot partition takes ten times as long to leave a busy node. And a failed node's 28 replicas can use only 28 of the 35 nodes in its zone, each copying 114 GB, so the rebuild takes about ten minutes instead of eight.

Rebuilding still takes minutes, and the group runs on two copies meanwhile. DynamoDB's answer is a log replica, a member that stores only recent log entries, and this design adopts it. The leader adds one in a few seconds, because only the recent log has to be copied, and the group has three copies of each new write again while the full replica is rebuilt.

The rest of the fleet scales on request rate, not data. Routers keep no state, so they're added behind a load balancer as traffic grows. The metadata service grows only with the number of caches, routers and client library instances, because each one asks for changes once a second whatever its traffic.

2. What happens when a replica fails, or its data differs?

Dynamo-style key-value stores keep replicas in step with three mechanisms: failure detection, hinted handoff and anti-entropy. Each one exists in this design too, in a smaller form, because the log does most of their work.

Noticing a failure

Cassandra spreads heartbeats by gossip, and each node decides on its own, from the heartbeats it hears, whether each peer is up.

Here, each leader sends heartbeats to its followers, and a follower that hears nothing for an election timeout starts an election. DynamoDB found that gray failures, where one follower loses the leader while the others can still reach it, caused elections nobody needed. Its fix: before starting an election, the follower asks the other replicas whether they can reach the leader, and gives up if they can.

One partition loses its leader
Time runs left to right. The leader's node dies (1). The followers miss its heartbeats, check with each other that neither can reach it (2), and elect B with epoch 6 (3). B waits for the old lease to expire, and commits a first entry in epoch 6, before it takes writes or strong reads (4). Writes fail with a retryable error in the red band. Eventual reads are answered by B and C the whole time, in green.Time runs left to right. The leader's node dies (1). The followers miss its heartbeats, check with each other that neither can reach it (2), and elect B with epoch 6 (3). B waits for the old lease to expire, and commits a first entry in epoch 6, before it takes writes or strong reads (4). Writes fail with a retryable error in the red band. Eventual reads are answered by B and C the whole time, in green.
Writes pause until the old lease runs out, and eventual reads never stop. Time runs left to right. The leader's node dies (1). The followers miss its heartbeats, check with each other that neither can reach it (2), and elect B with epoch 6 (3). B waits for the old lease to expire, and commits a first entry in epoch 6, before it takes writes or strong reads (4). Writes fail with a retryable error in the red band. Eventual reads are answered by B and C the whole time, in green.

A replica that missed writes

In a leaderless design, a write still has to reach W replicas when one is down. Dynamo uses a sloppy quorum. The write counts an acknowledgement from the next healthy node on the ring instead, and that node keeps the write with a hint naming the replica it belongs to. This is hinted handoff. It keeps writes available, and quorums shows its cost: a read that asks the key's usual replicas can miss the write entirely.

Cassandra has the coordinator keep the hint for the unreachable replica and replay it later. It keeps generating hints for up to 3 hours of downtime by default, and treats them as best effort. A replica down longer than the window stays out of date until repair finds it.

Here a write needs two of the partition's own three replicas, and nothing stands in for them. The missed writes are already in the leader's log, in order. A follower that comes back asks for every entry after its last index, and the leader streams them. If the log has been trimmed past that point, the follower copies a snapshot instead. Nothing has a window after which a missed write is dropped.

Where a missed write waits
On the left, replica C is down, so the coordinator keeps hints for it in orange, on its own disk (1). Writes in the first 3 hours C is down get hints, and writes after that get none, in red (2). On the right, C's missed writes are entries 1043 to 1077 in the leader's log (3). When C returns, it asks for everything after 1042, and the leader streams the entries to it in order, in green (4).On the left, replica C is down, so the coordinator keeps hints for it in orange, on its own disk (1). Writes in the first 3 hours C is down get hints, and writes after that get none, in red (2). On the right, C's missed writes are entries 1043 to 1077 in the leader's log (3). When C returns, it asks for everything after 1042, and the leader streams the entries to it in order, in green (4).
A hint waits on another node until its window closes; a log entry waits in order. On the left, replica C is down, so the coordinator keeps hints for it in orange, on its own disk (1). Writes in the first 3 hours C is down get hints, and writes after that get none, in red (2). On the right, C's missed writes are entries 1043 to 1077 in the leader's log (3). When C returns, it asks for everything after 1042, and the leader streams the entries to it in order, in green (4).

Replicas that disagree

The log keeps replicas in step by construction. It doesn't protect against a disk that flips a bit, or a bug in the code that applies entries. DynamoDB guards against both with a scrub. It checks that all three replicas hold the same data, and that a live replica matches one rebuilt from the archived log.

Comparing two 10 GB replicas key by key means reading and sending 10 GB. A Merkle tree, a tree of hashes, avoids that. Each replica splits its keys into buckets by hash range and hashes each bucket's keys and versions. Those hashes are the leaves, and each parent is a hash of its children. Two replicas compare their roots, and go down only where the hashes differ.

Comparing two replicas by hash
The roots differ, in red (1). The left children match, in green, so half of the keys need no more checking (2). On the right, the comparison follows the one child that differs down to a single leaf (3), and only that bucket's keys are sent and fixed (4).The roots differ, in red (1). The left children match, in green, so half of the keys need no more checking (2). On the right, the comparison follows the one child that differs down to a single leaf (3), and only that bucket's keys are sent and fixed (4).
Matching hashes rule out whole halves, so only one bucket is copied. The roots differ, in red (1). The left children match, in green, so half of the keys need no more checking (2). On the right, the comparison follows the one child that differs down to a single leaf (3), and only that bucket's keys are sent and fixed (4).
Back of envelopeWhat one comparison sends
The question is whether replicas can be compared often
without moving their data. One 10 GB partition of 1 KB
items, in a tree with 2^15 leaves.

  keys in the partition    10 GB / 1 KB        =     10M
  keys per leaf            10M / 32,768        ≈     305
  one key differs
    hashes exchanged       15 levels × 2 × 32 B  ≈  1 KB
    keys copied            305 × 1 KB          ≈  305 KB
  against copying the partition
                           10 GB / 305 KB      ≈  33,000x less

Building the trees on one node
  read all its replicas    3.2 TB / 200 MB/s   ≈  4.4 hours
  ─────────────────────────────────────────────────────────
A comparison is almost free once the trees exist, and
building them reads the whole disk. So the scrub runs
about once a week, throttled.

In a leaderless design this repair isn't optional. A replica that missed a delete still holds the old value, so the tombstone has to outlive the longest a replica can be out of date. Cassandra keeps tombstones for 10 days by default, and its documentation says to repair every node at least once every 7 days, or deleted data can come back.

Here a follower that missed a delete gets it from the log, or from a snapshot that no longer holds the key. So a tombstone can be dropped once every replica has applied past it, and the weekly scrub is a second line of defence, not the only one.

None of this protects against a bad write, because replication copies a mistaken DELETE to all three replicas within milliseconds, as replication and leader election warns. That's what the archive is for. Each replica uploads its sealed log segments and periodic snapshots to object storage, and a restore replays a snapshot's log up to a chosen moment. DynamoDB offers that for any time in the previous 35 days.

3. Hot keys and contention

The average partition sees 20 writes and 100 reads a second. Keys aren't average. DynamoDB caps each partition at 3,000 read units and 1,000 write units a second. A read unit is one strong read of up to 4 KB, and a write unit is one write of up to 1 KB. Our leaders have a ceiling too, because one machine applies every write in a partition's log, so take the same 1,000 writes a second as the limit here.

When a partition runs hot, it splits, as section 4 describes. That fixes a hot range of keys. It doesn't fix one hot key, and DynamoDB's paper says so: a partition whose traffic goes to a single item doesn't benefit from a split.

A split divides keys, not a key
Partition P7 takes 1,600 writes a second against a limit of 1,000. 1,300 of them go to one key, in red, and the blue part is every other key (1). The split cuts P7's range in two. P7a gets 200 writes a second, well under the limit. P7b gets the hot key's 1,300 plus 100 others, and is still over it (2).Partition P7 takes 1,600 writes a second against a limit of 1,000. 1,300 of them go to one key, in red, and the blue part is every other key (1). The split cuts P7's range in two. P7a gets 200 writes a second, well under the limit. P7b gets the hot key's 1,300 plus 100 others, and is still over it (2).
After the split, the half holding the hot key is still over its limit. Partition P7 takes 1,600 writes a second against a limit of 1,000. 1,300 of them go to one key, in red, and the blue part is every other key (1). The split cuts P7's range in two. P7a gets 200 writes a second, well under the limit. P7b gets the hot key's 1,300 plus 100 others, and is still over it (2).

Reads of one hot key first go to all three replicas as eventual reads, which triples what one leader could serve. Past that, the key belongs in a cache in front of the key-value store, where a copy a second old can serve most of its reads. Distributed cache designs that tier, including what it does for one hot key.

Writes to one hot key come in two kinds. The first is a read-modify-write by compare-and-set, such as a counter. Each client reads the version, adds one, and writes If-Match. Under contention most of those writes fail and retry, and each success has to commit before the next client can read it. That's a chain of dependent operations, and quorums puts such a chain at about 550 a second when each step crosses zones.

The fix comes from section 2. The leader already decides the order, so let it do the arithmetic. An increment goes into the log as an operation, with no condition and no read by the client. The leader applies increments in log order, and many of them share one flush. An increment carries a request ID like any write, so a retried increment still counts once.

The second kind is a key that takes more writes than one partition can, even as increments. Then split the key itself: write to one of N sub-keys chosen at random, and add the N values on read.

4. Where does the 10 ms go?

Back of envelopeOne conditional put, inside one region
The question is what the 10 ms p99 pays for, and which
part could go. The course's figures: a 1.5 ms round trip
between zones and 0.3 ms for a flush.

  client to router, same zone, assumed            0.5 ms
  router to leader, possibly another zone         1.5 ms
  leader finds the key's current version   0.1 to 0.5 ms
  append, and the faster follower flushes
    1.5 ms round trip + 0.3 ms flush              1.8 ms
  leader's own flush, at the same time              0 ms
  ─────────────────────────────────────────────────────────
  typical                                  3.9 to 4.3 ms
    of which two round trips between zones        3.0 ms
  left for queueing, compaction and pauses     about 6 ms

The copy to a second zone is requirement 3, and it stays.
The router hop is the one item that can go.

A client library that caches the partition map sends each request straight to the leader. Dynamo measured that swap: moving coordination from a load-balanced node into the client cut its 99.9th percentile read latency from 68.9 ms to 30.4 ms. The hop itself is small. The gain comes at the tail, because the extra hop and the load balancer add variance. So services that can link the library use it, and routers stay for the rest.

The quorum helps here too. The leader waits for the faster of its two followers, so one slow follower doesn't slow writes, which is the tail argument from replication and leader election.

5. Multi-region: the same question, one level up

The requirements cover one region, and some tables need copies in two or three. For each of those tables, decide where writes land.

  • A home region per partition. The leader lives in one region, and the other regions hold followers for eventual reads.
  • Every region takes writes, and the later timestamp wins between regions. This is how DynamoDB's global tables work by default.
  • Synchronous writes across regions. DynamoDB offers this too, with conditions.

A home region keeps requirement 5 everywhere. A write from the far side of the world pays a round trip to the home region, somewhere between 60 and 200 ms across continents, as consistency models puts it. Choose the home by where the data's owner usually is, such as a user's home region, and most writes stay local.

DynamoDB's default mode, multi-Region eventual consistency, replicates writes asynchronously, usually within a second. If the same item changes in two regions at once, the documentation says the write with the latest internal timestamp wins. A conditional write is checked only against the version in its own region. So the clock decides again: the naive tier from section 2, one level up.

The synchronous mode, multi-Region strong consistency, needs exactly three regions, and a write that conflicts with one in another region fails and is retried.

Whichever mode a table uses, every region holds a full copy, so this is replication, not partitioning. Three regions means three times the 107 nodes, and every write is shipped to each other region: 200,000 writes a second of 1 KB is 200 MB a second into each one.

So the choice is per table. Some tables, such as sessions, can take the cheap mode, because last-write-wins does no harm when each write states the whole value and either order of two writes is fine. Logout is the exception: a later last-seen write can bring a deleted session back, so revocation goes in its own record. Tables like carts get a home region, and the few that need every region to agree on every write pay for synchronous writes.

The question from the start comes back unchanged. Inside a region, a leader decides. Between regions, either a leader in one region still decides and distant writers pay for the distance, or the clock decides.

6. How do you know it is working?

During an incident you need four answers quickly: are writes being refused, is any partition without a leader, are replicas in step, and is one partition running hot.

  • The 412 rate per table. A rise means contention on some key, not a fault. A sudden fall to zero on a busy table can mean clients stopped sending conditions.
  • Partitions without a leader, and elections a minute. A partition should go without one for seconds. Many elections and no failed nodes point to a gray failure.
  • Follower lag in log entries, per group, and the share of eventual reads forwarded to a leader. Lag is a queue, so alert on whether it's growing, not only on its size.
  • Throughput per partition against its limit, and its top keys. A table's total hides one hot partition.
  • Scrub mismatches. This should be zero. Any mismatch is a page, because it means a disk or the apply code is wrong.

Don't label metrics by key. A label value per key is its own time series, and 100 billion of them would sink the metrics backend. Aggregate by table and partition, and find one key's history in the logs.


Final design

The final design, with the path of one conditional put
Blue is the client and its library, purple the routers and replicas on the request path, orange the logs, engines and archive, yellow the control plane and grey the scrub and telemetry. Each partition's group has a leader and two followers in three zones. The control plane writes the partition map, and the data plane only reads it. The badges follow the eight steps below.Blue is the client and its library, purple the routers and replicas on the request path, orange the logs, engines and archive, yellow the control plane and grey the scrub and telemetry. Each partition's group has a leader and two followers in three zones. The control plane writes the partition map, and the data plane only reads it. The badges follow the eight steps below.
Each partition's leader decides the order, and the control plane only moves partitions. Blue is the client and its library, purple the routers and replicas on the request path, orange the logs, engines and archive, yellow the control plane and grey the scrub and telemetry. Each partition's group has a leader and two followers in three zones. The control plane writes the partition map, and the data plane only reads it. The badges follow the eight steps below.

One conditional put, end to end:

  1. The client library hashes the key and finds its partition in a cached copy of the partition map. A service without the library sends the request to a router, which does the same.
  2. The request goes to the partition's leader. A replica that isn't the leader redirects it, and a node that no longer holds the partition answers with the newer map.
  3. The leader checks that it holds its lease and has committed an entry in its own epoch. Then it checks the request ID against the partition's committed request IDs, and If-Match against the newest version. A failed condition returns 412 with the current version, once that version has committed.
  4. The leader appends the write to the partition's replication log under its epoch, and sends it to the followers in the other two zones.
  5. When the entry is on a majority of the voters' disks, the leader's and one follower's outside a membership change, the leader applies it to RocksDB, with its request ID row, and returns 200 with the entry's index as the version.
  6. Eventual reads go to any replica, usually in the client's own zone. A replica that hasn't reached the highest version the client has seen, its min_version, forwards the read to the leader.
  7. Every replica uploads its log segments and periodic snapshots to object storage, and a weekly scrub compares replicas by Merkle tree.
  8. The controller splits partitions that pass 20 GB or run hot, and moves replicas onto new nodes as a learner and then one joint swap. For a failed node, it adds a log replica in seconds and then a full one in the same zone. It writes each change to the partition map.

The numbers behind the shape: 100 TB stored three times needs 107 nodes by disk and 72 to 101 by throughput, so the engine is chosen to save space. 10,000 partitions of 10 GB give each node about 93 leaders, so a node failure pauses writes on under 1 percent of partitions for a few seconds. A conditional put typically takes about 4 ms, and 3 ms of that is two round trips between zones.


What is expected at each level

How interviewers turn what they see into these levels is in How a System Design Interview Is Scored.

Mid-level

Breadth matters more than depth at this level, and it's fine to be led.

You should hash keys to partitions, keep three replicas in different zones, and explain why hash % N breaks when a node joins. You should be able to walk a put to its replicas and say when it's acknowledged, and say what a quorum is.

You aren't expected to raise vector clocks, leases or Merkle trees without being asked. You are expected to answer sensibly when asked "two clients write the same key at the same moment, what happens?" A good answer says which write survives, and whether the other client finds out.

Senior

You drive the structure, and three things should come up without prompting.

The race. Say who orders two writes to one key, and what the losing writer sees. Last-write-wins is acceptable only if you say what it throws away.

A partition size or token count, with its costs. Name the number, and say what it does to a node join and a node failure.

A replica that missed writes. Say whether hints, repair or the log bring it back, and how long it can be away before something is lost.

Two things are disqualifying: claiming that W + R > N makes reads strongly consistent, and having no answer for how a new node gets its data while writes continue.

Staff+

A correct design is still the bar. A staff+ answer also decides what not to build.

Name who decides, early, and use it. That one choice sets the API, the replication, the failure handling and the multi-region story.

Put a leader on each partition, and price it. A few seconds of paused writes on under 1 percent of partitions per node failure, a copy in a second zone on every write, and no writes on the minority side of a split.

Size the fleet by disk, and pick the engine for space. 107 nodes by disk against 72 to 101 by throughput, with headroom, is the argument for levelled compaction.

Make a move a membership change, a learner first and then one joint swap, so the partition never has two leaders and keeps taking writes while it moves, even if a zone fails mid-move.

Be able to say what you would not build. No vector clocks and sibling merging for data with no natural merge. No sloppy quorums and hinted handoff when the log already holds every missed write. No ring of random tokens when a control plane already exists. No consensus code of your own: DynamoDB checks its replication protocol with TLA+, a formal specification that a tool checks for errors, and you'd need the same. No synchronous cross-region writes for tables that don't need them. A team could spend a quarter on any one of these.


Sources

Each figure about a real system above comes from one of these, read for this page. The fleet sizes, rates and timings are assumptions, worked through in the worksheets where they're used.

  • DeCandia et al., Dynamo: Amazon's Highly Available Key-value Store, SOSP 2007. The always-writeable cart, vector clocks, sloppy quorums, and deleted items that resurface. The versions the cart service saw over 24 hours, and their cause. The day-long joins of the random-token ring, the fixed partitions that replaced it, and the 68.9 ms to 30.4 ms gain from coordinating in the client.
  • Elhemali et al., Amazon DynamoDB: A Scalable, Predictably Performant, and Fully Managed NoSQL Database Service, USENIX ATC 2022. Multi-Paxos per partition, writes acknowledged by a quorum of logs, and B-tree storage nodes. The lease wait after an election, the gray-failure check and log replicas. Splits by key distribution and their limit for one item. Metadata load from routers starting with cold caches, the scrub, 35 days of point-in-time restore, and the 99.99 percent figure.
  • Amazon DynamoDB documentation. Partition key design gives the 3,000 read and 1,000 write units per partition, and hot partitions prices eventual reads at half. How global tables work describes last-writer-wins between regions and the three-region synchronous mode.
  • Apache Cassandra documentation. The Dynamo architecture covers last-write-wins on timestamps, the dependence on clocks, token neighbours and gossip. Hints gives the 3 hour window, and repair the Merkle trees and the 7 day repair against the 10 day grace period.
  • Kyle Kingsbury, Jepsen: Riak and Jepsen: Cassandra, 2013. Concurrent read-modify-writes under last-write-wins losing 71 percent of writes on a healthy Riak cluster, and 92 percent with strict quorums during a partition. Why Cassandra skipped vector clocks, and its first lightweight transactions losing 1 to 5 percent.
  • Riak documentation, Causal Context. Siblings, and the advice to set allow_mult to true.
  • RocksDB wiki, Write Ahead Log and Column Families. The disableWAL write option, for systems that rely on a log of their own, and column families that share one log but keep their own files.

Spot a mistake, or something unclear? . Or get in touch.

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.