Skip to main content

Consistency Models

Learning objectives
  • Define linearizability, sequential, causal, and eventual consistency, and order them by strength
  • Distinguish consistency models (single objects, replicas) from isolation levels (transactions)
  • Explain the four session guarantees and recognize their violations in banking and e-commerce UIs
  • Implement read-your-writes and monotonic reads with leader routing, sticky replicas, or version tokens

TL;DR​

  • A consistency model is a contract: which values a read is allowed to return, given the writes that happened. Stronger models allow fewer surprising results and cost more coordination.
  • Linearizable: behaves like one copy, respecting real time. Sequential: one global order consistent with each client's program order, but not necessarily real time. Causal: everyone sees cause-before-effect; concurrent writes may be seen in different orders. Eventual: replicas converge if writes stop — no promise about what you read in the meantime.
  • Users rarely need global linearizability; they need session guarantees: read-your-writes, monotonic reads, monotonic writes, writes-follow-reads.
  • Deliver session guarantees cheaply: read from the leader for a short window after a write, pin a user to one replica, or carry a version token (LSN, timestamp, cluster time) and only read from replicas that have caught up to it.
  • Serializability (isolation) is not linearizability (recency). Strict serializability is both, and is what you want for a ledger's balance check.
  • Name the anomaly when you choose a weaker model: "a user may briefly see their old balance after a transfer" is a product decision, not a database detail.

Why it matters​

A customer transfers $200 and the app immediately reloads the account page. The read goes to a replica that is 800 ms behind, so the balance still shows the old amount and the transfer is missing from the history. The customer assumes it failed and taps "Transfer" again. If the transfer API is not idempotent, the bank has just moved $400. If it is idempotent but the UI does not reuse the key, it is the same outcome. A replication-lag detail became a customer complaint and a reconciliation ticket.

Other anomalies show up in the same way:

  • Monotonic reads violation: a refund appears in the order history, and on refresh it disappears (the second request hit a more-lagged replica).
  • Consistent prefix / causality violation: a "payment received" push notification arrives before the payment shows in the account, or a debit appears before the credit that funded it, briefly showing a negative balance.
  • Stale read for a decision: an inventory service checks stock on a lagging replica during a flash sale and oversells.

Consistency models give you vocabulary to say precisely which of these your design permits, and the techniques below let you prevent the ones that matter without paying for linearizability everywhere.

Core concepts​

Consistency vs isolation​

Two different questions are often blurred together:

  • Consistency models (this page) answer: for a single object replicated across nodes, which values may a read return? They are about recency and ordering.
  • Isolation levels answer: when transactions touch several objects concurrently, which interleavings are allowed? (read committed, snapshot isolation, serializable — see Transactions & Isolation Levels.)

Serializability says the outcome equals some serial order of transactions, which may not match real time: a serializable database may legally return a stale snapshot. Linearizability says single operations respect real time. Strict serializability combines them: transactions appear to execute one at a time, in an order consistent with real time. Spanner calls this external consistency.

The hierarchy​

An arrow means "is stronger than / implies". The Jepsen project maintains a more complete version of this map, including isolation levels.

Linearizability​

The system behaves as if there were a single copy of the data and every operation took effect atomically at some instant between its invocation and its response. Consequences:

  • Once a write completes, every read that starts afterwards (by wall-clock time, across all clients) sees that value or a newer one.
  • Once any client has read a new value, no client can later read an older one.

It is what you need for compare-and-set decisions on shared state: "is this username taken", "is this lock held", "does this account have ≥ $200 right now", "is seat 14C free". It is also composable: if each object is linearizable, the system of objects is too.

Cost: every operation must coordinate with a leader or quorum. Reads cannot be served by an arbitrary replica unless it can prove it is current (Raft ReadIndex, leader leases — see Consensus & Raft).

Sequential consistency​

All clients see all operations in one total order, and each client's operations appear in the order that client issued them. But that order need not match real time: a write that completed before your read started may appear "after" your read. Lamport defined it in 1979 for multiprocessors. In practice, ZooKeeper offers something close to it for a single client session: writes are linearizable, while reads from the connected server may lag behind other clients but never go backwards for that session.

