System DesignVol. 12 · Part XII
0 / 0

Shelves / System Design

SD·129

Consistency Architecture

Choosing and implementing consistency per piece of data: the spectrum from linearizability through causal to eventual consistency, where strong consistency is required (invariants) and where it isn't, transaction isolation levels and their anomalies in practice, optimistic concurrency with versions and ETags, pessimistic locking with SELECT FOR UPDATE and advisory locks, conditional writes and compare-and-set, causal relationships with session guarantees and version vectors, conflict detection and resolution (last-writer-wins, merge functions, CRDTs, application-level resolution), consistency across services, and patterns for user-visible consistency.

23 topics · ~21 min read · 31-question quiz
Updated Suggest a correction

Start here: which rules must never break?

Consistency in system design means: when several people read and change the same data at the same time, or read it from different copies, what are they guaranteed to see? Stronger guarantees are easier to program against and cost more (latency, throughput, availability). The skill is choosing per piece of data: which invariants (rules that must always hold) need strong protection, and where a slightly stale or briefly inconsistent answer is fine.

A rule broken by two correct transactions

The tiffin centre's rule: at least one delivery rider must be on shift. Asha and Ravi are both on shift, and both ask to go off at the same moment. Each transaction checks "are at least two on shift?", sees 2, and takes itself off:

Text
read committed   : both committed → riders on shift: 0   ✗ rule broken
repeatable read  : both committed → riders on shift: 0   ✗ rule broken
serializable     : one committed, one "serialization failure (retry)" → riders on shift: 1   ✓

Neither transaction did anything wrong on its own; each changed a different row based on a check the other invalidated. That anomaly is called write skew, and only the serializable isolation level prevented it, by detecting the conflict and failing one transaction, which the application then retries (and on retry, sees only one rider left and stays on shift).

Money lost by read-modify-write

A wallet holds ₹100. Two purchases of ₹30 and ₹50 arrive together; each reads the balance, subtracts, and writes the result:

Text
read committed                : both ok → balance 70   (should be 20; ₹50 vanished)
repeatable read               : one ok, one "serialization failure" → balance 70, second purchase must retry
read committed + SELECT … FOR UPDATE : both ok → balance 20 ✓

Under read committed, the second write simply overwrote the first: a lost update. Repeatable read detected it and refused the second transaction. Locking the row while reading (FOR UPDATE) made the second purchase wait for the first, then read 70 and write 20. (The simplest fix of all is not to read at all: update wallet set balance = balance - 50 where balance >= 50 is a single atomic statement.)

The spectrum, from strongest to weakest

Guarantee You can rely on Typical use
serializable / strict serializable transactions behave as if one at a time money, stock, bookings, invariants across rows
linearizable (per key) every read sees the latest completed write locks, leader election, unique usernames
snapshot / repeatable read a consistent snapshot; some anomalies (write skew) reports, most reads
read committed no dirty reads; lost updates possible without care default in PostgreSQL; fine with atomic updates
causal / read-your-writes your own and causally related changes in order profiles, comments, carts
eventual copies converge if writes stop menus, counters, feeds, search indexes

How deep to go in consistency architecture

Volume 17 defines six mastery levels. For this chapter they look like this; the chapter aims at L3 everywhere, and its lab at L4.

Level What you can do
L1 Explain strong vs eventual consistency and name the common anomalies
L2 Protect invariants with atomic updates, locks or the right isolation level, with retries
L3 Explain isolation levels and their anomalies, linearizability, causal consistency and CAP/PACELC
L4 Reproduce and fix consistency bugs (lost updates, write skew, stale reads) in real systems
L5 Choose consistency per data item across services, caches and regions, and design compensations
L6 Set data-consistency standards and review practices across an organisation

Consistency as a design decision

"Consistency" means different things in different contexts (Vol. 5 ch. 69):

  • ACID consistency: transactions move the database from one valid state to another, preserving constraints and invariants.
  • Replica consistency (the C in CAP): what readers observe given replication: do all replicas agree, and does a read see the latest write?
  • Isolation: how concurrent transactions interact (serializable, snapshot, read committed…).
  • Cross-system consistency: whether two services or stores (database and search index, orders and payments) agree.

