Algorithms · Working together

Vector clocks

How Amazon’s cart never loses the thing you added. Two servers each think they have the latest cart. A list of counters can tell who saw what.

The problem

Picture the shopping cart during a busy sale. Your cart lives on several servers, and a network hiccup cuts two of them off from each other. You tap "add to cart" on your phone, and your laptop adds something else. Both taps land on different servers.

Amazon's 2007 paper Dynamo: Amazon's Highly Available Key-value Store describes a store that always accepts writes, even during network failures. Refusing your tap would be worse than a messy cart. So the hard question is what to do when the servers reconnect and disagree.

The obvious way

Keep whichever copy was saved last by the wall clock, a rule called last-writer-wins. It's simple, but it fails here. Both servers made a valid edit starting from the same cart, and neither saw the other's. Picking one throws the other away, so an item you added silently vanishes. Server clocks also drift, so "last" can be a guess.

The clever idea

Think of two coworkers editing printed copies of a shared shopping list. Each initials the page every time they change it. Later you can tell whether one copy already includes the other's changes, or whether they each changed it on their own. In Dynamo, every version carries a vector clock: a list of (server, counter) pairs recording who has edited it, and how many times.

To compare two clocks, check every entry. If one clock is greater or equal in every entry, it supersedes the other: it already knows about those edits. If neither wins everywhere, the edits are concurrent. Dynamo keeps both versions, and the client reconciles them. For a cart, that means merging.

How the code does it

Both servers start from one shared cart, so the first save gives clock {A: 1}. Then A's edit makes {A: 2} while B's edit makes {A: 1, B: 1}. A is ahead on A's counter, B is ahead on B's, so compare returns concurrent.

Now the two strategies split. Last-writer-wins just looks at the timestamps and drops the pen. The vector clock branch sees the conflict and keeps both items. The table at the end shows the difference: one cart has two items and the other has three.

Trade-offs

Dynamo gives up simplicity for availability. Conflicting versions must be stored and reconciled by the client, and a merged cart can't always tell a deliberate removal from a missing add, so deleted items can resurface. If you need one strict answer at all times, like a bank balance, don't use this approach.

Where else you'll see it

The same idea of tracking causality and merging concurrent edits shows up in other systems that stay writable during network trouble, including collaborative editors and some distributed databases.

Suppose clockA = {A:2, B:1} and clockB = {A:1, B:1}. What does compare(clockA, clockB) return?

  • "after"
  • "before"
  • "concurrent"
Show the answer

"after". A's clock is greater or equal in every entry (2 ≥ 1 and 1 ≥ 1), so A already includes B's history and supersedes it.

Change it and see
  • Set timeB to 99.0 and rerun
  • Make clockB = bump(clockA, "B")
  • Add a third item to cartB

The code

Python, with what each line means beside it. It compares the clever way with keeping whichever copy has the latest clock time.

def bump(clock, node):Define a helper that ticks a clock
new = dict(clock)Copy the clock so the old one stays
new[node] = new.get(node, 0) + 1Add one to this server's counter
return newHand back the new clock
def compare(c1, c2):Define how to compare two clocks
nodes = set(c1) | set(c2)Gather every server named in either
ge1 = all(c1.get(n, 0) >= c2.get(n, 0) for n in nodes)Is clock one at least as big everywhere?
ge2 = all(c2.get(n, 0) >= c1.get(n, 0) for n in nodes)Is clock two at least as big everywhere?
if ge1: return "after"If so, clock one is newer: after
if ge2: return "before"If the reverse, clock one is older: before
return "concurrent"Neither wins everywhere: concurrent
def merge(c1, c2):Define how to merge two clocks
return {n: max(c1.get(n, 0), c2.get(n, 0)) for n in set(c1) | set(c2)}Keep the biggest counter per server
base = bump({}, "A")Server A saves the first cart, ticks A
clockA = bump(base, "A")A adds a pen and ticks again
clockB = bump(base, "B")B adds a lamp and ticks its own counter
cartA = ["book", "pen"]A's cart now holds book and pen
cartB = ["book", "lamp"]B's cart holds book and lamp
timeA, timeB = 100.0, 100.5B's wall clock runs half a second ahead
print("A:", clockA, "B:", clockB)Print both clocks
verdict = compare(clockA, clockB)Compare the two clocks
print("A vs B:", verdict)Print the verdict
lww = cartA if timeA > timeB else cartBObvious way: newest wall time wins
if verdict == "concurrent":If the edits were concurrent...
smart = sorted(set(cartA) | set(cartB))keep the union of both carts
print("merged clock:", merge(clockA, clockB))and print the merged clock
else:Otherwise...
smart = cartA if verdict == "after" else cartBkeep whichever cart is newer
show([Show a table of both outcomes
{"way": "last-writer-wins", "cart": ", ".join(lww), "items": len(lww)},Row: the last-writer-wins result
{"way": "vector clocks", "cart": ", ".join(smart), "items": len(smart)},Row: the vector clock result
], "same two writes, two outcomes")Label the table

Read more

Run it. Then change it.

The code runs right in the page and draws as it goes. Free, nothing to install.

More on working together