Causal consistency​

If operation A could have influenced operation B (same client did A then B, or B read a value written by A), then every node sees A before B. Operations that are concurrent (neither could have seen the other) may be observed in different orders on different nodes.

Example: a merchant updates a product's price (A); a pricing job reads the new price and creates a promotion based on it (B). Causal consistency guarantees nobody sees the promotion with the old base price. Two unrelated merchants editing two unrelated products are concurrent and can be seen in any order.

Causal consistency is the strongest model that can stay available during partitions, which makes it attractive for geo-replicated, AP-leaning systems. It requires tracking dependencies (vector clocks or dependency lists — see Time, Clocks & Ordering).

Eventual consistency​

If writes stop, all replicas eventually converge to the same value. That is the entire promise. It says nothing about what you read in the meantime, how long "eventually" is, or what happens to concurrent writes (last-writer-wins? merge?). Eventual consistency is a liveness property with no safety guarantee, which is why you almost always layer session guarantees or conflict-resolution rules on top.

Session guarantees​

Terry et al. (1994) defined four guarantees scoped to one client session. They match what users actually notice:

GuaranteePromiseBanking / e-commerce violation
Read-your-writesAfter you write, your reads reflect that writeTransfer done, account page shows old balance
Monotonic readsYour successive reads never go back in timeRefund visible, then gone on refresh
Monotonic writesYour writes are applied in the order you issued them"Change address" then "place order" applied in reverse; order ships to old address
Writes-follow-readsA write made after reading X is ordered after X everywhereReply to a dispute message visible to others before the message it replies to

Together they give each user a causally consistent view of their own activity, without forcing global coordination.

Seeing the problem and the fix​

Without the token, the API would have read from the lagging replica and returned the old balance.

Other named models you may hear​

  • Consistent prefix reads: readers see writes in an order that some prefix of history could have produced — never an effect without its cause. Violations appear in partitioned logs when related events land in different partitions.
  • Bounded staleness: reads are at most T seconds or K versions behind. Spanner and CockroachDB expose bounded-staleness reads; Azure Cosmos DB offers it as one of five named levels (strong, bounded staleness, session, consistent prefix, eventual).
  • Strong eventual consistency: replicas that have received the same set of updates are in the same state, regardless of order — the guarantee CRDTs provide.

Trade-offs​

ModelStrengthsWeaknessesChoose when
Linearizable / strict serializableNo anomalies; safe for check-then-act on shared stateLeader/quorum round trip on every op; unavailable on minority sideBalances, transfers, inventory decrement, uniqueness, locks
SequentialSingle global order; simpler than linearizable to implement for readsCan return stale data in real time; rarely offered explicitlyCoordination services where per-session order suffices
CausalIntuitive (no effect before cause); available under partitionDependency tracking metadata; concurrent writes still conflictGeo-replicated user content, comments, collaborative features
Session guarantees on eventualCheap; fixes what users noticeOther users can still see stale dataAccount pages, order history, profile settings
Bounded stalenessPredictable lag, cheap local readsNot suitable for decisions; bound must be monitoredDashboards, catalog, "balance as of" displays far from home region
EventualLowest latency, highest availabilityAnything can happen before convergence; needs conflict resolutionCounters, recommendations, analytics, search indexes

In practice​