Architecture-level consistency decisions answer: for each piece of data and each operation, what guarantees do users and invariants require, and what do we pay for them? Strong guarantees cost latency, availability and throughput; weak guarantees cost application complexity and user-visible anomalies. The answer is almost never uniform across a system.

The consistency spectrum

linearizable(strict serial.)Spanner, etcd sequentialZooKeeper causalMongoDB sessions sessionguaranteesread-your-writes eventualDNS, caches ← more coordination: latency, lower availability under partitions more anomalies for applications to handle →
A simplified spectrum of consistency models from strongest to weakest. Linearizability makes the system behave like a single copy updated instantly; sequential and causal consistency relax real-time ordering while preserving program and cause-effect order; session guarantees give each client a consistent view of its own actions; eventual consistency only promises convergence when updates stop. Stronger models need more coordination, costing latency and availability under partitions.
Model Promise Typical use
Linearizability Every operation appears to take effect atomically at one instant between its start and end; all clients see one up-to-date copy Leader election, locks, unique constraints, account balances, configuration
Serializability (isolation) Concurrent transactions behave as if executed one at a time in some order Multi-row business transactions
Strict serializability Serializable and respects real-time order Spanner, CockroachDB (close), FoundationDB
Causal consistency Operations that are causally related are seen by everyone in that order; concurrent ones may be seen in different orders Comments and replies, social feeds, collaborative apps
Session guarantees Per client: read-your-writes, monotonic reads, monotonic writes, writes-follow-reads User-facing apps over replicated stores
Eventual consistency If updates stop, replicas converge eventually; no ordering guarantees meanwhile Caches, DNS, search indexes, counters, analytics
Bounded staleness Reads at most T seconds or K versions behind Azure Cosmos DB, Spanner stale reads

Where strong consistency is required

Strong consistency is needed where an invariant must hold despite concurrency, and violations are costly or irreversible:

  • Uniqueness: usernames, email addresses, idempotency keys, seat assignments.
  • Non-negativity / limits: account balances, inventory counts, credit limits, quotas, rate limits that protect money.
  • Exclusive ownership: locks, leases, leader election, "only one active subscription".
  • Sequencing: invoice numbers without gaps (legal requirements in some countries), ledger ordering.
  • Security decisions: revoked access must take effect (bounded and short delay at minimum).

Everything else can usually tolerate eventual consistency with good UX: like counts, view counts, recommendations, search results, analytics, notifications, profile pictures, catalogue descriptions.

A powerful technique: isolate the invariant. Instead of making a whole system strongly consistent, route just the invariant-protecting operation through a strongly consistent component (a single database row with a constraint, a conditional write, a consensus-backed counter) and keep everything around it eventually consistent. For example, check "probably in stock" from a cache for display, but reserve inventory with an atomic conditional decrement at checkout.

Transaction isolation in practice

Most relational databases default to weaker isolation than serializable for performance. Know your database's default and its anomalies (Vol. 4, Vol. 5 ch. 69):

Level Prevents Still allows Defaults
Read uncommitted (almost nothing) Dirty reads Rarely used
Read committed Dirty reads/writes Non-repeatable reads, lost updates, write skew PostgreSQL, Oracle, SQL Server default
Repeatable read / snapshot isolation Non-repeatable reads, (in PG) lost updates Write skew, phantoms in some engines MySQL InnoDB default; PG's repeatable read is SI
Serializable All of the above (none, but transactions may abort and need retry) CockroachDB default; opt-in in PG (SSI)

Two anomalies that cause real bugs:

  • Lost update: two transactions read a value, both compute a new value, both write; one update is lost (two concurrent "add ₹100" operations end up adding ₹100 once). Fix with atomic updates (UPDATE accounts SET balance = balance + 100), SELECT … FOR UPDATE, optimistic version checks, or higher isolation.
  • Write skew: two transactions read overlapping data, make decisions based on it, and write different rows, jointly violating an invariant (two doctors both go off call because each saw the other still on call; two bookings for the same room in different rows). Fix with serializable isolation, explicit locking of the rows that represent the constraint (or a "materialised conflict" row), or a database constraint (exclusion constraints in PostgreSQL for overlapping bookings).
