Versioning data and tunable quorums
medium 24 minWhen several machines accept changes to the same key, a store needs versions to tell newer from conflicting.
Video lesson · Chapter 1 of 5
Two copies accept different edits to the same label
Two drafts, one story
1:20Reel coming soon
Theory
Read or listen first. About 2 min.
What it is
Versioning means attaching something to each value that says where it stands in the history of its key. With it, a store can look at two copies and decide: this one is newer, they are the same, or neither has seen the other.
The last case is a conflict. Versions find it, but they do not settle it. For that the store needs a rule: keep one, keep both, or merge them.
Why it exists
In a replicated store, two nodes can change the same key at the same time, for example while the link between them is down. Without versions, whichever copy arrives last quietly replaces the other. Nobody gets an error, and an update is gone.
Clocks alone do not help enough. Two machines never agree exactly on the time, and a later timestamp does not mean that the writer had seen the earlier value. What matters is not when a change happened but what it was based on.
A short history
1988
Colin Fidge and Friedemann Mattern independently publish the papers usually cited for vector clocks.
2007
The Dynamo paper describes a production store that attaches vector clocks to its values and hands conflicting versions to the application.
2011
Marc Shapiro and colleagues formally define conflict-free replicated data types (CRDTs).
2012
Nuno Preguiça and colleagues present dotted version vectors, which handle many clients writing through a few servers.
Words to know
- Version
- Data attached to a value that places it in the history of its key.
- Happened before
- Version V happened before W if W was made by someone who had seen V, directly or through others.
- Concurrent
- Neither version has seen the other.
- Siblings
- Concurrent versions of one key that the store keeps side by side.
- Last write wins
- A rule that keeps the version with the highest timestamp and drops the others.
- CRDT
- A data type whose copies can be merged in any order with the same result.
- Context
- The version a client read, sent back with its write to show what the write is based on.
How it works
Step through the idea, or press Play.
Stamp. Every write carries a version that shows what it was based on
Understand it
Start here
Two drafts of one story
Imagine two friends who write one story together. Each friend has a stamp in their own colour and presses it once for every change. Afterwards the stamps show who had seen what.
The stamps do not say which line is better. They only say that nobody had seen both.
A shared document has the same problem. When Alice and Bob type in the same paragraph at the same moment, the editor needs to know what each of them had seen before it can merge their changes.
The problem
Three ways to go wrong
Lost update
Client A writes X = 10 and client B writes X = 20 at the same time. One of them disappears without an error.
Clock skew
The clock of node A is 5 seconds ahead. Its timestamps win against writes that really came later.
Lost causality
From the values alone nobody can tell whether A led to B or whether they were independent.
Two writers, two nodes
What a fast clock destroys
Overview
Four kinds of versions
| Version | How | Good | Weak |
|---|---|---|---|
| Timestamp | The time of the write | Simple | Clocks differ, conflicts stay hidden |
| Version number | A counter for each key | No clocks needed | Needs one place that counts |
| Vector clock | A counter for each node | Finds concurrent writes | Grows with the number of writers |
| Dotted version vector | A vector plus an exact mark for this write | Fewer false siblings with many clients | More complex |
Strictly, a vector clock orders events in processes and a version vector orders copies of data. The idea and the comparison are the same, and people often say vector clock for both. The way counters turn into identifiers is covered in unique IDs with causality.
One counter
Version numbers and conditional writes
If one place decides about a key, a plain number is enough. Read the value with its version, change it, and write it back only if the version is still the same. This is optimistic locking, also called compare and set.
The second writer notices
import random, time, boto3from botocore.exceptions import ClientErrortable = boto3.resource("dynamodb").Table("Items")class Conflict(Exception): passdef update_with_version(item_id, data, expected): try: return table.update_item( Key={"id": item_id}, UpdateExpression="SET #d = :d, #v = :next", ConditionExpression="#v = :now", ExpressionAttributeNames={"#d": "data", "#v": "version"}, ExpressionAttributeValues={":d": data, ":next": expected + 1, ":now": expected}, ReturnValues="ALL_NEW")["Attributes"] except ClientError as e: if e.response["Error"]["Code"] == "ConditionalCheckFailedException": raise Conflict(item_id) raisedef update_with_retry(item_id, change, attempts=3): for i in range(attempts): item = table.get_item(Key={"id": item_id}, ConsistentRead=True)["Item"] try: return update_with_version(item_id, change(item["data"]), item["version"]) except Conflict: if i == attempts - 1: raise time.sleep(random.uniform(0, 0.1 * 2 ** i))Many counters
Vector clocks
A vector clock is a list of pairs, node and counter, attached to a version. The node that handles a write raises its own counter. [A:2, B:1] means: this version includes two writes handled by A and one by B.
Node A and node B, step by step
| Step | Node A | Node B |
|---|---|---|
| A writes X = 1 | [A:1] X = 1 | nothing yet |
| B receives it | [A:1] X = 1 | [A:1] X = 1 |
| A writes X = 5 | [A:2] X = 5 | [A:1] X = 1 |
| B writes X = 10 | [A:2] X = 5 | [A:1, B:1] X = 10 |
Three outcomes
Compare these
| V | W | Result |
|---|---|---|
| [A:1] | [A:2, B:1] | V happened before W |
| [A:2] | [A:1, B:1] | Concurrent |
| [A:2, B:1] | [A:1, B:2] | Concurrent |
| [A:2, B:1] | [A:2, B:1] | The same version |
A client must send the version it read, the context, along with its write. Without it the store cannot know what the write was based on. And the list grows with every node that handles a write. The Dynamo paper cuts the oldest pair beyond a limit, for example 10 pairs, and accepts that the history is then less exact.
Refined
Dotted version vectors
Suppose two clients both read [A:1] and both write through node A. A plain server-side vector gives the first [A:2] and the second [A:3]. It now looks as if the second had seen the first, which is false. If the server keeps both as siblings with one common vector instead, it cannot tell later which sibling a new write has really seen, and siblings pile up.
A dotted version vector keeps the vector of what the client had seen, here [A:1], and adds a dot for this one write: (A, 2) for the first and (A, 3) for the second. Both were based on [A:1], so they are clearly concurrent. A client that has seen both sends a context that covers both dots, and the store can drop exactly those two. Riak recommends dotted version vectors over vector clocks since version 2.0 for this reason.
Settle it 1
Last write wins
Attach a timestamp to each write. Write 1 sets X to A at time 100, write 2 sets X to B at time 105, so B stays.
Good
- Simple to build
- No siblings to manage
- Fine when values are written once, or the newest reading is all that counts
Costs
- The other write is lost without an error
- The result depends on synchronized clocks
- Read, change, write back is not safe with it
Settle it 2
Siblings
Keep all concurrent versions and return them on a read. [A:2, B:1] with the value Alice and [A:1, B:2] with the value Bob both come back, and the application merges them. The merged write carries a context that covers both, so it replaces them.
Good
- No accepted write is lost
- The application knows what a good merge is
Costs
- More work in every client
- Sibling explosion, if nobody merges or clients write without a context
Settle it 3
Types that merge by themselves
A CRDT has a merge function for which order, grouping and repetition do not matter. Copies that have received the same updates are equal, whatever the order was. That promise is called strong eventual consistency.
| Type | Allows | Merge |
|---|---|---|
| G-Counter | Only add | Largest count of each node, then sum |
| G-Set | Only add elements | Union |
| PN-Counter | Add and subtract | Two G-Counters, one for each direction |
| LWW-Register | Replace one value | Highest timestamp, with a tie rule |
| OR-Set | Add and remove elements | Union of unique tags, minus the removed tags |
A counter on two nodes
Tuning
N, R and W
N is the number of copies, W how many must store a write and R how many must answer a read before the client gets its reply. If R + W is greater than N, the two sets share at least one copy.
Four settings for N = 3
| Name | R | W | Effect | For example |
|---|---|---|---|---|
| Overlapping | 2 | 2 | A read meets the last finished write | User profiles, orders |
| Read-heavy | 1 | 3 | Fast reads, writes need all copies | Content, catalogues |
| Write-heavy | 3 | 1 | Fast writes, reads need all copies | Logs, metrics |
| Eventual | 1 | 1 | Fastest, may be old | Caches, view counts |
Choosing for one feature
Many stores let you choose for each request. DynamoDB has a flag for a strongly consistent read. In Cassandra the level is set in the driver or, in the shell cqlsh, with the command CONSISTENCY. It is not part of the query language.
CONSISTENCY QUORUM;SELECT * FROM users WHERE id = '123';CONSISTENCY ONE;INSERT INTO users (id, name) VALUES ('123', 'Alice');const result = await client.send(new GetCommand({ TableName: "Users", Key: { id: "123" }, ConsistentRead: true,}));Catching up
Read repair
A read asks several replicas. Nodes A and C answer with version 3, node B with version 2. The client gets version 3, and the store sends version 3 to B. Data that people read heals by itself.
A read that heals
It needs no separate scan, but it does cost extra writes, and it never reaches keys that nobody reads. For those there is anti-entropy.
In practice
Three stores compared
| DynamoDB | Cassandra | Riak KV | |
|---|---|---|---|
| Version you see | Your own version attribute, if you add one | A timestamp for each cell | A causal context |
| Conflicts | Conditional writes; last writer wins between Regions by default | Last write wins | Siblings, or last write wins, as configured |
| Choice for each request | Eventual or strongly consistent read | ANY, ONE, TWO, THREE, QUORUM, LOCAL_QUORUM, EACH_QUORUM, ALL | R and W for a request or bucket |
| Merging types | Atomic number updates | Counter columns | Counters, sets, maps, flags, registers |
| Deletes | Item removed, conditions possible | Tombstones, kept 10 days by default | Tombstones |
Do
- Use conditional writes when two clients may change one value
- Carry the version through read, change and write
- Make operations safe to repeat
- Use CRDTs where they fit
- Watch the number of siblings
Do not
- Trust wall clocks alone
- Leave the conflict rule to chance
- Pay for strong consistency everywhere
- Ignore a refused version
- Skip tests with concurrent writers
Summary
The whole topic in one minute.
A version answers one question: had the writer of this value seen that other value? A version number answers it with one writer, a vector clock answers it with many. If neither had seen the other, the versions are concurrent.
Then you choose a rule. Last write wins is simple and loses data. Siblings lose nothing and make the client work. CRDTs merge by themselves, for the types that allow it. N, R and W decide how many copies take part, so you can tune freshness against speed and availability for each operation.
- Versions say what a write was based on; timestamps only say when.
- One deciding place: a version number and a conditional write.
- Many writers: a vector clock finds concurrent versions.
- Last write wins loses data, siblings need merging, CRDTs merge themselves.
- R + W greater than N gives overlap, not transactions.
- Read repair heals what is read; the rest needs a background check.