Designing a distributed key-value store is one of the most common and foundational system design interview questions. A key-value (KV) store is a NoSQL database that stores data as a collection of key-value pairs. While designing a single-server KV store is trivial (an in-memory hash table suffices), scaling it across hundreds of nodes introduces complex distributed systems challenges. In this article, we will design a highly available, scalable, and distributed KV store similar to Amazon Dynamo or Apache Cassandra.
Requirements (functional and non-functional)
Before jumping into the architecture, it is crucial to align with your interviewer on the system's requirements.
Functional Requirements
put(key, value): Insert a new key-value pair or update an existing one.get(key): Retrieve the value associated with a specific key.- Out of scope: Complex queries, joins, and range queries.
Non-functional Requirements
- High Availability (HA): The system must remain operational even if multiple nodes fail. Availability is prioritized over absolute consistency (AP system in the CAP theorem).
- Scalability: The system should scale horizontally. Adding or removing nodes should have minimal impact on overall performance.
- Low Latency: Read and write operations should complete in single-digit milliseconds.
- Tunable Consistency: Clients should be able to configure the trade-off between consistency and latency per request.
Capacity estimates
Let us assume we are designing this system for a read-heavy application, such as user profile caching or session management.
- Traffic: 100 million Daily Active Users (DAU).
- QPS: Assume each user makes 10 reads and 1 write per day.
- Reads per day = 1 billion. Average Read QPS = 10^9 / 10^5 seconds ≈ 10,000 QPS. Peak Read QPS ≈ 20,000 QPS.
- Writes per day = 100 million. Average Write QPS = 10^8 / 10^5 seconds ≈ 1,000 QPS. Peak Write QPS ≈ 2,000 QPS.
- Data Size: Assume the average size of a key is 32 bytes and a value is 1 KB.
- Storage: 100 million writes/day * 1 KB ≈ 100 GB/day. Over 3 years, this is roughly 100 TB of data.
- Bandwidth:
- Ingress: 1,000 writes/sec * 1 KB = 1 MB/sec.
- Egress: 10,000 reads/sec * 1 KB = 10 MB/sec.
These numbers indicate that a single machine cannot hold all the data or handle the peak traffic reliably. We must partition the data across multiple nodes.
API design
The API for a distributed KV store is straightforward but requires parameters to support tunable consistency.
put(key: string, value: byte[], consistency_level: int) -> booleanget(key: string, consistency_level: int) -> byte[]
The consistency_level parameter dictates how many nodes must acknowledge the operation before it is considered successful. We will explore this deeply in the Quorum section.
Data model
Since we need low latency, we cannot rely solely on disk seeks. Modern KV stores use a combination of memory and disk.
- Write Path: Data is first written to a Write-Ahead Log (WAL) on disk for durability, then to an in-memory data structure (MemTable). Once the MemTable is full, it is flushed to disk as an Immutable SSTable (Sorted String Table).
- Read Path: The system checks the MemTable first. If not found, it checks a Bloom Filter to quickly determine which SSTable might contain the key, minimizing expensive disk reads.
High-level architecture
In our distributed KV store, there is no central "master" node. A master-slave architecture would introduce a single point of failure and a write bottleneck. Instead, we use a decentralized, leaderless architecture (like a Dynamo-style ring).
- Client Request: A client sends a
putorgetrequest to any node in the cluster (or through a load balancer). - Coordinator Node: The node receiving the request acts as the coordinator. It hashes the key to determine which nodes are responsible for storing the data.
- Replication: The coordinator forwards the request to the responsible replica nodes.
- Response: Once the required number of replicas acknowledge the request, the coordinator returns the result to the client.
Deep dives
To build a robust distributed KV store, we must solve three major challenges: Data Partitioning, Replication & Consistency, and Inconsistency Resolution.
1. Data Partitioning (Consistent Hashing)
To scale horizontally, we must distribute data evenly across servers. A naive approach is hash(key) % N (where N is the number of servers). However, if a server crashes or we add a new one, N changes, causing almost all keys to be remapped. This results in massive data movement.
Solution: Consistent Hashing We map both the servers and the keys onto a circular hash space (e.g., 0 to 2^160 - 1). To find the server for a key, we hash the key and move clockwise on the ring until we find the first server. When a node is added or removed, only a small fraction of keys (those adjacent to the node) need to be moved.
Virtual Nodes (V-Nodes) Physical nodes are rarely distributed perfectly evenly on the ring. To balance the load, each physical node represents multiple "virtual nodes" on the ring. If Node A has 3 virtual nodes, it occupies 3 random spots on the ring.
Here is how you can implement a Consistent Hash Ring with Virtual Nodes:
import hashlib
import bisect
class ConsistentHashRing:
def __init__(self, replicas=3):
self.replicas = replicas
self.ring = dict()
self.sorted_keys = []
def _hash(self, key):
# Use MD5 to hash the key to a large integer
return int(hashlib.md5(key.encode('utf-8')).hexdigest(), 16)
def add_node(self, node):
# Add multiple virtual nodes for each physical node
for i in range(self.replicas):
vnode_key = self._hash(f"{node}#{i}")
self.ring[vnode_key] = node
bisect.insort(self.sorted_keys, vnode_key)
def get_node(self, key):
if not self.ring:
return None
hash_val = self._hash(key)
# Find the first v-node clockwise
idx = bisect.bisect(self.sorted_keys, hash_val)
if idx == len(self.sorted_keys):
idx = 0 # Wrap around the ring
return self.ring[self.sorted_keys[idx]]2. Replication and Quorum Consensus
To achieve high availability, data must be replicated. When a key is mapped to a node on the hash ring, it is also replicated to the next N - 1 distinct physical nodes clockwise on the ring. N is the replication factor.
With multiple replicas, how do we ensure a client doesn't read stale data? We use Quorum Consensus. Let:
- N: Number of replicas.
- W: Write quorum (number of nodes that must acknowledge a write).
- R: Read quorum (number of nodes that must respond to a read).
For strong consistency, we must ensure that the read and write quorums overlap. The formula is: W + R > N
| Configuration | Latency | Consistency | Use Case |
|---|---|---|---|
| W=1, R=N | Fast writes, slow reads | Strong | Write-heavy systems (e.g., logging) |
| W=N, R=1 | Slow writes, fast reads | Strong | Read-heavy systems (e.g., profile data) |
| W+R > N (e.g., W=2, R=2, N=3) | Balanced | Strong | General purpose KV store |
| W+R <= N (e.g., W=1, R=1, N=3) | Fast both | Eventual | Highly available, latency-sensitive apps |
3. Handling Inconsistencies (Vector Clocks)
In a distributed system prioritizing availability (AP), network partitions can cause nodes to accept concurrent writes to the same key. This leads to conflicting data.
To detect conflicts, we use Vector Clocks. A vector clock is a list of [server, version] pairs associated with a data item.
- Client writes
val1to Node A. Vector clock:[A:1]. - Client updates to
val2via Node A. Vector clock:[A:2]. - Network partition happens. Client updates to
val3via Node B. Vector clock:[A:2, B:1]. - Another client updates to
val4via Node C. Vector clock:[A:2, C:1].
Now we have a conflict. [A:2, B:1] and [A:2, C:1] are siblings. The system cannot automatically determine which is newer. When a client reads this key, the system returns both values. The client application must resolve the conflict (e.g., by merging the data or letting the user choose) and write back the resolved value with a new vector clock: [A:2, B:1, C:1].
Bottlenecks and trade-offs
- CAP Theorem: Our design is primarily AP. During a network partition, we continue to accept writes to ensure availability, which means we trade off strong consistency. We mitigate this by allowing clients to tune
WandR. - Hot Keys (The Celebrity Problem): Consistent hashing distributes data evenly, but it doesn't solve the problem of a single key being accessed millions of times per second (e.g., a viral tweet). This can overwhelm a single node. We can mitigate this by adding a random number to the key (salting) to distribute the load across multiple nodes, but this requires the application layer to know how to read all the salted keys and aggregate them.
- Anti-Entropy: Over time, nodes can fall out of sync due to missed writes. We use background processes with Merkle Trees (hash trees) to efficiently compare data between nodes and synchronize them without transferring the entire dataset.
Questions an interviewer will ask next
1. How do nodes detect if another node has failed? Answer: We use a Gossip Protocol. Every node periodically sends a heartbeat to a few random nodes. If a node hasn't updated its heartbeat counter in a while, other nodes mark it as dead. It is decentralized and highly scalable.
2. What happens if a node temporarily goes down during a write? Answer: We use Hinted Handoff. If Node A is down, the coordinator writes the data to a healthy node (e.g., Node D) along with a "hint" that the data belongs to Node A. When Node A comes back online, Node D forwards the data to it.
3. How do you handle a node permanently failing or a new node joining? Answer: When a new node joins, it announces its presence via the Gossip protocol. It is assigned virtual nodes on the consistent hash ring. It then streams the necessary data from its neighboring nodes. Merkle trees make this data transfer efficient by only transferring the distinct data blocks.