SQL
-- PostgreSQL exclusion constraint: no two bookings for the same room may overlap in time
CREATE EXTENSION IF NOT EXISTS btree_gist;
CREATE TABLE bookings (
    room_id   int        NOT NULL,
    during    tstzrange  NOT NULL,
    guest_id  bigint     NOT NULL,
    EXCLUDE USING gist (room_id WITH =, during WITH &&)
);
-- Concurrent overlapping INSERTs: one succeeds, the other fails with a constraint violation

Serializable isolation is often cheaper than expected (PostgreSQL SSI, CockroachDB), but applications must retry serialization failures (SQLSTATE 40001): wrap transactions in retry loops with backoff.

Optimistic concurrency control

Optimistic concurrency assumes conflicts are rare: read without locking, then at write time check that nothing changed since the read; if it did, reject (and let the caller retry or merge).

Mechanisms:

  • A version column (integer incremented on every update) or updated_at timestamp, checked in the UPDATE … WHERE version = ?.
  • ETags in HTTP: the server returns ETag: "v7"; the client sends If-Match: "v7" with its update; the server responds 412 Precondition Failed if the resource changed (prevents lost updates between users editing the same resource).
  • Conditional writes in key-value stores: DynamoDB ConditionExpression, etcd transactions comparing mod_revision, S3 If-Match, Redis WATCH/MULTI.
// JPA optimistic locking: @Version column; concurrent update → OptimisticLockException
@Entity
class Document {
    @Id UUID id;
    String title;
    String body;
    @Version long version;        // JPA adds "WHERE version = ?" and increments on update
}

@Transactional
public DocumentDto update(UUID id, long expectedVersion, UpdateDoc cmd) {
    Document d = repo.findById(id).orElseThrow();
    if (d.version != expectedVersion) throw new ConflictException(d.version);   // 409 to client
    d.title = cmd.title(); d.body = cmd.body();
    return DocumentDto.from(d);   // flush fails with OptimisticLockException if someone committed first
}

Optimistic concurrency suits low-contention data (documents, profiles, settings) and works across requests (users editing for minutes) where holding locks is impossible. Under high contention (a hot counter), it causes many retries; use atomic operations or pessimistic locking instead.

Pessimistic concurrency control

Pessimistic concurrency prevents conflicts by locking before reading/modifying:

  • Row locks: SELECT … FOR UPDATE (exclusive), FOR SHARE, FOR NO KEY UPDATE; NOWAIT (fail immediately) or SKIP LOCKED (skip locked rows: job queues, chapter 128).
  • Advisory locks (PostgreSQL pg_advisory_xact_lock(key)): application-defined locks on arbitrary keys, released at transaction end.
  • Table locks: rarely appropriate in OLTP.
  • Distributed locks (Redis-based with care, etcd/ZooKeeper leases): coordinating across processes or stores, with fencing tokens to be safe (Vol. 5 ch. 77).
SQL
-- Transfer money: lock both accounts in a consistent order to avoid deadlocks
BEGIN;
SELECT id, balance FROM accounts WHERE id IN (17, 42) ORDER BY id FOR UPDATE;
-- application checks balance of 17 >= 500
UPDATE accounts SET balance = balance - 500 WHERE id = 17;
UPDATE accounts SET balance = balance + 500 WHERE id = 42;
INSERT INTO ledger (from_id, to_id, amount, idempotency_key) VALUES (17, 42, 500, 'tx-8f3c');
COMMIT;

Guidelines: keep lock scopes small and transactions short (never hold locks across network calls to other services or user think time); acquire locks in a consistent order to avoid deadlocks; set lock and statement timeouts; monitor lock waits.

Choosing optimistic vs pessimistic

Situation Choose
Low contention, long think time (user edits) Optimistic (versions/ETags)
High contention on a few rows, short operations Pessimistic locks or atomic updates
Simple arithmetic on one row Atomic update (SET x = x + 1, WHERE stock >= qty)
Invariant across rows Serializable isolation, locking the constraint rows, or DB constraints
Across services Neither directly: sagas with reservations, idempotency, compensations (Vol. 5 ch. 73)

