Key-Value Store: Choosing Consistency
Last-write-wins is a rule that resolves two conflicting writes by keeping the one with the later time stamp. This lesson deep-dives one part of the design, choosing how consistent each request must be.
One key, two kinds of read
An eventual read asks the first copy and may get the older value. A strong read asks every copy and takes the newest version.
copies = [("copy A", "red", 2), ("copy B", "blue", 3)]
print("eventual read asks copy A ->", copies[0][1])
best = copies[0]
for entry in copies:
if entry[2] > best[2]:
best = entry
print("strong read asks every copy ->", best[1])Last-write-wins keeps the later time stamp, not the last arrival
The 3 writes for one key arrive out of order. The kept value is the one with the highest time stamp, not the one that arrived last.
arrivals = [(5, "red"), (9, "blue"), (7, "green")]
kept = arrivals[0]
for stamp, value in arrivals:
print("arrived: time", stamp, "value", value)
if stamp > kept[0]:
kept = (stamp, value)
print("kept:", kept[1], "from time", kept[0])A slow clock can erase a newer write
The newer write carries the smaller time stamp because its server clock runs slow. Last-write-wins keeps the older write, and the newer write is lost.
arrivals = [(10, "old address"), (8, "new address")]
kept = arrivals[0]
for stamp, value in arrivals:
print("arrived: time", stamp, "value", value)
if stamp > kept[0]:
kept = (stamp, value)
print("kept:", kept[1])
print("newer write kept:", kept[1] == "new address")Example
arrivals = [(12, "Ana"), (15, "Ana Lee"), (13, "A. Lee")]
kept = arrivals[0]
for stamp, value in arrivals:
print("arrived: time", stamp, "value", value)
if stamp > kept[0]:
kept = (stamp, value)
print("kept:", kept[1], "from time", kept[0])Key points
- Strong consistency: a read returns the latest finished write, even when the read must ask more copies to be sure.
- Eventual consistency: a read may return an older value for a short time, and the copies agree later.
- Per-request choice: each request picks strong or eventual, so one key can serve both kinds of read.
- Last-write-wins: a conflict rule that keeps the write with the later time stamp and drops the other.
- Clock risk: server clocks can run slightly fast or slow, so the later time stamp is not always the truly newer write.
In this example, 3 writes for one profile name arrive out of order and the write stamped 15 is kept. It did not arrive last, and last-write-wins does not care about arrival order.
Note
vector clocks are a stronger tool for tracking which write came first, and a later course covers them.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What is the honest risk of last-write-wins?