Inside a key-value store
medium 24 minA distributed key-value store keeps simple pairs on many machines.
Video lesson · Chapter 1 of 5
One key maps to three named replicas
A key-value store in 80 seconds
1:20Reel coming soon
Theory
Read or listen first. About 2 min.
What it is
A distributed key-value store is a non-relational database that keeps pairs, a key and its value, on many machines. The interface is tiny: get a key, put a key, delete a key.
The tiny interface is what makes it easy to spread out. Every request names exactly one key, so the store can work out from that key alone which machines to ask. No other machine has to take part.
Why it exists
One machine has a limited disk, a limited number of requests per second, and it can fail. Splitting the keys over machines solves the first two. Keeping copies on several machines solves the third.
The same handful of parts appears in many databases: a hash ring, replicas, a coordinator, quorums, versions and repair. If you can build this store on a whiteboard, you can explain how the others work and why they differ.
A short history
1987
Alan Demers and colleagues describe epidemic algorithms, in which database copies repair each other by exchanging updates with random partners.
1997
David Karger and colleagues publish consistent hashing, so that adding or removing a machine moves only a small share of the keys.
2007
Amazon publishes the Dynamo paper. It combines consistent hashing, virtual nodes, quorums, vector clocks, hinted handoff and Merkle trees in one store.
2012
Amazon launches DynamoDB, a managed service. It shares part of the name with Dynamo but is a different design.
Words to know
- Partitioning
- Splitting the keys so that each machine is responsible for a part of them.
- Replica
- One of the N copies of a key, each on a different machine.
- Coordinator
- The node that handles one request: it finds the replicas, asks them and answers the client.
- Quorum
- The number of replicas that must answer before a request counts as done: W for writes, R for reads.
- Preference list
- The ordered list of nodes that should hold a key, plus spares in case some are down.
- Anti-entropy
- Background work that compares copies and repairs the ones that differ.
How it works
Step through the idea, or press Play.
Place. Hash the key to a position and find its N machines
Understand it
Start here
A street with spare keys
Imagine a street where every house keeps a spare key for its neighbours. If a family locks itself out, the next houses can help. No house has to keep every key of the town, and no family depends on one single hook.
Machines are houses and keys are data. The rest of this page is about who holds what, and who is asked.
A library shows the same two ideas. One librarian cannot serve a million books, so several librarians each take the titles that begin with certain letters: that is partitioning. Popular books have copies at several desks: that is replication.
Goals
What the store must do
Low latency
A get or put should take milliseconds, also for the slowest 1%. A network trip and a disk write set the limit.
High throughput
Many operations at once, spread over all nodes.
Scalability
Add nodes to hold more data and serve more requests.
Fault tolerance
Keep working when a machine, a disk or a link fails.
Tunable consistency
Choose, for each use, between fresh answers and staying available.
Simple interface
Get, put and delete. No joins and no query planner.
What such a database offers its users, the data types and the key names, is the topic of key-value databases. This page looks inside the machine room.
Big picture
The parts
One request, three replicas
| Part | What it does |
|---|---|
| Client | Sends get, put or delete with a key |
| Load balancer or smart client | Picks a node; a smart client knows the ring and goes straight to a replica |
| Coordinator node | Receives the request, finds the replicas on the ring, sends the reads or writes, waits for the quorum, answers |
| Storage node | Keeps its ranges of keys on disk, serves local reads and writes, takes part in replication and repair |
| Membership list | Who is in the ring and which positions they own; every node keeps a copy |
Placement
Partitioning on a ring
There are three reasons to partition. There is more data than fits on one machine. The work can run in parallel on many machines. And a failure touches only a part of the data.
Consistent hashing places keys and nodes on the same circle, for example the numbers from 0 to . To find the owner of a key, hash it and walk clockwise to the first node. Take nodes A, B, C and D at 0%, 25%, 50% and 75% of the circle. A key at 48% belongs to C.
Four nodes, evenly placed
| Node | Position | Owns keys from | Also holds copies for |
|---|---|---|---|
| A | 0% | 75% to 100% | D and C |
| B | 25% | 0% to 25% | A and D |
| C | 50% | 25% to 50% | B and A |
| D | 75% | 50% to 75% | C and B |
If a node joins a ring of N nodes, about K / (N + 1) of the K keys get a new owner. With plain hash mod N nearly every key would move. The proof and the lookup code live in consistent hashing.
Even load
Virtual nodes
Many positions for each machine
- The ranges even out
- A new node takes a little from many machines
- A stronger machine gets more positions
- After a failure, many machines share the extra load
One position for each machine
- Random positions leave big and small ranges
- A new node takes load from one neighbour only
- A strong and a weak machine get the same chance
How many? More positions spread the load better but make the ring bigger and repairs more scattered. Values from 100 to 256 were common in early designs; Cassandra once used 256 and now ships with 16 together with a smarter way to choose them. Riak divides the ring into a fixed number of partitions and shares those out.
Copies
Replication and quorums
Copies give durability, because data survives a lost node. They give availability, because another replica can answer. And they can give locality, because a copy may be close to the user. With a replication factor N = 3, a key sits on three consecutive machines of the ring.
The overlap rule
| Setting | Name | Read waits for | Write waits for | Note |
|---|---|---|---|---|
| N=3, W=2, R=2 | Balanced | 2 | 2 | Both survive one lost replica |
| N=3, W=1, R=3 | Fast writes | 3 | 1 | One lost replica stops reads |
| N=3, W=3, R=1 | Fast reads | 1 | 3 | One lost replica stops writes |
| N=3, W=1, R=1 | Fastest | 1 | 1 | Reads may be old: 2 is not more than 3 |
How often is a quorum available?
Write path
A put, step by step
- 1
Client request
PUT user:123arrives at a node, which becomes the coordinator. - 2
Hash the key
The hash starts with 7A in hexadecimal. That is 122 of 256, so about 48% of the way round.
- 3
Find the nodes
Walking clockwise from 48% gives C, then D, then A.
- 4
Write the replicas
The new version goes to all three at the same time.
- 5
Wait for the quorum
With W = 2 the coordinator waits for two answers. The third may come later.
- 6
Respond
Success after two answers. If two do not arrive in time, the client gets an error, and the write may still have reached one node.
A write with one slow replica
Read path
A get, step by step
- 1
Ask the replicas
The same hash gives C, D and A. The coordinator asks them and uses the first R = 2 answers.
- 2
Reconcile
It compares the versions. If one descends from the other, the newer one wins. If they are concurrent, the store's rule decides or the client gets both.
- 3
Respond
The value goes back to the client, with its version, so that a later write can say what it was based on.
- 4
Repair
If one replica was behind, the coordinator sends it the newer version. This is read repair.
A read that finds an old copy
How a store tells newer from concurrent is the topic of versioning data.
Growing
A node joins
- 1
Join
An operator adds node E. Joining is a deliberate step, so that a restart is not mistaken for a new machine.
- 2
Choose positions
E gets its positions on the ring. In our example, one position at 62%.
- 3
Identify the keys
Keys from 50% to 62% now belong to E instead of D.
- 4
Stream the data
The neighbours copy the ranges that E must hold, while they keep serving them: 50% to 62%, and copies of 25% to 50% and 0% to 25%.
- 5
Update the ring
The new membership spreads to all nodes, usually by gossip.
- 6
Finish
E serves its ranges. The old holders may delete what they no longer need.
Who gives data to E?
Sizing
How many nodes?
An example with stated assumptions: 200 million keys of 1 KB each, an average of 100,000 reads and 10,000 writes a second, N = 3, R = 2, nodes with 500 GB that should stay below 70% full, and 50,000 local operations a second for each node.
Storage and load
When things fail
Repair and conflicts
| Tool | When it works | What it does |
|---|---|---|
| Hinted handoff | During a write | Another node keeps the write for a node that is down |
| Read repair | During a read | An old replica that shows up in a read gets the new version |
| Merkle trees | In the background | Two replicas compare hashes and copy only what differs |
| Periodic sync | In the background | All ranges are checked sooner or later, including keys nobody reads |
When two versions conflict
| Rule | How | Cost |
|---|---|---|
| Last write wins | The highest timestamp stays | The other write is lost, and clocks disagree |
| Vector clocks | Counters show whether one version saw the other | Finds conflicts but does not settle them |
| CRDT | A data type whose copies merge to the same result | Only certain types |
| Application | All versions go back to the client, which merges them | More work in the client |
During a network split: which side are you on?
Leaning to available
- The Dynamo design, Cassandra and Riak with low R and W
- Writes are nearly always accepted
- Conflicts are settled later
Leaning to consistent
- etcd, ZooKeeper and Consul
- The minority side may refuse requests
- A majority agrees first, with Raft or a similar protocol
Higher R and W give fresher answers and longer waits. DynamoDB does not fit one label: a read is eventually consistent by default and strongly consistent if you ask for it, so look at the request and not only at the product. See consistency models.
In practice
Using such a store well
Do
- Design keys for the questions you ask, for example a partition key plus a sort key
- Make writes idempotent, because a timed-out write may have worked
- Use conditional writes to protect a change
- Know your query patterns before you choose keys
- Watch for hot partitions
Do not
- Use a key with few values, or today's date, to partition by
- Store large values: DynamoDB allows 400 KB for an item
- Serve your main query from a secondary index that may lag
- Forget that a read may be old
- Skip capacity planning
Good fit
- Session storage
- User profiles and preferences
- Shopping carts
- A caching layer
- Leaderboards, if the store has sorted sets
Not ideal
- Complex queries with joins
- ACID transactions across many keys, unless the store offers them
- Data with many relationships
- Work that depends on many secondary indexes
import boto3from botocore.exceptions import ClientErrortable = boto3.resource("dynamodb").Table("Users")def key(user_id): return {"pk": f"USER#{user_id}", "sk": "PROFILE"}def guarded(call): try: call() return True except ClientError as e: if e.response["Error"]["Code"] == "ConditionalCheckFailedException": return False # somebody was faster raisedef create_user(user_id, data): return guarded(lambda: table.put_item( Item={**data, **key(user_id), "version": 1}, ConditionExpression="attribute_not_exists(pk)"))def get_user(user_id): return table.get_item(Key=key(user_id), ConsistentRead=True).get("Item")def update_user(user_id, data, version): return guarded(lambda: table.update_item( Key=key(user_id), UpdateExpression="SET #d = :d, #v = :next", ConditionExpression="#v = :now", ExpressionAttributeNames={"#d": "data", "#v": "version"}, ExpressionAttributeValues={":d": data, ":next": version + 1, ":now": version}))Summary
The whole topic in one minute.
Hash the key to find its place on a ring, walk clockwise to find the first N different machines, send the write to all of them and wait for W answers. For a read, wait for R answers and take the newest version.
Everything else follows from the fact that machines fail and messages get lost. Virtual nodes keep the load even, versions tell old values from new ones, hints and Merkle trees repair copies that missed a write, and R and W let each use choose between speed, freshness and availability.
- A key alone decides its machines: hash it and walk clockwise to N different nodes.
- The coordinator is a role that any node can play.
- A write goes to all N replicas and waits for W; a read waits for R; overlap needs R + W greater than N.
- Virtual nodes even out load and spread the work of joins and failures.
- Hints, read repair and Merkle trees bring late copies up to date.
- Size for the peak and for the busiest key, not only for storage.