Techniques to deliver session guarantees, from simplest to most precise:

  1. Read from the leader for writers. After a user writes, route their reads to the primary for a short window (e.g., the next few seconds, longer than your p99 replication lag). Store the "last write at" timestamp in the session or a cookie. Simple, but it concentrates load on the primary during write-heavy periods.
  2. Read own data from the leader, others from replicas. A user's own account page reads from the primary; public product pages read from replicas. Works when "own data" is a small fraction of traffic.
  3. Sticky replica. Hash user_id to a replica so each user always reads from the same one: gives monotonic reads (not read-your-writes). Breaks on replica failover — fall back to the primary then.
  4. Version tokens. The write returns a position in the replication stream (PostgreSQL LSN, MySQL GTID set, a commit timestamp, MongoDB cluster time). The client echoes it on later reads. The server reads from any replica whose applied position ≥ token, waits briefly, or falls back to the primary. Precise and scales well; works across devices if the token is stored server-side per user.
  5. Database-native sessions. MongoDB causally consistent sessions carry operationTime / afterClusterTime. DynamoDB ConsistentRead: true gives read-your-writes by reading the leader. CockroachDB and Spanner give strict serializability by default, plus opt-in stale reads.

Version-token routing in Go (PostgreSQL):

// After commit on the primary, capture the WAL position.
func (r *Repo) commitLSN(ctx context.Context, tx pgx.Tx) (string, error) {
var lsn string
err := tx.QueryRow(ctx, "SELECT pg_current_wal_lsn()::text").Scan(&lsn)
return lsn, err
}

// pickReader returns a replica that has replayed at least minLSN, or the primary.
func (r *Repo) pickReader(ctx context.Context, minLSN string) *pgxpool.Pool {
if minLSN == "" {
return r.replicas[rand.IntN(len(r.replicas))]
}
for _, rep := range r.replicas {
var caughtUp bool
err := rep.QueryRow(ctx,
"SELECT pg_last_wal_replay_lsn() >= $1::pg_lsn", minLSN,
).Scan(&caughtUp)
if err == nil && caughtUp {
return rep
}
}
return r.primary // nobody has caught up: correctness over load
}

In production you would cache each replica's replay position (poll every ~100 ms) instead of querying on every read, and capture the LSN after the transaction commits rather than inside it.

Measure lag, don't assume it. PostgreSQL exposes write_lag, flush_lag and replay_lag in pg_stat_replication. Alert on replay lag and make sure your "read from leader after write" window exceeds the p99, not the average.

Consistent prefix in event streams. Put causally related events in the same ordered partition: key Kafka messages by account_id so a debit and the credit that funded it are consumed in order. Cross-partition ordering does not exist — see Message Queues & Event Streaming.

Common pitfalls​

  • Assuming the ORM's "read replica" setting is harmless. Enabling replica reads globally breaks read-your-writes on every page that reads right after a write. Symptom: intermittent "my change didn't save" tickets that nobody can reproduce locally.
  • Using a stale read to make a decision. Checking stock or balance on a replica and then writing to the primary. Symptom: oversell or overdraft under load, exactly when lag is highest. Decisions belong on the primary inside the same transaction (or a conditional write).
  • Read-your-writes only on one device. Token kept in the mobile app's memory, but the user checks the web app. Store the token server-side per user if cross-device matters.
  • Confusing serializable with "latest". A serializable snapshot read can be stale. If you need "the balance right now", you need strict serializability or a read on the leader.
  • Ignoring failover. Sticky replica routing silently loses monotonic reads when a replica is replaced by a fresher or staler one. Reset the session's pin and fall back to the primary.
  • Cache as an unacknowledged consistency layer. A cache in front of a linearizable database makes the system eventually consistent. Invalidate on write or include the version in the cache key — see Caching.

Interview angle​

  • Interviewers test whether you can name the anomaly and pick the cheapest guarantee that prevents it. "We'll use strong consistency" everywhere is as weak as "eventual consistency is fine".
  • Strong answer pattern: "Balance checks and debits run on the leader inside a serializable transaction. Account pages need read-your-writes, so writes return a commit LSN and reads route to a replica that has replayed it, else the primary. The catalog is eventually consistent with a cache TTL; checkout re-validates price."
  • Expect: "What's the difference between linearizability and serializability?" "How would you give read-your-writes across mobile and web?" "What happens to your token scheme during failover?" "How do you order events for the same account across services?"
  • Red flags: using "consistent" without saying which model; claiming a cache or replica read is "strongly consistent"; not knowing that serializable can be stale.

Self-check​

