Sub topic 1
Requirements, Scale Targets, and the get/put/delete API
Prerequisites
This chapter assumes you know the following:
- Basic data structures such as hash maps and sorted lists.
- Client-server networking and what an RPC (remote procedure call) is.
- What a hash function does.
- How to read short Python snippets.
You do not need any distributed-systems background. This chapter is the first of the series. It fixes what we are building before we decide how to build it.
Why start with requirements
A key-value store looks simple: you give it a key and it returns a value. The design choices behind that simple interface vary widely. A store that holds shopping carts, a store that holds session tokens, and a store that holds configuration for a fleet of servers need different trade-offs. Writing the requirements first lets you check each later design choice against a stated goal.
In this tutorial we design a general-purpose, distributed key-value store. It spreads data across many machines and keeps working when some of them fail. Later chapters add partitioning, replication, quorums, and repair. This chapter sets the targets they must meet.
Functional requirements
Functional requirements describe what the system does. Ours are short:
- Store a value under a key.
- Return the value for a key.
- Remove a key.
- Treat values as opaque bytes. The store does not parse or index them.
- Look up data only by exact key. There are no joins, secondary indexes, or range queries in the first version.
The last point matters. Dropping range queries lets us place keys by hash, which spreads load evenly. If you need ordered scans, you would partition by key range instead, and you would give up some of that even spread.
Non-functional requirements
Non-functional requirements describe how well the system does its job. For a distributed store, these usually decide the design.
| Requirement | Meaning | Design pressure it creates |
|---|---|---|
| Scalability | Add machines to add capacity | Partition data across nodes |
| High availability | Reads and writes succeed even when nodes fail | Replicate data, avoid a single leader |
| Low latency | Fast responses at the 99th percentile, not only on average | Few network hops, in-memory writes |
| Durability | Acknowledged writes survive a crash | Write to disk before replying |
| Tunable consistency | Callers choose how fresh a read must be | Configurable read and write quorums |
| Operability | Nodes can join, leave, and be replaced without downtime | Automatic rebalancing and repair |
Some of these conflict. Strong consistency costs latency and availability. Durability costs write speed if every write waits for the disk. We will not remove these conflicts. We will make the choices explicit and adjustable.
Scale targets
Targets turn vague goals into numbers you can design against. We will use these as a running example. They are illustrative, not universal.
- 1 billion keys.
- Average value size of 1 KB, with a hard limit of 1 MB.
- 100,000 requests per second overall, with a mix of 90% reads and 10% writes.
- p99 latency under 10 ms for a read in one data center.
- 99.99% availability for reads and writes.
- Replication factor of 3.
Quick arithmetic shows why one machine will not do. One billion keys at 1 KB is about 1 TB of unique data. With three copies, you store about 3 TB. That is possible on a single large server, but 100,000 requests per second with a 10 ms p99 and no single point of failure is not. We need many nodes for throughput and for fault tolerance, even before capacity forces the issue.
keys = 1_000_000_000
value_bytes = 1_000
replication_factor = 3
unique_tb = keys * value_bytes / 1e12
total_tb = unique_tb * replication_factor
print(f"unique data: {unique_tb:.1f} TB, with replicas: {total_tb:.1f} TB")
node_capacity_tb = 2.0 # usable disk per node, leaving headroom
nodes = -(-total_tb // node_capacity_tb) # ceiling division
print(f"minimum nodes by capacity: {int(nodes)}")This prints 1.0 TB unique, 3.0 TB with replicas, and a minimum of 2 nodes by capacity. Capacity alone gives a low number. Throughput, failure tolerance, and the need for headroom push the real cluster size higher, which is why you size by the tightest of several limits, not by disk alone.
The API: get, put, delete
The interface is three operations.
from typing import Optional
class KeyValueStore:
def get(self, key: bytes) -> Optional[bytes]:
"""Return the value for key, or None if the key does not exist."""
raise NotImplementedError
def put(self, key: bytes, value: bytes) -> None:
"""Store value under key, replacing any previous value."""
raise NotImplementedError
def delete(self, key: bytes) -> None:
"""Remove key. Deleting a missing key is not an error."""
raise NotImplementedErrorThis is the single-node contract. The distributed version will extend it, but the shape stays the same. Each method has details worth deciding now.
Semantics worth fixing early
- put is an overwrite. A second put to the same key replaces the first value. This is an upsert, meaning it inserts or updates.
- delete is idempotent. An operation is idempotent if repeating it has the same effect as doing it once. Making delete idempotent lets a client safely retry after a timeout.
- Keys and values are bytes. Bytes avoid encoding disputes between clients written in different languages.
- Size limits are enforced. Reject keys or values over the limit at the API boundary. Unbounded values cause memory spikes and slow replication.
Idempotency and retries
In a network, a client that sends a request and gets no reply does not know whether the request ran. The node may have crashed before it executed the write, or after it executed the write but before it answered. The client must retry to make progress, so operations should tolerate repetition.
Plain put and delete are naturally idempotent, because writing the same value twice leaves the same state. Operations such as "increment this counter" are not. If you want them later, you need request identifiers or a different data model. We leave them out of the base API.
Delete is harder than it looks
On one machine, delete just removes the entry. In a replicated store, removal has a trap. Suppose a replica is offline when you delete a key. When it returns, it still holds the old value. Other replicas have no entry. A repair process comparing them cannot tell whether the entry was deleted or was never written, and it may copy the stale value back. The deleted key reappears.
The standard fix is a tombstone. A tombstone is a marker that says "this key was deleted at this version". Replicas keep tombstones for a grace period, long enough for every replica to hear about the delete. After that, a background process removes them. We return to tombstones in the storage engine and repair chapters.
Request flow at a glance
The diagram shows the path a client request takes in the final design. Each box is the subject of a later chapter.
Common mistakes at this stage
- Skipping numbers. "Highly scalable" cannot be tested. "100,000 requests per second at p99 under 10 ms" can.
- Averaging latency. Averages hide slow requests. A few slow replies can ruin a page that makes many calls, so state targets as percentiles.
- Promising every property. You cannot have strong consistency, full availability, and minimal latency all at once under network failures. State which you favor. Our default is availability and low latency, with consistency that callers can tune. The consistency chapters explain why.
- Adding query features too early. Range scans and secondary indexes change how you partition data. Leave them out until you need them.
- Ignoring deletes. Treating delete as a plain removal causes deleted data to return after repair.
Where this leads
Each requirement points to a later chapter:
- Durability and fast writes lead to the log-structured storage engine.
- Scale leads to partitioning with consistent hashing.
- Availability leads to replication, quorums, and hinted handoff.
- Tunable consistency leads to read and write quorums and versioning.
- Operability leads to gossip, anti-entropy repair, and failure testing.
Exercise
A replica is down when a client deletes key "k". The delete is applied as a plain removal of the entry on the other two replicas. The down replica then returns, still holding the old value for "k". Why might "k" reappear, and what mechanism prevents it?
Show answer
Repair compares the replicas. Two have no entry and one has a value, and nothing marks the missing entries as a deliberate delete. The process treats the value as a write that the others missed and copies it back. A tombstone prevents this. It records the delete as a versioned entry, so repair sees that the delete is newer than the old value and spreads the delete instead. Tombstones are kept for a grace period and then removed.
Exercise
Using the scale targets in this chapter (1 billion keys, 1 KB average value, replication factor 3), how much total storage is needed for data, and why is the minimum node count by capacity not the real cluster size?
Show answer
Unique data is 1,000,000,000 × 1 KB = about 1 TB. With three replicas the total is about 3 TB. Capacity gives only a lower bound. The real size also depends on throughput (100,000 requests per second must be spread across nodes), fault tolerance (the system must keep serving when nodes fail), and disk headroom for compaction and growth. You size the cluster by whichever limit is tightest.