🎓 A1Learner
🔍
0 of 47 lessons completed

Strong and Eventual Consistency

Strong consistency is a rule where a write finishes only after every copy holds the new value. Eventual consistency is a rule where a write finishes early and the copies agree a little later.

A strong write updates every copy first

The write changes both copies before it finishes. Only then does a read run, and the read returns the new value.

copies = ["Ada", "Ada"]
print("Before the write:", copies)
copies[0] = "Grace"
print("After copy one updates:", copies)
copies[1] = "Grace"
print("After copy two updates:", copies)
print("Write finished. Read from copy two:", copies[1])

An eventual write finishes after one copy

The write finishes as soon as the first copy changes. A read from the second copy still returns the old value, so that read is stale.

copies = ["Ada", "Ada"]
copies[0] = "Grace"
print("Write finished. Copies:", copies)
print("Read from copy two:", copies[1])
print("Read is stale:", copies[1] != "Grace")

Counting stale reads

Reads run in a fixed order while the second copy catches up. The counter shows how many of those reads were stale.

copies = ["Grace", "Ada"]
latest = "Grace"
stale_reads = 0
read_value = copies[1]
if read_value != latest:
    stale_reads = stale_reads + 1
print("First read:", read_value)
copies[1] = latest
read_value = copies[1]
if read_value != latest:
    stale_reads = stale_reads + 1
print("Second read:", read_value)
print("Stale reads:", stale_reads)

Example

print("Strong write")
strong = ["Ada", "Ada"]
strong[0] = "Grace"
strong[1] = "Grace"
print("Copies when the write finishes:", strong)
print("Read from copy two:", strong[1])
print("Eventual write")
eventual = ["Ada", "Ada"]
eventual[0] = "Grace"
print("Copies when the write finishes:", eventual)
print("Read from copy two:", eventual[1])
eventual[1] = "Grace"
print("Copies a little later:", eventual)

Key points

  • Strong consistency: a read after a finished write always returns the new value.
  • Eventual consistency: every copy reaches the new value after a short delay.
  • Stale read: a read that returns the old value before the copies agree.
  • Replication lag: the delay while a new value travels to the remaining copies.
  • Use strong consistency to protect values where an old answer would be wrong in a costly way.

In this example, the strong write leaves both copies holding the new value at finish time. The eventual write finishes with one old copy, and that copy catches up a little later.

Note

eventual consistency makes writes faster, and a few stale reads are the price.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

A write finishes, and a read from another copy returns the old value a moment later. Which rule is at work?