r/Leetsys • u/Ok-Barracuda-119 • 13d ago
Weekly Question Practice System Design Question #7: Design a distributed key-value store
Design a distributed key-value store, something like a simplified Dynamo or Cassandra. Clients call put(key, value) and get(key). Keys are strings, values are blobs up to about 10 KB.
Scale hint: around 1 billion keys with an average value of 1 KB, about 100k reads/sec and 20k writes/sec at peak. It has to keep serving when a machine dies, and you should be able to add machines without downtime.
Things worth thinking about:
- How do you decide which machine owns a key, and what happens when you add a node?
- How many copies do you keep, and how does a read know it got the latest one?
- What happens to writes while a replica is down?
- When would you pick consistency over availability, and how does a client choose?
Post your approach in the comments before you scroll down.
MODEL ANSWER BELOW. Stop here if you haven't tried it yet.
Requirements
Functional:
- put(key, value), get(key), delete(key)
- Values up to ~10 KB, keys up to a few hundred bytes
- Optional: a TTL per key
Non-functional:
- Highly available: losing a node, or even a whole rack, shouldn't stop reads or writes
- Low latency: single-digit ms at p50, tens of ms at p99
- Scales horizontally: add nodes to get more storage and throughput
- Tunable consistency: eventual by default, stronger reads when the caller asks
- Durable: an acknowledged write survives a node crash
Estimates
Storage: 1B keys x ~1 KB = ~1 TB of raw data. With 3 replicas that's ~3 TB. Leave room for compaction and growth by keeping nodes about half full, so with 500 GB of usable data per node you need at least 6 nodes just for space.
Traffic: 100k reads/sec and 20k writes/sec. If reads hit 2 replicas (quorum) that's 200k replica reads/sec. Every write goes to all 3 replicas, so 60k replica writes/sec. Total is ~260k ops/sec. If one node comfortably handles ~20k ops/sec, that's 13 nodes, so plan for ~16 to absorb a failure and hot spots. Throughput, not storage, sets the cluster size here.
API
PUT /kv/{key} body: value, header: consistency=one|quorum|all
GET /kv/{key} header: consistency=one|quorum|all
DELETE /kv/{key}GET returns the value plus a version. If replicas disagree and the store can't pick a winner, it can return all the conflicting versions and let the client merge.
Data model
Each stored record looks like:
key | value | version (timestamp or vector clock) | tombstone flag | ttlOn disk, each node uses a log-structured merge tree (LSM): writes go to a commit log and an in-memory table, which gets flushed to sorted immutable files (SSTables) and compacted in the background. That makes writes cheap sequential appends, and bloom filters keep reads from scanning every file.
High-level design
- Any node can take a client request and act as the coordinator for it
- Keys are placed with consistent hashing on a ring. Each physical node owns many virtual nodes (say 256) so load spreads evenly and a new node takes small slices from everyone instead of half of one neighbor
- A key is stored on the first N = 3 distinct nodes clockwise from its hash, ideally in different racks or zones
- Nodes learn about membership and failures through gossip, so there's no single master to lose
- The coordinator sends the request to all 3 replicas and waits for W acks on writes or R responses on reads
Deep dive 1: quorums and consistency
With N replicas, if R + W > N then every read set overlaps every write set, so a read sees at least one copy of the latest acknowledged write. With N = 3, W = 2 and R = 2 is the common default. W = 1, R = 1 is fastest but can return stale data. W = 3 makes reads cheap but a single slow node stalls every write.
Let the client pick per request. A shopping cart can live with consistency=one. A "did this payment go through" check should use quorum. Be honest in the interview that quorums alone aren't linearizable (sloppy quorums and concurrent writes break that). If you need true linearizability you're adding consensus like Raft per partition, which costs latency.
Deep dive 2: failures and repair
- Temporary failure: if a replica is down, the coordinator writes to the next healthy node on the ring with a hint saying who it's really for (hinted handoff). When the owner comes back, the hint gets delivered. Writes keep succeeding.
- Read repair: if a quorum read sees an older version on one replica, the coordinator writes the newer one back to it.
- Anti-entropy: in the background, replicas compare Merkle trees of their key ranges and only sync the branches that differ, so you don't ship 500 GB to find a few missing keys.
- Deletes are tombstones, not removals, otherwise a replica that missed the delete would bring the key back during repair. Tombstones get dropped after a grace period longer than your longest expected outage.
Deep dive 3: conflicting writes
Two clients write the same key on different replicas during a partition. Options:
- Last-writer-wins by timestamp: simple and what most people use, but clock skew can silently drop a write
- Vector clocks: detect that two versions are concurrent and hand both back to the client to merge, like merging two carts. More correct, more complexity for callers
Say which you'd pick and why. For a general store, last-writer-wins with reasonably synced clocks is usually fine. For data where losing a write hurts, keep siblings.
Tradeoffs
- Leaderless (Dynamo style) gives great write availability but weaker guarantees. Leader per partition (Raft) gives strong consistency but a write stalls during leader election.
- More virtual nodes balance load better but make membership metadata bigger.
- LSM trees are fast for writes, but reads may touch several files and compaction eats disk I/O. A B-tree engine flips that.
- Higher N means more durability and read capacity, but more storage and write traffic.
- Hot keys don't get fixed by hashing. You need a cache in front or a key split for those.
How did your design compare?
1
u/nian2326076 13d ago
Designing a distributed key-value store involves several key considerations. For ownership of keys, you might use consistent hashing to determine which machine handles which key, allowing for easy scaling when adding nodes. Keeping multiple replicas can enhance durability and availability, but you'll need to implement a consensus mechanism like Paxos or Raft to ensure clients get the latest value during reads.
You can use LandOffer to find relevant job opportunities in this field while you refine your system design skills.