16. Consistency and CAP
16.3 What is eventual consistency?
At the bank: Each counter keeps its own copy of the ledger and posts changes to the other by courier. For a while, the two might show different balances. But if no new transactions happen, once the couriers arrive, both agree.
In the system: Eventual consistency promises only this: if no new writes happen, all replicas will eventually return the same value. In between, a read may return an older value.
You've already met it:
- DNS (Chapter 4): changes spread as caches expire.
- Caches (Chapter 12): a copy can be stale until its TTL or a delete.
- Asynchronous replicas (Chapter 14): followers lag behind the leader.
Why choose it: replicas can answer locally, immediately, without waiting for each other, and keep answering even when they can't reach each other. That gives low latency and high availability.
What to watch:
- "Eventually" has no deadline in the definition. In practice it's usually milliseconds to seconds, but measure it (replication lag, Chapter 14).
- Conflicts: if two replicas accept different writes to the same data, something must decide the final value: last-write-wins (which loses one write), merging, or data types designed to merge, like CRDTs. In the chapter's code, last-write-wins keeps only one of two profile edits, while a counter CRDT adds 3 likes from Mumbai and 5 from Frankfurt to get the correct 8.
Use it where a slightly old answer does no harm: likes, view counts, product descriptions, recommendations, feeds.
Memory code: "Couriers arrive eventually; until then, branches may disagree."