AlgoViz

Versioning data and tunable quorums

medium 24 min

When 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

0:00 / 4:13

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

  1. 1988

    Colin Fidge and Friedemann Mattern independently publish the papers usually cited for vector clocks.

  2. 2007

    The Dynamo paper describes a production store that attaches vector clocks to its values and hands conflicting versions to the application.

  3. 2011

    Marc Shapiro and colleagues formally define conflict-free replicated data types (CRDTs).

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

Step 1 of 3

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.

What the stamps tell
Our storyAshaLee

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

Client 1 writes B to node A, which then holds version A2. Client 2 writes C to node B, which then holds version A1 B1. Client 3 reads from both nodes and gets both values with their versions.
Pink arrows are writes, blue arrows are reads. The versions show that neither writer had seen the other value.

What a fast clock destroys

tstamp=ttrue+5 sA at 100→105,B at 103→103⇒A winst_{\text{stamp}} = t_{\text{true}} + 5\text{ s} \qquad \text{A at }100 \to 105,\quad \text{B at }103 \to 103 \quad\Rightarrow\quad \text{A wins}
B wrote 3 seconds later, yet the older value from A stays. Every write on B within 5 seconds after one on A is lost.

Overview

Four kinds of versions

VersionHowGoodWeak
TimestampThe time of the writeSimpleClocks differ, conflicts stay hidden
Version numberA counter for each keyNo clocks neededNeeds one place that counts
Vector clockA counter for each nodeFinds concurrent writesGrows with the number of writers
Dotted version vectorA vector plus an exact mark for this writeFewer false siblings with many clientsMore 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

No lock is held while a client thinks. Only the loser of a race repeats its work.
Python
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))
Optimistic locking in Amazon DynamoDB with a growing, random wait between attempts. It needs boto3 and an account, so it does not run here.

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

StepNode ANode B
A writes X = 1[A:1] X = 1nothing 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
A missing entry counts as 0, so [A:1] and [A:1, B:0] are the same. In the last row neither version contains the other.

Three outcomes

V<W  ⟺  (∀i:Vi≤Wi)∧V≠WV∥W  ⟺  V≰W∧W≰VV < W \iff (\forall i: V_i \le W_i) \wedge V \ne W \qquad V \parallel W \iff V \not\le W \wedge W \not\le V
Read the first as: V happened before W, so W replaces it. Read the second as: V and W are concurrent. If all counters are equal, it is the same version.

Compare these

VWResult
[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.

TypeAllowsMerge
G-CounterOnly addLargest count of each node, then sum
G-SetOnly add elementsUnion
PN-CounterAdd and subtractTwo G-Counters, one for each direction
LWW-RegisterReplace one valueHighest timestamp, with a tie rule
OR-SetAdd and remove elementsUnion of unique tags, minus the removed tags
The price: only certain types, and some keep tombstones that grow until they can be cleaned up safely.

A counter on two nodes

Each node raises only its own part, so the larger count always contains the smaller one.

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

NameRWEffectFor example
Overlapping22A read meets the last finished writeUser profiles, orders
Read-heavy13Fast reads, writes need all copiesContent, catalogues
Write-heavy31Fast writes, reads need all copiesLogs, metrics
Eventual11Fastest, may be oldCaches, view counts
W = 1 also means that one lost machine can lose a write that was already confirmed.

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.

SQL
CONSISTENCY QUORUM;SELECT * FROM users WHERE id = '123';CONSISTENCY ONE;INSERT INTO users (id, name) VALUES ('123', 'Alice');
cqlsh: the level stays until you change it.
JavaScript
const result = await client.send(new GetCommand({  TableName: "Users",  Key: { id: "123" },  ConsistentRead: true,}));
DynamoDB: a fresh read for this request only.

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

Cassandra's default read repair is blocking: the client waits for it, so two quorum reads in a row do not go back in time.

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

DynamoDBCassandraRiak KV
Version you seeYour own version attribute, if you add oneA timestamp for each cellA causal context
ConflictsConditional writes; last writer wins between Regions by defaultLast write winsSiblings, or last write wins, as configured
Choice for each requestEventual or strongly consistent readANY, ONE, TWO, THREE, QUORUM, LOCAL_QUORUM, EACH_QUORUM, ALLR and W for a request or bucket
Merging typesAtomic number updatesCounter columnsCounters, sets, maps, flags, registers
DeletesItem removed, conditions possibleTombstones, kept 10 days by defaultTombstones
DynamoDB also offers transactions over several items. Cassandra also offers expiry times (TTL) and lightweight transactions for conditions.

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.

Sources