1. Define linearizability in one sentence, and give two operations in a bank that need it.

Every operation appears to take effect atomically at a single point between its start and end, so the system behaves like one copy that respects real-time order. Debiting an account conditional on sufficient balance, and allocating a unique resource such as a virtual account number or a payment reference, both need it.

2. How does serializability differ from linearizability, and what is strict serializability?

Serializability is about multi-object transactions: the result equals some serial order, which need not match real time, so stale snapshots are allowed. Linearizability is about single objects respecting real time. Strict serializability requires both: a serial order of transactions that also respects real time.

3. Why is causal consistency interesting for geo-replicated systems?

It is the strongest model known to remain available during network partitions. It prevents the anomalies users find most confusing (effects before causes) while letting each region accept writes locally. The cost is dependency metadata and the need to resolve truly concurrent writes.

4. Scenario: after a refund, users see it in the order history, then it disappears on refresh, then reappears. Which guarantee is violated and how do you fix it?

Monotonic reads: successive reads hit replicas with different lag. Fix by pinning the user's reads to one replica (hash of user ID), or by carrying the highest version the user has seen and only reading from replicas at or beyond it, falling back to the primary.

5. Explain version tokens for read-your-writes. What can go wrong?

The write returns its position in the replication stream (LSN, GTID, commit timestamp). The client sends it with subsequent reads; the server reads from a replica whose applied position is at least that token, waits briefly, or uses the primary. Risks: the token is lost when the user switches devices (store it server-side), primary failover changes the position space (fall back to the new primary), and a misbehaving client can force all reads to the primary (cap or validate the token).

6. Why is "eventual consistency" alone an insufficient specification?

It only promises convergence once writes stop. It says nothing about what reads return before convergence, how long it takes, or how concurrent writes are resolved. A real design must add session guarantees, a staleness bound, or a conflict-resolution rule, and state which anomalies remain.

7. During a flash sale, the stock check reads from a replica and the decrement goes to the primary. What breaks and what should you do instead?

Replica lag spikes under load, so many requests see stock that has already been sold and the system oversells. Make the decision and the decrement one atomic operation on the authoritative store, for example UPDATE stock SET qty = qty - 1 WHERE sku = $1 AND qty > 0 and check the affected row count, or use a reservation counter in a single-writer store.

🧠 Flashcards0/9 learned · 0 retries

Exercise​

Build a small read-routing layer for an account service:

  1. Run PostgreSQL with one streaming replica (Docker Compose). Add artificial lag on the replica with recovery_min_apply_delay = '2s'.
  2. Write a Go HTTP service with POST /transfers and GET /accounts/:id. Initially, route all GETs to the replica and demonstrate the read-your-writes violation with a script that posts and immediately reads.
  3. Implement version tokens: return the commit LSN in a response header, accept it on GET, and route to the replica only if pg_last_wal_replay_lsn() has passed it; otherwise wait up to 200 ms, then fall back to the primary.
  4. Add a metric for "reads served by primary due to lag".

Done when: the script shows the violation before the change and zero violations after, and you can explain what happens to tokens if you promote the replica.

Further reading​

  • Martin Kleppmann, Designing Data-Intensive Applications, ch. 5 (replication lag anomalies) and ch. 9 (linearizability, causality).
  • Maurice Herlihy & Jeannette Wing, "Linearizability: A Correctness Condition for Concurrent Objects" (1990).
  • Leslie Lamport, "How to Make a Multiprocessor Computer That Correctly Executes Multiprocess Programs" (1979) — sequential consistency.
  • Douglas Terry et al., "Session Guarantees for Weakly Consistent Replicated Data" (1994).
  • Peter Bailis et al., "Highly Available Transactions: Virtues and Limitations" (VLDB 2014).
  • Jepsen: Consistency Models — interactive map of models and their relationships.
  • Azure Cosmos DB documentation, "Consistency levels" — a practical example of five named levels.
Finished this page?

Do the self-check first. Marking it complete schedules spaced reviews (1, 3, 7, 14, 30… days).