AlgoViz

Inside a key-value store

medium 24 min

A distributed key-value store keeps simple pairs on many machines.

Video lesson · Chapter 1 of 5

One key maps to three named replicas

0:00 / 3:54

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

  1. 1987

    Alan Demers and colleagues describe epidemic algorithms, in which database copies repair each other by exchanging updates with random partners.

  2. 1997

    David Karger and colleagues publish consistent hashing, so that adding or removing a machine moves only a small share of the keys.

  3. 2007

    Amazon publishes the Dynamo paper. It combines consistent hashing, virtual nodes, quorums, vector clocks, hinted handoff and Merkle trees in one store.

  4. 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.

Step 1 of 3

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.

Who keeps whose keys?
1122334455

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

Clients send get and put requests through a load balancer to a coordinator node. The coordinator writes to storage nodes C, D and A, three replicas of the key. Node B is in the same ring but does not hold this key.
Pink is the write. Node B takes part in the ring but not in this request.
PartWhat it does
ClientSends get, put or delete with a key
Load balancer or smart clientPicks a node; a smart client knows the ring and goes straight to a replica
Coordinator nodeReceives the request, finds the replicas on the ring, sends the reads or writes, waits for the quorum, answers
Storage nodeKeeps its ranges of keys on disk, serves local reads and writes, takes part in replication and repair
Membership listWho is in the ring and which positions they own; every node keeps a copy
The coordinator is a role, not a special machine. Any node can play it, so it is not a single point of failure.

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 2128−12^{128} - 1. 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

NodePositionOwns keys fromAlso holds copies for
A0%75% to 100%D and C
B25%0% to 25%A and D
C50%25% to 50%B and A
D75%50% to 75%C and B
With N = 3, each node holds its own range and the ranges of the two nodes before it.

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

R+W>NN=3,;W=2,;R=2:;2+2=4>3R + W > N \qquad N=3,; W=2,; R=2:; 2+2 = 4 > 3
Any two replicas that answered the read and any two that stored the write share at least one machine. So the read meets the newest finished write.
SettingNameRead waits forWrite waits forNote
N=3, W=2, R=2Balanced22Both survive one lost replica
N=3, W=1, R=3Fast writes31One lost replica stops reads
N=3, W=3, R=1Fast reads13One lost replica stops writes
N=3, W=1, R=1Fastest11Reads may be old: 2 is not more than 3
A write is sent to all N replicas in every case. W only says how many answers to wait for.

How often is a quorum available?

p=0.99:3p2(1−p)+p3=0.0294+0.9703=0.9997p = 0.99:\quad 3p^2(1-p) + p^3 = 0.0294 + 0.9703 = 0.9997
Assuming that each node is up 99% of the time and that nodes fail independently. Two of three are then up 99.97% of the time.

Write path

A put, step by step

  1. 1

    Client request

    PUT user:123 arrives at a node, which becomes the coordinator.

  2. 2

    Hash the key

    The hash starts with 7A in hexadecimal. That is 122 of 256, so about 48% of the way round.

  3. 3

    Find the nodes

    Walking clockwise from 48% gives C, then D, then A.

  4. 4

    Write the replicas

    The new version goes to all three at the same time.

  5. 5

    Wait for the quorum

    With W = 2 the coordinator waits for two answers. The third may come later.

  6. 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

The client does not wait for the slowest replica. That is how quorums cut the slow tail of response times.

Read path

A get, step by step

  1. 1

    Ask the replicas

    The same hash gives C, D and A. The coordinator asks them and uses the first R = 2 answers.

  2. 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. 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. 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. 1

    Join

    An operator adds node E. Joining is a deliberate step, so that a restart is not mistaken for a new machine.

  2. 2

    Choose positions

    E gets its positions on the ring. In our example, one position at 62%.

  3. 3

    Identify the keys

    Keys from 50% to 62% now belong to E instead of D.

  4. 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. 5

    Update the ring

    The new membership spreads to all nodes, usually by gossip.

  6. 6

    Finish

    E serves its ranges. The old holders may delete what they no longer need.

Who gives data to E?

Each arrow is a copy that moves. With N = 3 the next three nodes each give up one copy; D keeps 50% to 62% as a second copy behind E. With virtual nodes the sources are many small ranges instead.

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

200M×1 KB×3500 GB×0.7=600350→23×(100k×2+10k×3)50k=690k50k→14\frac{200\text{M} \times 1\text{ KB} \times 3}{500\text{ GB} \times 0.7} = \frac{600}{350} \to 2 \qquad \frac{3 \times (100\text{k} \times 2 + 10\text{k} \times 3)}{50\text{k}} = \frac{690\text{k}}{50\text{k}} \to 14
Peak is 3 times the average. A read costs 2 local operations and a write costs 3. Load decides, so 14 nodes, plus spare ones for failures. Storage alone would need 2, but N = 3 needs at least 3.

When things fail

Repair and conflicts

ToolWhen it worksWhat it does
Hinted handoffDuring a writeAnother node keeps the write for a node that is down
Read repairDuring a readAn old replica that shows up in a read gets the new version
Merkle treesIn the backgroundTwo replicas compare hashes and copy only what differs
Periodic syncIn the backgroundAll ranges are checked sooner or later, including keys nobody reads
The first two are best effort. Details in fault tolerance and failure detection.

When two versions conflict

RuleHowCost
Last write winsThe highest timestamp staysThe other write is lost, and clocks disagree
Vector clocksCounters show whether one version saw the otherFinds conflicts but does not settle them
CRDTA data type whose copies merge to the same resultOnly certain types
ApplicationAll versions go back to the client, which merges themMore work in the client

During a network split: which side are you on?

The choice only arises during a split. It is explained in the CAP theorem topic.

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
Python
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}))
Amazon DynamoDB from Python: create only if absent, read fresh, update only if nobody else did. It needs the boto3 library and an account, so it does not run here.

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.

Sources