Sub topic 16
Choosing a consistency model for your workload
This chapter assumes you know the models from earlier chapters: linearizability, sequential, causal and eventual consistency, session guarantees, quorums, and the CAP and PACELC trade-offs. It also assumes you can read short Python. The goal here is to turn those ideas into a repeatable decision process.
Start from invariants, not from model names
A consistency model is a cost. Stronger models cost latency, availability during partitions, and throughput. So the question is not "which model is best?" but "what is the weakest model under which my application's invariants still hold?"
An invariant is a rule about your data that must never be broken. Examples:
- A username is unique.
- An account balance never goes below zero.
- A user sees their own profile edit after saving it.
- A reply never appears before the post it answers.
For each invariant, ask what anomaly would break it. Then match the anomaly to the cheapest model or guarantee that prevents it.
| Anomaly that breaks the invariant | Cheapest guarantee that prevents it |
|---|---|
| User saves a change and then sees the old value | Read-your-writes |
| Page refresh shows older data than the previous view | Monotonic reads |
| Reply visible without the original post | Causal consistency |
| Two clients both claim the same unique name | Linearizable compare-and-set, or consensus |
| Two transactions each pass a check, then jointly break a rule | Serializability |
| Stale read after a write completed, visible to another client | Linearizability |
| Counter or set loses concurrent updates | Merge-able data type (CRDT) or conflict handling |
Decision questions
Work through these questions in order. Each one narrows the choice.
- Do concurrent writers need to coordinate on a single decision? Unique names, leader election, locks, and "only one winner" rules need a total order on those operations. Use consensus-backed linearizable operations for these, even if everything else is weaker.
- Do operations touch several keys that must change together? If yes, you need transactions. Serializability protects multi-key invariants. If you also need real-time ordering, you need strict serializability.
- Do readers need to see the effects of writes that finished before they began? That is the real-time requirement of linearizability. If only a user's own view must be sensible, session guarantees are much cheaper.
- Does order between related events matter, but not order between unrelated ones? Use causal consistency. It keeps cause before effect without a global order.
- Can the application tolerate temporary staleness and merge concurrent updates? Use eventual consistency, with a stated conflict-resolution rule.
Most systems end up with different answers for different data. That is normal and intended.
Costs to weigh
Each step up the ladder costs something specific.
- Latency. Linearizable writes need a quorum or leader round trip. Across regions, that is tens to hundreds of milliseconds per write. PACELC says you pay this even when there is no partition.
- Availability under partition. A linearizable system must refuse requests on the minority side of a partition. A system with weaker guarantees can keep answering, with stale or divergent data.
- Throughput. A single leader or a single consensus group limits write rate. Sharding helps, but cross-shard transactions bring back coordination.
- Complexity of the application. Weak models move work into your code: merge functions, retries, idempotent operations, and compensation steps.
The last cost is easy to miss. Choosing eventual consistency does not remove the problem. It moves conflict handling from the database into your application.
A worked example: an online store
Consider a store with several kinds of data, and choose a model for each.
| Data | Invariant | Anomaly to prevent | Choice |
|---|---|---|---|
| Product catalog | Descriptions are roughly current | None serious | Eventual consistency, cached reads |
| Shopping cart | Items added by the user are not lost | Lost updates, own writes not visible | Read-your-writes plus a merge-able set (CRDT) |
| Comments on products | Reply never before parent | Effect before cause | Causal consistency |
| Inventory count at checkout | Stock never oversold | Two buyers take the last item | Linearizable conditional update |
| Order and payment | Charge and order record agree | Partial update | Serializable transaction |
| Username or email at signup | Unique | Duplicate claim | Linearizable compare-and-set |
Notice that the high-volume data (catalog, carts) uses cheap models, and only the small, critical paths pay for strong ones. This is the usual pattern.
Checking a quorum configuration against a requirement
Quorum settings are a common tuning knob. The rule R + W > N guarantees that read and write sets overlap, but, as earlier chapters showed, it does not by itself give linearizability. This helper separates the two questions: does the overlap hold, and does it tolerate failures?
def quorum_report(n, r, w):
"""Describe what an (N, R, W) configuration gives you."""
overlap = r + w > n
read_tolerates = n - r # replicas that can be down while reads succeed
write_tolerates = n - w # replicas that can be down while writes succeed
return {
"overlap": overlap,
"reads_survive_failures": read_tolerates,
"writes_survive_failures": write_tolerates,
}
for config in [(3, 2, 2), (3, 1, 3), (3, 1, 1), (5, 3, 3)]:
print(config, quorum_report(*config))Running it shows the trade-off:
(3, 2, 2)overlaps and tolerates one failure for both reads and writes.(3, 1, 3)overlaps and gives fast reads, but one down replica blocks all writes.(3, 1, 1)is fast and available but does not overlap, so reads can be stale.(5, 3, 3)overlaps and tolerates two failures.
Treat overlap as necessary for strong reads, not sufficient. Sloppy quorums, hinted handoff, concurrent writes, and clock-based last-write-wins can all break the guarantee even when R + W > N.
Common mistakes
- Choosing one model for the whole system. Different data has different invariants. Split them.
- Using "strong consistency" as a vague label. Ask which model: linearizable, serializable, or strict serializable. They are not the same.
- Reading CAP as a three-way menu. Partitions happen on real networks. The real choice is what to do during one. PACELC covers the rest of the time.
- Trusting last-write-wins for data you care about. It silently drops concurrent writes and depends on clock quality.
- Assuming the vendor's default. Many stores default to a weaker level than people expect, and offer stronger options per request. Read the documentation and test it.
- Skipping verification. A claimed guarantee is a hypothesis. Run a history checker such as Jepsen-style tests against your real deployment, with partitions injected.
A checklist
Before you commit to a model, write down answers to these:
- What are the invariants, in one sentence each?
- What is the worst anomaly each data type can tolerate?
- What latency budget does each operation have, and across which regions?
- What should happen during a partition: refuse or answer with possibly stale data?
- How are concurrent writes merged, and who owns that code?
- How will you test that the system keeps its promise?
Exercise
A ride-sharing app stores (a) a driver's live location, updated every second, (b) the assignment of a driver to a ride request, and (c) a rider's trip history list. Pick a consistency model for each and justify it in one sentence.
Show answer
(a) Eventual consistency: a stale location is replaced a second later, and the volume makes coordination wasteful. (b) Linearizable conditional update (compare-and-set through consensus): two dispatchers must not assign the same driver, so there must be a single winner. (c) Read-your-writes with otherwise eventual consistency: the rider should see a trip they just finished, but a slight delay in other views is harmless.
Exercise
A team sets N=3, R=2, W=2 and states, "Our reads are linearizable because R + W > N." Name two reasons this claim may be false.
Show answer
Any two of: sloppy quorums with hinted handoff can accept writes on replicas outside the key's normal set, so overlap is not guaranteed; concurrent writes resolved by last-write-wins with skewed clocks can discard the newest write; a read that sees a partially completed write can return it and then a later read return the old value unless read repair or write-back is done; failed writes that reached only some replicas can become visible later.