The conditional atomic update is often the best of both: UPDATE inventory SET stock = stock - 2 WHERE sku = 'X' AND stock >= 2 reserves stock atomically without a read-modify-write race; zero rows affected means "insufficient stock".

Causal relationships

Many user-facing anomalies are violations of causality: seeing a reply without the message it replies to, seeing a "user unfriended you" event processed after a post visible only to friends, a profile photo reverting after you changed it. Causal consistency guarantees that if operation A could have influenced B (A happened-before B), everyone who sees B also sees A.

Mechanisms:

  • Session guarantees implemented via tokens: the client carries the latest version/LSN/timestamp it has seen or written, and servers only answer once they're at least that up to date (MongoDB causally consistent sessions with afterClusterTime, Cosmos DB session consistency, the LSN approach in chapter 127).
  • Logical clocks: Lamport timestamps (total order consistent with causality) and vector clocks/version vectors (detect whether two versions are causally ordered or concurrent), hybrid logical clocks (HLC) combining physical time with logical counters (CockroachDB, YugabyteDB) (Vol. 5 ch. 75).
  • Co-locating causally related data in one partition (a conversation's messages in one partition gives per-conversation order).
  • Explicit dependencies: a reply carries the ID of its parent; the UI or consumer waits/defers rendering until the parent is present.
v0(A:0, B:0) replica A: v1(A:1, B:0) replica B: v2(A:0, B:1) neither dominates→ concurrent: resolvemerged v3 (A:1, B:1)
Detecting concurrent updates with version vectors. Two replicas start from the same version. Replica A applies an update, producing vector (A:1, B:0); replica B independently applies another, producing (A:0, B:1). Neither vector dominates the other, so the system knows the updates were concurrent and must resolve the conflict, rather than silently discarding one as last-writer-wins would.

Conflict resolution

Whenever multiple replicas or clients accept writes independently (multi-leader replication, multi-region active-active, offline-first mobile apps, collaborative editing), conflicts occur: concurrent updates to the same data. Strategies:

Strategy How Pros Cons
Avoid conflicts Route all writes for a key to one "home" replica/region (per user, per tenant) No conflicts for that key Cross-region writes for some users; failover complexity
Last-writer-wins (LWW) Keep the write with the highest timestamp (or replica ID tie-breaker) Simple, converges Silently loses concurrent writes; clock skew picks "wrong" winners (Cassandra, DynamoDB global tables)
Merge function Application-defined merge of concurrent values (union of shopping-cart items; max of counters) Preserves intent where a merge is meaningful Must be designed per data type; deletes are tricky
CRDTs Data types whose concurrent updates merge deterministically and commutatively (counters, sets, maps, registers, sequences for text) Strong eventual consistency without coordination Limited operations; metadata overhead; invariants like "balance ≥ 0" can't be guaranteed
Keep siblings / ask the user Store all concurrent versions; the application or user resolves (Riak siblings, Git merge conflicts, CouchDB) No silent loss UX and code complexity
Operational transformation (OT) Transform concurrent edits against each other (Google Docs style) with a central server Rich collaborative editing Complex; server-centric

CRDTs in brief

Conflict-free replicated data types guarantee that replicas which have received the same set of updates converge to the same state, in any order, without coordination:

  • G-Counter (grow-only counter): each replica keeps its own count; value = sum; merge = element-wise max.
  • PN-Counter: two G-Counters (increments and decrements).
  • G-Set, 2P-Set, OR-Set (observed-remove set: adds win over concurrent removes using unique tags).
  • LWW-Register, MV-Register (multi-value: keeps concurrent values).
  • Sequence CRDTs for collaborative text (RGA, Fugue, used by Automerge and Yjs).
Python
# State-based PN-Counter CRDT: merge is element-wise max of per-replica counts
from collections import defaultdict

class PNCounter:
    def __init__(self, replica: str):
        self.replica = replica
        self.p = defaultdict(int)   # increments per replica
        self.n = defaultdict(int)   # decrements per replica

    def inc(self, k: int = 1): self.p[self.replica] += k
    def dec(self, k: int = 1): self.n[self.replica] += k
    def value(self) -> int: return sum(self.p.values()) - sum(self.n.values())

    def merge(self, other: "PNCounter"):
        for r, v in other.p.items(): self.p[r] = max(self.p[r], v)
        for r, v in other.n.items(): self.n[r] = max(self.n[r], v)

a, b = PNCounter("A"), PNCounter("B")
a.inc(3); b.inc(2); b.dec(1)
a.merge(b); b.merge(a)
assert a.value() == b.value() == 4      # converge regardless of merge order or repetition

Products using CRDTs: Redis Enterprise active-active (CRDB), Riak data types, Azure Cosmos DB (custom conflict resolution), Automerge/Yjs for local-first collaborative apps, Akka/Pekko Distributed Data, Electric SQL and similar sync engines.

What CRDTs can't do: enforce global invariants that require coordination (no overselling, no negative balance, uniqueness). For those, route through a single authority (escrow or reservation schemes can split a budget across replicas for limited local autonomy).

Consistency across services

In microservice architectures each service owns its data; there's no shared transaction across them. Consistency between services is eventual, achieved by:

  • Sagas: sequences of local transactions with compensating actions on failure, orchestrated or choreographed (Vol. 5 ch. 73, chapter 131).
  • Transactional outbox to publish events atomically with local state changes (chapter 131).
  • Idempotent consumers and reconciliation jobs that detect and repair divergence (compare order states with payment provider records nightly).
  • Reservations (semantic locks): mark resources as pending (seat held for 10 minutes, funds authorised but not captured) to protect invariants across steps.
  • Accept and design for intermediate states visible to users ("payment processing").

When a business operation truly needs atomicity across data owned by two services, revisit the boundaries: maybe the data belongs in one service.

User-visible consistency patterns

Users experience consistency through the UI; many anomalies can be designed away:

  • Read-your-writes in the UI: after a successful command, update the UI from the command's response (or optimistic UI) rather than immediately re-querying an eventually consistent read model; or pass a version token and wait for the read model to reach it.
  • Optimistic UI with rollback on failure (likes, toggles).
  • Pending states: show "processing" for asynchronous operations; notify on completion.
  • Clear conflict UX: when a 412/409 occurs, show what changed and offer merge or overwrite.
  • Monotonic views: avoid flickering between replicas (session stickiness).
  • Freshness indicators: "updated 2 minutes ago" for dashboards fed by eventually consistent pipelines.

Choosing consistency per data type: an example

E-commerce platform:

Data / operation Requirement Mechanism
Inventory reservation at checkout Never oversell Conditional atomic decrement in the inventory DB (single authority per SKU)
Product page stock indicator Approximate is fine Cache, refreshed within seconds
Order placement Exactly-once effect, durable DB transaction + idempotency key + outbox
Payment capture No double charge Provider idempotency keys; reconciliation
Order history page Read-your-writes for the buyer Read from primary or wait for projection version
Search results Eventual (minutes OK) CDC → search index
Reviews and ratings Eventual; causal for replies Async moderation pipeline; parent references
Shopping cart (multi-device, offline) Merge concurrent edits Server-side merge (union with quantities by latest per item) or CRDT map
Coupon single-use Uniqueness Unique constraint on (coupon, user)
Analytics dashboards Eventual (hours OK) Batch/stream pipeline to warehouse

Lab: isolation anomalies, reproduced and prevented

PostgreSQL 16 on the lab machine, psycopg 3, two threads per experiment. Where the anomaly needs both transactions to read before either writes, a threading.Barrier forces that interleaving, so each result is deterministic rather than a once-in-a-thousand race.

Experiment 1: write skew (the on-call rule)

Python
c.execute(f"set transaction isolation level {level}")
n = c.execute("select count(*) from riders where on_shift").fetchone()[0]
barrier.wait()                                          # both have read n = 2
if n >= 2: c.execute("update riders set on_shift = false where name = %s", (name,))
c.commit()
Isolation Outcome Riders on shift
read committed both committed 0 ✗
repeatable read both committed 0 ✗
serializable one committed, one SerializationFailure 1 ✓

PostgreSQL's serializable level is Serializable Snapshot Isolation (SSI): transactions run on snapshots as in repeatable read, while the database tracks read-write dependencies (predicate locks shown in pg_locks as SIReadLock) and aborts one transaction when a dangerous cycle appears. No blocking, but false positives happen, so every serializable transaction needs a retry loop, typically 3–5 attempts with a little jitter. Alternatives for this specific rule: lock the rows you depend on (select … from riders where on_shift for update), or materialise the conflict (a single shift_status row both transactions must update, turning write skew into an ordinary write-write conflict).

Experiment 2: lost update (the wallet)

Isolation / technique Outcome Final balance
read committed both ok 70 ✗ (one deduction lost)
repeatable read one ok, one SerializationFailure 70, second purchase retries → 20
read committed + FOR UPDATE both ok, second waited 20 ✓

Three more correct designs, none needing a higher isolation level: an atomic update (balance = balance - 50 where balance >= 50, then check the row count); optimistic concurrency (update … where id = 1 and version = 7, retry if 0 rows); and an append-only ledger (insert a transaction row; the balance is a sum, with a constraint or a serialised check for overdraft).

Experiment 3: where consistency choices live in a whole system

The isolation level only covers one database. For the tiffin centre:

Data Invariant Guarantee chosen Mechanism
wallet balance never negative, no lost money serializable per account atomic update in the primary, no cache on write path
tiffin slot stock never oversold linearizable per slot conditional update / constraint (chapter 116)
order status customer sees own updates read-your-writes primary reads after write, or LSN wait (chapter 127)
menu, ratings none critical eventual replicas, caches with TTL, CDN
kitchen dashboard roughly current eventual, bounded staleness events (chapter 131)

Strong guarantees are spent where invariants live; everything else is allowed to be cheaper.

Try it yourself

  1. Add a retry loop (3 attempts) to the serializable rider transaction and show the loser ends up staying on shift.
  2. Run Experiment 1 under serializable with 10 riders and 10 concurrent requests. How many serialization failures occur, and does the invariant hold?
  3. Implement the wallet with optimistic concurrency (a version column) and measure retries under 20 concurrent purchases.
  4. Use pg_locks during a serializable transaction to see its SIRead locks.

Revision sheet: consistency architecture

Key ideas

  • Start from invariants: which rules must never break; spend strong consistency there.
  • Isolation levels and anomalies: dirty read, non-repeatable read, phantom, lost update, write skew; read committed < repeatable read/snapshot < serializable.
  • PostgreSQL: read committed default; repeatable read = snapshot isolation (detects write-write conflicts); serializable = SSI (detects dangerous read-write cycles; needs retries).
  • Techniques: atomic updates, SELECT … FOR UPDATE, optimistic concurrency (versions), constraints, materialised conflicts, append-only ledgers.
  • Distributed guarantees: linearizability, sequential, causal, read-your-writes, monotonic reads, eventual; CAP (during partitions choose C or A) and PACELC (else latency vs consistency).
  • Across services: no distributed transaction by default; sagas, outbox, idempotency and reconciliation (chapter 131).

Numbers to remember

  • Lab: write skew broke the rule under read committed and repeatable read; serializable aborted one of two.
  • Lab: lost update left ₹70 instead of ₹20 under read committed; FOR UPDATE gave ₹20.

Pitfalls

  • Read-modify-write in application code without locks or versions.
  • Assuming repeatable read prevents write skew.
  • Serializable without retry loops.
  • One global consistency level for everything (too slow or too weak).
  • Caches and replicas on paths that enforce invariants.
  • Treating "eventual" as "soon" without measuring lag.

Glossary

  • Write skew: concurrent transactions each preserve an invariant alone but break it together.
  • Lost update: one write silently overwrites another's effect.
  • SSI: serializable snapshot isolation.
  • Optimistic concurrency: detect conflicts at write time via versions.
  • Linearizability: single-copy, real-time-ordered behaviour per object.