Summary#
A consistency model is a contract between a data store and its clients. It says which values a read is allowed to return, given the writes that happened before and around it. With one copy of the data, the answer is simple. With replicas, caches and regions, the store can expose its internal lag, and the model tells you how much of that lag you may see.
From strongest to weakest:
- Linearizability (strong consistency): the store behaves as if there were one copy, and every read sees the latest completed write.
- Sequential consistency: everyone sees the same order of operations, but it may lag real time.
- Causal consistency: effects never appear before their causes.
- Session guarantees: read-your-writes, monotonic reads, monotonic writes and writes-follow-reads. They protect one client's view.
- Bounded staleness: reads are at most T seconds or K versions behind.
- Eventual consistency: replicas converge once writes stop.
- Weak consistency: best effort, with no promise that a write will ever be seen.
BASE (Basically Available, Soft state, Eventual consistency) is the design philosophy behind many NoSQL stores, in contrast with ACID transactions.
Eventually consistent systems converge through:
- event-based sync (change data capture, outbox, streams);
- read repair;
- background reconciliation (anti-entropy, Merkle trees, audit jobs).
Databases expose the choice as settings: quorum sizes (R + W > N), Cassandra consistency levels, DynamoDB's ConsistentRead, MongoDB read and write concerns, and Cosmos DB's five levels. Pick the weakest model that keeps each feature correct. Weaker models are faster, cheaper and stay available during failures.
Why It Exists#
The moment you add a read replica, a cache or a second region, a read can land on a copy that has not yet received the latest write.
- A user updates their profile picture, refreshes, and sees the old one.
- A comment appears before the post it replies to.
- A counter goes from 105 back to 98 because two reads hit different replicas.
Whether these anomalies are acceptable depends on the feature. Engineers need a precise vocabulary to state what is allowed, and to pick technologies and settings that deliver it.
Without that vocabulary, teams say "eventually consistent" or "strongly consistent" and mean very different things. Bugs then appear only under load or failure, when replicas actually diverge.
Consistency models come from two research traditions:
- multiprocessor memory, where Lamport defined sequential consistency in 1979;
- replicated databases and distributed systems, which produced session guarantees, causal consistency and eventual consistency.
This page builds on CAP Theorem and PACELC. CAP explains why you cannot always have the strongest model; this page explains what you can have instead.
How It Works#
What a consistency model describes#
Picture every client operation as an interval on a timeline, from when the request is sent to when the response arrives. Operations from different clients overlap. A consistency model is a rule about which histories of such intervals are legal.
- Data-centric models (linearizable, sequential, causal, eventual) describe what all clients collectively may observe.
- Client-centric models (the session guarantees) describe what one client, or one session, may observe. They are weaker overall, but they fix the anomalies users notice most, cheaply.
Models are ordered by strength. Every linearizable history is also sequentially consistent, every sequentially consistent history is also causally consistent, and so on down to eventual. A stronger model allows fewer surprising results but needs more coordination, which means more latency and less availability during partitions.
Arrows point from stronger to weaker. Anything that satisfies a model also satisfies every model below it.
Strong consistency and linearizability#
Linearizability is the formal name for what most people mean by "strong consistency". Maurice Herlihy and Jeannette Wing defined it in 1990. Every operation appears to take effect atomically at a single instant between its start and its end, and that order agrees with real time.
The practical consequence is simple. Once any client has seen a new value, no client may afterwards see an older one.
A concrete history makes this clear. The register x starts at 0.
- Client A writes
x = 1between time 10 ms and 30 ms. - Client B reads at 15-20 ms. The write is still in progress, so B may see 0 or 1.
- Client C reads at 25-28 ms and sees 1.
- Client B reads again at 40 ms. Under linearizability B must see 1, because the write completed at 30 ms. Seeing 0 would be a "stale read" violation.
- Also, once C saw 1 at 25 ms, any read that starts after 28 ms must see 1, even though the write's acknowledgement arrived only at 30 ms.
How systems provide it:
- A single copy, or a single leader that serves all reads and writes, with synchronous replication for durability. An example is a PostgreSQL primary, as long as clients read only from it.
- Consensus (Raft, Paxos). Writes are committed by a majority. Reads either go through the log, or are served by a leader that holds a valid lease, a time-bounded promise that no other leader exists. etcd, ZooKeeper (for writes and
syncreads), Consul, CockroachDB and Spanner all work this way. - Quorum reads and writes, plus extra machinery. Plain quorums are not enough, as explained below.
Why it matters. Many correctness tasks depend on linearizability:
- Locks and leader election: two clients must never both believe they hold the lock.
- Uniqueness constraints: only one user may register a given username.
- Compare-and-set: "decrement stock only if it is still 1".
These are exactly the places where weaker models cause double bookings and split-brain.
The cost. Every linearizable write and many reads need at least one round trip to a majority, or to the leader. That is ~1 ms within a region and 60-150 ms across regions, as PACELC describes. During a partition, the minority side cannot serve linearizable operations at all.
Linearizability vs serializability#
These two terms are often confused:
| Linearizability | Serializability | Strict serializability | |
|---|---|---|---|
| Unit | Single object, single operation | Transactions over many objects | Transactions over many objects |
| Promise | Real-time order of operations | Result equals some serial order of transactions | Some serial order that respects real time |
| Can show stale data? | No | Yes: a read-only transaction may be ordered "in the past" | No |
| Comes from | Distributed systems and concurrency | Databases (isolation levels) | Both; Spanner calls it "external consistency" |
Serializability is an isolation property, about how concurrent transactions interleave; see ACID and Isolation Levels. Linearizability is a recency property of replicas. A single-node database running SERIALIZABLE is strictly serializable in practice. A replicated database whose replicas run SERIALIZABLE locally but replicate asynchronously is serializable on each node, yet stale across nodes.
Sequential consistency#
Leslie Lamport defined sequential consistency in 1979 for multiprocessors. The result of any execution must be as if all operations ran in some single order, and each client's own operations appear in that order in the order the client issued them. Unlike linearizability, that single order need not match real time.
Example: Alice writes status = "busy" and then status = "free". All observers see "busy" before "free", and all agree on the order of every other write too. But Bob's reads may lag: he can still see "busy" a second after Alice set "free", as long as he never sees "free" and then "busy" again.
Sequential consistency is rarely offered as a product setting in databases. It matters because:
- it explains what systems like ZooKeeper give by default. ZooKeeper's writes are linearizable, but its reads from followers can be stale. Each client sees a consistent prefix of a single order, which is close to sequential consistency per client. A client calls
syncbefore a read when it needs the latest value. - it is the model CPU memory systems are compared against. Modern CPUs and languages (the Java and C++ memory models) offer weaker models unless you use atomics or fences.
Causal consistency#
Leslie Lamport's 1978 paper "Time, Clocks, and the Ordering of Events in a Distributed System" defined the happens-before relation: event A happened before event B if
- they occurred in the same process in that order, or
- A is the sending of a message and B is its receipt, or
- the two are linked by a chain of such steps.
Events not related by happens-before are concurrent.
Causal consistency promises that if write A happened before write B, every client that sees B also sees A. Concurrent writes may appear in different orders to different clients.
The classic anomaly it prevents:
- Alice posts "I lost my phone 😞".
- Alice finds it and posts "Found it! 🎉".
- Bob reads both and replies "Glad to hear!" to the second post.
- Carol, on a different replica, sees Bob's "Glad to hear!" before seeing Alice's "Found it!". Worse, she might see it beside "I lost my phone 😞".
Bob's reply causally depends on Alice's second post, so a causal store never shows the reply without the post.
How systems provide it.
- Each write carries dependency metadata: a vector clock, a list of the writes it depends on, or a hybrid logical timestamp.
- A replica delays making a write visible until all its dependencies are visible locally.
- No cross-replica agreement is needed on the critical path, so causal consistency remains available during partitions and keeps latency local. This is why it is often called the strongest model that is still always available.
Research systems such as COPS (Lloyd et al., "Don't Settle for Eventual", SOSP 2011) demonstrated causal+ consistency at scale.
In production:
- MongoDB offers causally consistent sessions (since version 3.6). Within a session, reads respect the writes and reads that came before, even across secondaries.
- Collaborative and chat systems often provide causality per conversation by sending all its messages through one ordered partition.
PRAM / FIFO consistency is a weaker step: each individual writer's writes are seen in the order that writer issued them, but no ordering is promised across writers. A per-key Kafka partition gives FIFO order per key.
Session guarantees#
Douglas Terry and colleagues defined four session guarantees in "Session Guarantees for Weakly Consistent Replicated Data" (PDIS 1994), from the Bayou project. They protect what a single client sees, without forcing global coordination.
| Guarantee | Promise | Anomaly it prevents | Typical implementation |
|---|---|---|---|
| Read-your-writes | After you write, your reads reflect that write | "I saved my profile and it reverted" | Read from the primary for a short window after writing, or track the write's log position and read only from replicas that have applied it |
| Monotonic reads | Your successive reads never go back in time | A like counter showing 105, then 98 | Stick a session to one replica (hash user ID to replica), or remember the last version seen and reject older replicas |
| Monotonic writes | Your writes are applied everywhere in the order you made them | "Set password" then "delete old sessions" applied in reverse on some replica | Route a session's writes through one leader or partition; sequence numbers per client |
| Writes-follow-reads | A write you make after reading X is ordered after X everywhere | Your reply appearing on replicas that lack the post you replied to | Attach the read's version as a dependency of the write (a causal token) |
Together, the four session guarantees give causal consistency within a session.
Read-your-writes, in detail. This is the most important guarantee in practice, because users notice its absence immediately. There are three common implementations:
- Time window. For N seconds after a user writes, send that user's reads to the primary. Choose N above the usual replica lag at p99. If lag is normally under 200 ms, a 5-second window is generous.
- Log position token. On write, return the primary's log sequence number (an LSN in PostgreSQL, a GTID in MySQL). The client sends it back with later reads, and a replica answers only if it has replayed past that position. Otherwise the request is forwarded to the primary or waits briefly.
- Read from cache you just wrote. Write-through to the cache, so the user's next read hits the fresh entry. This only works if all of their reads go through that cache.
# Read-your-writes routing with a log position token (pseudo-code)
on_write(user, change):
lsn = primary.execute(change) # returns commit log position
session[user].min_lsn = lsn # also returned to client as a cookie/header
return ok
on_read(user, query):
need = session[user].min_lsn or 0
replica = pick_replica(user) # sticky per user: monotonic reads
if replica.replayed_lsn() >= need:
return replica.execute(query)
if wait_until(replica.replayed_lsn() >= need, timeout = 50 ms):
return replica.execute(query)
return primary.execute(query) # fall back to primaryBounded staleness and consistent prefix#
Between session guarantees and eventual consistency sit two useful, named models.
- Bounded staleness: reads may lag, but by at most K versions or T time. Example: "prices shown are at most 10 seconds old". The system must monitor lag and stop serving from a replica that falls further behind, which costs some availability. Azure Cosmos DB offers it as a configurable level, and Spanner's "bounded-staleness reads" let a reader request a snapshot no older than T.
- Consistent prefix: readers see some prefix of the global write history, never writes out of order or with gaps. A reader may be behind, but never sees B without A. Replaying a single ordered log, such as one database replica applying the primary's WAL, gives consistent prefix per replica.
Eventual consistency#
Eventual consistency promises only this: if no new writes arrive, all replicas eventually converge to the same value. It says nothing about how long that takes, and nothing about what reads return before then. Werner Vogels popularised the term in industry with "Eventually Consistent" (ACM Queue, 2008).
- Typical lag is milliseconds within a region and hundreds of milliseconds to seconds across regions. It can stretch to minutes during overload or partitions.
- Examples: DNS (changes propagate as cached records expire), email delivery, asynchronous read replicas, CDN caches, search indexes fed by change data capture, social feeds, like and view counts, and Dynamo-style stores at low consistency levels.
- Convergence needs a conflict rule. If two replicas accept different writes to the same key, convergence requires a deterministic merge: last-writer-wins, version vectors with an application merge, or CRDTs (see the CAP page's deep dive). Without one, replicas can disagree forever.
- Strong eventual consistency is a stricter variant achieved by CRDTs: any two replicas that have received the same set of updates, in any order, are already in the same state. They do not have to wait for quiescence.
Eventual consistency is the right default for most read-heavy, user-facing content, because the anomalies are brief and harmless. A post shows up 500 ms later, or a count is off by a few for a second. In exchange, reads are local, cheap and always available.
The weak point is invariants. "Balance never negative", "seat sold once" and "username unique" cannot be protected by an eventually consistent store, because two replicas can each accept a write that is fine locally but wrong globally.
Weak consistency#
Weak consistency means: after a write, reads may or may not see it, and there is no promise that they ever will. It is a best-effort approach. That sounds useless, but it fits data whose value decays fast:
- Memcached and other caches without invalidation: a cached value may be stale, or evicted at any moment and never refilled. The source of truth is elsewhere.
- Real-time media: in VoIP, video calls and live streams, packets lost during a brief reception drop are not resent. Hearing the next words now matters more than hearing the missed words late.
- Multiplayer games: position updates are sent unreliably (often over UDP). Each new update replaces the last, so a lost one is simply skipped.
- Metrics sampling and telemetry: losing a fraction of samples barely changes the aggregate.
The design rule: use weak consistency only where newer data supersedes older data quickly and missing an update is harmless.
BASE vs ACID#
ACID describes the transactional guarantees of classic relational databases: Atomicity, Consistency (invariants), Isolation and Durability. BASE was coined as a contrasting philosophy for large-scale, partition-friendly systems. Dan Pritchett described it in "BASE: An Acid Alternative" (ACM Queue, 2008), drawing on his eBay experience. Its three parts:
- Basically available: the system keeps answering, perhaps with partial or stale data, rather than failing.
- Soft state: the state may change over time even without new input, as replicas converge and background processes catch up.
- Eventual consistency: given time without new writes, replicas agree.
| ACID | BASE | |
|---|---|---|
| Priority | Correctness of every transaction | Availability and scale |
| Consistency | Strong, immediate | Eventual (often tunable) |
| Failure behaviour | Abort and retry; unavailable rather than wrong | Answer with what is available; reconcile later |
| Typical scope | One node, or consensus-replicated | Partitioned and replicated across nodes and regions |
| Programming model | Transactions hide concurrency | Application handles staleness, conflicts, idempotency |
| Typical systems | PostgreSQL, MySQL, Oracle, Spanner, CockroachDB | Cassandra, DynamoDB (default reads), Riak, many caches and search indexes |
The dividing line has blurred:
- Many NoSQL stores now offer ACID transactions within limits. DynamoDB transactions cover up to 100 items, and MongoDB has had multi-document transactions since 4.0.
- Distributed SQL databases provide ACID at global scale, at a latency cost.
Modern systems are usually ACID at the core (orders, payments, inventory) and BASE at the edges (feeds, search, analytics, caches). Change data capture keeps the edges up to date from the core.
Where inconsistency comes from in a real design#
Most staleness in production designs does not come from exotic database settings. It comes from the ordinary read-scaling tools:
| Source | Why reads can be stale | Typical lag | Fix when freshness matters |
|---|---|---|---|
| Async read replicas | Replica applies the primary's log after the commit | ms to seconds; minutes under load | Read-your-writes routing, LSN tokens, read from primary |
| Caches (Redis, Memcached) | Entry filled before the write and not yet invalidated | Up to the TTL | Delete on write, CDC-driven invalidation, short TTLs, versioned keys |
| CDN / browser caches | HTTP caching until max-age | Seconds to hours | Cache-busting URLs, purge APIs, short max-age for dynamic data |
| Denormalized copies | The same data is copied into several tables or documents and updated separately | Until every copy is updated | Update copies in one transaction, or from an event stream; reconcile |
| Search indexes and materialized views | Built asynchronously from the source | Seconds | Read the source for "my own" items; show "updating" states |
| Multi-region replication | Cross-region async replication | 100 ms to seconds | Home region per user; route writes and own reads to it |
The data-model choice also matters.
- Relational schemas keep each fact in one place, so there is nothing to keep in sync within the database.
- Document, key-value and wide-column designs often denormalize: they duplicate the same fact across documents or keys, one per access pattern. Reads get faster, but every duplicate is another copy that can drift. Whoever writes the fact must update all copies, usually asynchronously, and the copies are eventually consistent with each other.
Eventual-consistency patterns: how copies converge#
If you accept eventual consistency, you still need mechanisms that make "eventually" short and reliable. There are three families, and most systems use all three.
1. Event-based synchronisation (push). Each change is published as an event, and every copy subscribes and applies it.
- Change data capture (CDC) tails the database's commit log, such as the PostgreSQL WAL or MySQL binlog, with tools like Debezium. It emits a change event for every committed row and feeds caches, search indexes, analytics and other services. Because it reads the log, it captures every write, including those made by scripts and other code paths.
- The transactional outbox writes the business change and an "event to publish" row in the same database transaction. A relay publishes the outbox rows to Kafka. This avoids the dual-write problem, where the DB commit succeeds but the event publish fails, or the reverse.
- Requirements: consumers must be idempotent, and must handle out-of-order events, for example by applying an event only if its version is newer than the stored version. See Change Data Capture.
2. Read repair (on the read path). In leaderless stores such as Cassandra and Riak:
- A read at consistency level QUORUM contacts several replicas and compares versions.
- If one replica returns an older version, the coordinator returns the newest value to the client and writes it back to the stale replica.
- Frequently read data therefore converges quickly. Rarely read data may stay divergent, which is why the third mechanism exists.
3. Background reconciliation (anti-entropy). A periodic process compares replicas and fixes differences, regardless of reads.
- Comparing every row would be too expensive, so replicas build Merkle trees: hash trees over key ranges. Two replicas compare root hashes, and if they differ, they descend only into the subtrees that differ. They can then sync a few divergent keys out of billions, exchanging only a few kilobytes of hashes. Cassandra's
nodetool repairand Dynamo's anti-entropy work this way. - Hinted handoff is a related mechanism. When a replica is down during a write, another node stores a "hint" and replays it when the replica returns.
- At the application level, reconciliation jobs compare two systems of record, such as the payments ledger against the payment provider's settlement files, or inventory counts against the warehouse. They then flag or repair mismatches. These jobs are the safety net for every bug in the event pipeline.
How databases expose consistency#
Most databases let you choose a model per request or per session. The table summarises the main settings, and the sections after it explain each family.
| Database | Settings | What you get |
|---|---|---|
| PostgreSQL / MySQL | Read from primary vs replica; synchronous_commit, synchronous standbys; isolation levels | Primary reads: strong. Async replica reads: eventual, prefix-consistent per replica |
| Cassandra / ScyllaDB | Per-statement level: ONE, QUORUM, LOCAL_QUORUM, EACH_QUORUM, ALL; SERIAL for lightweight transactions | Tunable: R + W > N gives overlapping quorums; SERIAL gives linearizable compare-and-set via Paxos |
| DynamoDB | ConsistentRead=true per read; transactions; global tables | Strong reads within a region from the leader replica; default eventual reads at half the read cost; global tables replicate asynchronously across regions by default |
| MongoDB | writeConcern (w:1, w:"majority"), readConcern (local, majority, linearizable, snapshot), readPreference; causal sessions | From fast and possibly rolled-back, to majority-durable, to linearizable single-document reads; causal within a session |
| Azure Cosmos DB | Five levels: Strong, Bounded staleness, Session, Consistent prefix, Eventual | Session is the default and gives read-your-writes and monotonic reads per session token |
| Spanner / CockroachDB | Default strong reads; stale or follower reads with a bound | Strict serializability by default; bounded-staleness reads served locally for lower latency |
| etcd / ZooKeeper | etcd: linearizable or serializable reads; ZooKeeper: sync before read | Linearizable writes; reads strong or possibly stale by choice |
| Redis (with replicas) | Read from primary or replica; WAIT for replica acknowledgements | Async replication: no strong guarantee across failover, even with WAIT |
| Amazon S3 | None needed | Strong read-after-write consistency for all objects since December 2020 |
Quorums (N, R, W). In Dynamo-style stores, each key has N replicas. A write waits for W acknowledgements, and a read queries R replicas and returns the newest version. If R + W > N, every read quorum overlaps every write quorum in at least one replica, so the read usually includes the latest acknowledged write.
| N | W | R | Overlap? | Behaviour |
|---|---|---|---|---|
| 3 | 1 | 1 | No | Fastest; reads often stale right after writes |
| 3 | 2 | 2 | Yes | Classic balance; tolerates one replica down for both reads and writes |
| 3 | 3 | 1 | Yes | Fast reads, but any replica down blocks writes |
| 3 | 1 | 3 | Yes | Fast writes, but any replica down blocks reads |
| 5 | 3 | 3 | Yes | Tolerates two replicas down |
Even with R + W > N, quorums alone are not linearizable:
- Sloppy quorums may accept writes on substitute nodes during failures, outside the key's normal replicas.
- Concurrent writes resolved by last-writer-wins can lose updates.
- A failed write that reached fewer than W replicas is not rolled back, so later reads may or may not see it.
- Without synchronous read repair, two readers can see new and then old values in sequence.
Cassandra's lightweight transactions (IF NOT EXISTS, IF version = 3) use Paxos at the SERIAL level when you need true compare-and-set. See Quorums and Leaderless Replication.
Partitioned databases. Cassandra, DynamoDB and MongoDB all distribute data by a partition key, or a shard key in MongoDB, and route each request to the replicas for that key.
- Single-key guarantees come from the partition's own replica group, so strong operations on a single key or partition are relatively cheap.
- Cross-partition guarantees are expensive or unavailable. A strongly consistent read of one item is easy. A consistent snapshot across many partitions needs distributed transactions or timestamps, as in Spanner and CockroachDB.
- The design lesson: choose partition keys so that the data needing strong consistency together lives in one partition. Examples: all seats of one event section, or all line items of one order.
An anomaly catalogue: what each model forbids#
Models are easier to choose when you know the concrete bugs each one rules out. The table lists the anomalies engineers actually meet, with a scenario for each and the weakest model that prevents it.
| Anomaly | Scenario | Weakest model that forbids it |
|---|---|---|
| Stale read | A read after a completed write returns the old value | Linearizability (or bounded staleness, within the bound) |
| Read-your-writes violation | You rename a playlist, refresh, and see the old name | Read-your-writes |
| Non-monotonic read | A follower count shows 1,204, then 1,198 on the next refresh | Monotonic reads |
| Causal reversal | A reply appears before the message it answers | Causal consistency |
| Out-of-order writes from one client | "Make account private" then "post photo" are applied in reverse, so the photo is briefly public | Monotonic writes (PRAM / FIFO) |
| Divergent replicas forever | Two replicas keep different values after writes stop | Eventual consistency (needs a deterministic conflict rule) |
| Lost update | Two clients read a counter of 10, both write 11 | Serializable transactions, compare-and-set, or a CRDT counter |
| Write skew | Two doctors each check that "someone else is on call" and both go off call | Serializability (snapshot isolation allows it) |
| Split brain | Two nodes both believe they are leader and accept writes | Linearizable leader election with fencing |
| Read skew (non-atomic visibility) | You see a new order row but not its line items | Atomic visibility: transactions, snapshot reads, or RAMP-style protocols |
The last four are transactional anomalies, which involve several objects. The rest are about one object's replicas. A design usually needs answers to both: "which replica model?" and "which isolation level?". They are separate dials, set by separate mechanisms.
Cache consistency: the most common source of stale reads#
Read traffic usually dwarfs writes, which is why read scaling happens first. A ratio of 10 reads per write is a common starting point, and content-heavy products reach 100:1 or more. A single feed load can trigger a hundred reads (photos, authors, like counts, comment previews), while the same user posts once a day. So teams add caches, and caches are where most real-world staleness lives.
With cache-aside, the application reads the cache first, falls back to the database on a miss, and fills the cache. On a write, it updates the database and then deletes the cache entry. Deleting is safer than updating the entry, because two concurrent "update cache" calls can land in the wrong order. Even so, one race remains.
The reader fetched the old value before the write, but stored it in the cache after the writer's delete. The cache then serves the stale price until its TTL runs out.
Four standard defences, from cheapest to strongest:
- A TTL on every entry. Staleness is then bounded by the TTL even when everything else fails. A 60-second TTL turns "stale forever" into "stale for at most a minute". That is bounded staleness by construction.
- Delayed double delete. Delete on write, then delete again after a short delay, somewhat longer than a typical read-then-fill, say 500 ms. This catches most racing fills.
- Leases or version checks on fill. "Scaling Memcache at Facebook" (Nishtala et al., NSDI 2013) describes a lease: on a miss, the cache hands the reader a token; a delete invalidates outstanding tokens; and a fill carrying an invalid token is rejected. The race above becomes impossible. The same paper uses leases to stop thundering herds: only one client per key gets a token to refill, and the others wait briefly. A simpler variant stores a version with each value and rejects fills older than the cached version.
- Invalidation from the commit log. Rather than trusting every code path to delete the cache, a CDC process tails the database's commit log and deletes, or refreshes, the keys each committed change affects. Facebook's design broadcasts deletes from the MySQL commit log to cache clusters in the same way. It catches writes from scripts and backfills too.
When updates must be visible immediately. If a feature truly needs read-after-write freshness through a cache, add a session guarantee:
- Write-through for the writer. Write the new value into the cache as part of the write. The writer's next read is then fresh.
- Bypass the cache briefly. Route the writer's reads past the cache for a few seconds after a write.
Everyone else tolerates the short staleness window. For truly critical reads, such as the final price at checkout, skip the cache entirely and read the source of truth.
Consistency and the data model#
The shape of the data decides how many copies of each fact exist, and every copy is another chance to be inconsistent.
Relational (normalised). Each fact lives in exactly one row: a user's name is in users, and posts refer to it by user_id. There is nothing to keep in sync inside the database, and ACID transactions update several tables atomically. That is why a relational database is the default when correctness matters: payments that must not double-charge, inventory that must not oversell. The usual objection, scalability, is often overstated. Read replicas, caching, connection pooling and sharding take relational systems a very long way.
Document (embedded). A document database may embed a user's posts inside the user document, which removes joins.
- Updates inside one document are atomic in most document stores. Embedding related data therefore creates a consistency boundary: everything in one document changes together.
- But duplication across documents is not covered by that boundary. If the author's name is also copied into every comment document, a rename must update every copy, and readers will see a mix of old and new names until all copies are rewritten.
Key-value (flat). Lookups work by exact key only, so the same data is often stored under several keys, one per access pattern (user:42, email:sam@example.com, handle:sam). Reads are as fast as they can be. Consistency is weakest here, because a change must be written to every key, usually without a transaction, and a failure part-way leaves the keys disagreeing.
The common pattern is to keep SQL as the source of truth, with a key-value cache (Redis) in front for hot data. The cache's inconsistency is then bounded and repairable.
Wide-column. Cassandra-style stores are designed around query patterns. Data is often written to several tables, such as posts_by_user and posts_by_hashtag, for different reads. A logged batch can make such multi-table writes eventually all-or-nothing, but readers may still see one table updated before the other.
The rule of thumb. Every denormalised copy needs an owner and an update path, usually an event stream, plus a reconciliation job that catches drift. If you cannot name the update path for a copy, it will go stale.
Consistency across shards: transactions, sagas and shard keys#
Inside a single database, a transaction makes "deduct inventory and create the order" atomic. Sharding breaks this when the two rows live on different shards, because two independent databases do not share a transaction.
Two-phase commit (2PC) is the textbook fix.
- A coordinator asks every participant shard to prepare: each one makes the change durable but invisible, holds its locks, and votes yes or no.
- If all vote yes, the coordinator tells everyone to commit. Otherwise it tells everyone to abort.
2PC is consistent, but slow and fragile.
- Slow. It needs at least two round trips, and locks are held across both.
- Blocking on coordinator failure. If the coordinator crashes after the participants vote yes but before they hear the decision, the participants are in doubt. They cannot commit, because another participant may have voted no. They cannot abort, because the coordinator may already have told someone to commit. They hold their locks until the coordinator recovers.
Production systems that use 2PC make the coordinator itself fault-tolerant, for example by storing its decision in a consensus group, as Spanner does. Most application teams avoid hand-rolled 2PC entirely.
Three alternatives, in order of preference:
- Choose the shard key so the transaction never spans shards. Shard by
user_idand keep everything about a user on one shard: balance, transaction history, profile. Almost all operations then become single-shard transactions, which are fast and fully ACID. If you constantly need cross-shard transactions, you probably picked the wrong shard key or the wrong boundaries. - Use a saga for the rare cross-shard operation. Split the operation into local steps, each with a compensating action that semantically undoes it.
- For a transfer: (1) debit A on shard 1; (2) credit B on shard 2; if step 2 fails, (3) refund A.
- The system is briefly inconsistent: the money has left A but not reached B. Sagas therefore give eventual consistency, with no isolation between concurrent sagas.
- Make every step idempotent, record saga progress durably, and design the intermediate states to be visible but harmless, for example a "transfer pending" line on both statements. See Distributed Transactions.
- Accept eventual consistency where it is harmless. A follower count copied onto several shards for fast profile reads can disagree for a few seconds and converge through events. Coordinating it with a distributed transaction would cost far more than the anomaly.
Managed systems do the sharding, not the thinking. Modern databases mostly distribute data for you, each in its own way:
| System | How keys are distributed |
|---|---|
| Cassandra | Hashes partition keys onto a token ring with virtual nodes, a form of consistent hashing |
| DynamoDB | Hashes the partition key to internal partitions, which split and merge as they grow |
| MongoDB | Range-based chunks on the shard key (ranges over the hash space if the key is hashed), moved by a background balancer |
| Vitess and Citus | Sharding layers in front of MySQL and PostgreSQL |
| Spanner, CockroachDB and similar distributed SQL databases | Built-in sharding, with distributed transactions |
None of them changes the consistency lesson. Single-partition operations are cheap and strong. Cross-partition atomicity is either unavailable, as in Cassandra outside a partition, limited, as in DynamoDB transactions of up to 100 items, or bought with extra round trips, as in distributed SQL. In an interview, "DynamoDB with user_id as the partition key, so each user's writes are single-partition" is the sentence that matters.
Multi-region consistency patterns#
A second region turns every consistency decision into a latency decision. A round trip between regions costs 60-150 ms, against about 1 ms inside a region. Five patterns cover almost every multi-region design. Each one takes a different position on the model ladder.
| Pattern | How it works | Model it gives | Latency profile |
|---|---|---|---|
| Single write region, local read replicas | All writes go to one region; others replicate asynchronously | Strong in the write region; eventual (prefix-consistent) elsewhere | Remote writes pay one cross-region trip; reads local |
| Home region per user or entity | Each user's data is written in their home region; others hold async copies | Strong for each user's own data; eventual for viewers in other regions | Local writes for most users; cross-region only for cross-user operations |
| Active-active with conflict resolution | Every region accepts writes and replicates to the others; conflicts merged by LWW or CRDTs | Eventual (strong eventual with CRDTs) | Local reads and writes everywhere |
| Global consensus | Each write commits to a majority spread across regions (Spanner, CockroachDB, multi-region etcd) | Linearizable / strictly serializable | Every write pays a majority round trip, e.g. 60-100 ms |
| Consensus writes, local stale reads | Writes as above; reads at a timestamp slightly in the past from the local replica | Strong writes; bounded-staleness reads | Writes slow, reads about 1 ms |
A worked comparison. A user in Frankfurt edits a shared document whose database runs in Virginia, Oregon and Frankfurt.
- Single write region in Virginia. The edit costs one Frankfurt-to-Virginia round trip, about 90 ms. A colleague in Oregon reads a local replica that is perhaps 100 ms behind.
- Global consensus. The edit needs a majority of the three regions. With the leader in Frankfurt and the nearest follower in Virginia, it costs about 90 ms. The Oregon colleague's linearizable read costs a trip to the leader, about 150 ms. A follower read costs 1 ms and may be a moment old.
- Active-active with a CRDT document model, the approach of collaborative editors. The edit applies locally in under 10 ms, and reaches Oregon about 150 ms later. Concurrent edits merge without conflicts. There is no global order, but every replica converges to the same text.
Which one is right depends on the invariant, not on fashion. A document editor has no invariant that merging can break, so active-active fits. A bank ledger does, so it needs consensus or a single write region.
Common traps.
- Last-writer-wins across regions with skewed clocks. It can drop a write that happened later in real time. Prefer version vectors, CRDTs, or single-writer ownership for anything that matters.
- "Read local, write global" without session guarantees. A user writes in Frankfurt, the write commits in Virginia, and their next read hits the stale Frankfurt replica. Carry the commit position, or route the user's reads to the write region briefly.
- Failing over a single write region with async replication. Promoting a remote replica loses whatever had not replicated, which is the replication lag times the write rate. Either accept that RPO explicitly, or replicate synchronously to a nearby standby.
Consistency at the client and the edge#
The database is not the only place where consistency is decided. Browsers, mobile apps and CDNs keep their own copies, and each has its own model.
Optimistic UI. Many apps show a change before the server confirms it: the "like" heart fills instantly, and a sent message appears in the thread with a "sending" tick.
- This is read-your-writes provided entirely by the client. The client's local copy includes the user's pending writes.
- The app must reconcile when the server answers. Confirm on success. On failure, roll back visibly, with a message.
- If the server assigns the canonical order, as in chat, the client must re-sort pending items once their server sequence numbers arrive.
Offline-first and local-first apps. Note-taking, field-work and collaborative apps let users edit with no connection at all.
- Each device is a full replica that accepts writes. That is the AP extreme: availability even during the longest possible partition.
- Sync on reconnect needs a merge rule. CRDT libraries such as Automerge and Yjs make the merge automatic for text, lists and maps.
- Per-record version numbers let a simpler app detect conflicts and ask the user which version to keep.
HTTP-level optimistic concurrency. REST APIs protect against lost updates between clients with ETags.
- The server returns
ETag: "v7"with a resource. - A client that wants to update it sends
If-Match: "v7". - If someone else changed the resource in the meantime, the server answers
412 Precondition Failed, and the client re-reads and retries.
This is compare-and-set over HTTP, and it upgrades a weak protocol to "no lost updates" cheaply.
CDN and browser caching. HTTP caching is bounded staleness by construction. Cache-Control: max-age=60 means "at most 60 seconds stale".
stale-while-revalidate(RFC 5861) lets a cache serve a stale copy while it fetches a fresh one in the background. That trades a short extra window of staleness for never making a user wait on the origin.- When freshness is critical, version the URL. For example,
app.3f9c1.jsis a new URL per deploy, so it can never be confused with the old file. Use purge APIs for content that changed in place.
Choosing a model per use case#
| Use case | Model | Why |
|---|---|---|
| Account balance before debit, payments | Strong (linearizable / strictly serializable) | Overdrafts and double charges are unacceptable |
| Seat booking, inventory decrement | Strong for the write (transaction or compare-and-set) | Two buyers must not get the last item |
| Username or email uniqueness | Strong (unique constraint or consensus) | Two users must not register the same name |
| Distributed locks, leader election, config | Linearizable (etcd, ZooKeeper) | Split-brain otherwise |
| User's own profile, settings, posts | Read-your-writes + monotonic reads | Users must see their own changes; others can lag |
| Comments, chat, collaborative docs | Causal (per conversation or document) | Replies must not appear before what they answer |
| Social feed, timelines | Eventual + session guarantees | Seconds of lag is fine; never "go back in time" for one user |
| Product catalogue, prices on listing pages | Bounded staleness (or eventual with short TTLs) | Slightly stale is fine; checkout re-reads the authoritative price |
| Like counts, view counts, analytics | Eventual | Approximate and converging is fine |
| Search results | Eventual (seconds) | Index lags source; show own new items from the source |
| DNS, CDN content | Eventual (TTL bound) | Global scale, caching essential |
| Live video, VoIP, game positions | Weak | Newer data supersedes old; retransmitting late data is useless |
Worked example: one photo-sharing app, six models#
Models make most sense in combination. Take a photo-sharing app with 50 million daily users and about 100 reads per write. Here is the model each feature gets, the mechanism behind it, and the number that justifies it.
1. Username registration: linearizable.
- Mechanism: a unique index on
users.handlein the primary PostgreSQL. The insert either succeeds or fails with a constraint violation. - Numbers: a few hundred sign-ups per second. That is trivial for one primary, so strong consistency costs nothing that matters.
2. Posting a photo: read-your-writes for the author, eventual for everyone else.
- Mechanism: the post row commits on the primary, and the response carries the commit's log position. For the next few seconds, the author's profile and feed reads go to a replica that has applied that position, or to the primary.
- Followers' feeds are rebuilt asynchronously from an event stream. A typical delay of 1-2 seconds is invisible to followers.
3. Comments under a photo: causal per photo.
- Mechanism: all comments for one photo go to the same partition of the comments store, keyed by
photo_id, and are read in that partition's order. - A reply therefore never appears before the comment it answers. No cross-partition coordination is needed, because conversations do not span photos.
4. Like counts: eventual, with no lost increments.
- Mechanism: likes are recorded as individual rows (the source of truth, which also prevents double-likes per user). Displayed counts are aggregated asynchronously into a counter cache, or kept as CRDT counters per region.
- Numbers: a viral photo might receive 20,000 likes per second. A single strongly consistent counter row would become a hot spot. An eventually consistent aggregate is fine, because nobody can tell 1,000,212 from 1,000,250.
5. Follower count on a profile: monotonic reads.
- Mechanism: sticky replica routing per viewer, so the number never appears to go backwards between refreshes, even though it is a few seconds stale.
6. Search and "explore": eventual, seconds of lag.
- Mechanism: an index fed by CDC. A brand-new post appearing in search 5 seconds later is acceptable. The author's own new post is shown from the source on their profile, so they never think it is missing.
Of the six features, only username registration needs coordination on every operation. The posting path adds a cheap session guarantee, and everything else runs on replicas, caches and streams. That ratio is typical: strong consistency is a small, protected core, not the default.
Measuring consistency in production#
A promised model is only real if you can see when it is violated. Treat staleness like latency: measure it continuously, give it an objective, and alert when it drifts.
Replica lag. The database's own counters show how far each replica is behind: pg_stat_replication and pg_last_xact_replay_timestamp() in PostgreSQL, and Seconds_Behind_Source in MySQL. Built-in lag numbers can mislead, however. MySQL's figure, for example, measures from the last event the replica applied, so it can report zero while the replica is not receiving events at all. A more honest technique is the heartbeat row:
- A small job on the primary updates
heartbeat.ts = now()once per second. - A probe on each replica reads that row, and computes lag as the replica's current time minus the replicated
ts.
This measures exactly what users experience, which is how old the data is. Percona Toolkit's pt-heartbeat does this for MySQL.
Pipeline lag. For eventual copies built from streams, track two things:
- Kafka consumer lag, in messages and in seconds, for each consumer group;
- end-to-end freshness: stamp each event with its commit time, and measure the gap at the moment the search index or cache applies it.
A consumer that is "only" 50,000 messages behind may be 2 seconds or 20 minutes behind, depending on throughput, so alert on time, not count.
Cache age. Record the age of cached entries when they are served, or simply enforce TTLs. To detect invalidation bugs, sample cache hits and compare them with the source. A mismatch rate that rises after a deploy points at a missed invalidation.
Consistency objectives. Write them down like latency objectives, for example:
- "99.9% of a user's reads within 10 seconds of their own write reflect that write" (read-your-writes);
- "search freshness p99 under 5 seconds";
- "zero seats with two confirmed bookings", checked by a nightly invariant query.
The last kind, an invariant audit, is the final safety net. It catches bugs in every layer above, including ones nobody predicted.
Runtime protection. Measurement can also steer traffic.
- Remove a replica from the read pool when its lag exceeds the bound. That turns eventual into bounded staleness.
- Shed or degrade features whose freshness objective cannot currently be met, such as hiding "live" counters during a backlog, rather than show misleading data.
When to Use It#
- In non-functional requirements, when stating per-feature consistency ("bookings strong, feed eventual with read-your-writes").
- When adding read replicas, caches, search indexes or regions, which are each a new source of staleness.
- When configuring databases: quorum sizes, consistency levels, read and write concerns, which replica serves which reads.
- When debugging "my change disappeared" or "the count went backwards" reports.
- When evaluating a database's claims: which model does it actually guarantee, and under which failures?
When NOT to Use It#
- Single-node systems with no replicas or caches: reads already see the latest write, and you can reason in terms of transactions and isolation levels instead.
- Do not pay for strong consistency everywhere "to be safe". It costs latency, money and availability, and most features do not need it.
- Do not settle for plain eventual consistency where users act on what they read and an invariant can be broken. Use a stronger model for that operation.
- Do not mix up isolation levels (how transactions interleave) with replica consistency (how fresh reads are). Treat them as separate decisions.
How to Implement It#
- List the operations and their invariants: what must never happen (double sale, negative balance, duplicate username) and which anomalies users would notice (their own change missing, a reply before its post).
- Assign the weakest sufficient model to each operation, using the table above, and write down the staleness bounds you promise ("feed lag p99 under 5 s").
- Map models to mechanisms:
- strong → primary or consensus reads and writes, transactions, conditional writes;
- session → sticky routing plus LSN tokens or a primary-read window;
- causal → per-entity partitions or dependency tokens;
- eventual → replicas, caches, CDC.
- Configure the stores per request, for example
ConsistentRead,LOCAL_QUORUMorw:"majority", rather than one global setting. - Make convergence reliable: an outbox or CDC for propagation, idempotent and version-checked consumers, read repair and anti-entropy for replicas, and reconciliation jobs between systems of record.
- Measure staleness: replica lag, consumer lag and cache age, with alerts when they exceed the promised bounds.
- Test under failure: partitions, failovers and clock skew, with Jepsen-style tests or chaos experiments, to confirm the anomalies you excluded really cannot happen.
# Per-request consistency choices (illustrative)
-- Cassandra (CQL; level set per statement in the driver)
CONSISTENCY LOCAL_QUORUM;
SELECT * FROM carts WHERE user_id = ?; -- strong within the local DC
INSERT INTO usernames (name, user_id) VALUES (?, ?)
IF NOT EXISTS; -- Paxos (SERIAL) compare-and-set
// DynamoDB
GetItem({ Key, ConsistentRead: true }) // strong, from the leader replica
GetItem({ Key }) // eventual, half the read cost
// MongoDB
db.orders.insertOne(doc, { writeConcern: { w: "majority" } })
db.orders.find(q).readConcern("majority")
session = client.startSession({ causalConsistency: true })| Technology | Fits when |
|---|---|
| PostgreSQL / MySQL primary + async replicas | Strong core, eventual reads at scale, RYW via routing |
| Spanner, CockroachDB, YugabyteDB | Strong (strictly serializable) across regions, with bounded-staleness reads when needed |
| etcd, ZooKeeper, Consul | Linearizable coordination data |
| Cassandra, ScyllaDB | Tunable per query, from ONE to QUORUM and SERIAL |
| DynamoDB | Per-read strong or eventual; transactions for small multi-item updates |
| MongoDB | Read and write concerns, causal sessions |
| Cosmos DB | Explicit five-level menu, with session consistency as the default |
| Debezium + Kafka | Event-based sync from a strong core to eventual copies |
Trade-offs#
| Model | Gain | Cost | Pick when |
|---|---|---|---|
| Linearizable | Simplest to reason about; protects invariants | Majority or leader round trip per operation; unavailable on minority side | Locks, money, bookings, uniqueness |
| Sequential | One agreed order | Still needs ordering coordination; may lag | Coordination services' reads |
| Causal | Intuitive ordering, always available, local latency | Dependency metadata; harder to implement | Chat, comments, collaboration |
| Session guarantees | Fixes user-visible anomalies cheaply | Sticky routing, tokens, some primary load | Most user-facing apps on replicas |
| Bounded staleness | Predictable freshness | Must stop serving lagging replicas | Prices, leaderboards |
| Eventual | Fastest, cheapest, always available | Anomalies; conflict resolution needed | Feeds, counters, search, DNS |
| Weak | Lowest overhead | Updates may be lost entirely | Real-time media, games, caches |
| Snapshot isolation | Consistent reads without blocking writers | Write skew across rows | Most OLTP reads and reports |
| Two-phase commit across shards | Atomic multi-shard writes | Two round trips, locks held, blocks if coordinator fails | Rare, essential cross-shard updates on managed systems |
| Saga with compensation | No distributed locks, each step local | Visible intermediate states, no isolation | Cross-service or cross-shard workflows |
| Cache with TTL + invalidation | Huge read offload | Bounded staleness, invalidation races | Read-heavy data tolerant of seconds of lag |
Common Pitfalls#
- Reading from a replica straight after a write, so users think their change was lost.
- Load-balancing reads across replicas randomly, so values appear to go backwards between page loads.
- Assuming R + W > N makes a store linearizable.
- Using an eventually consistent read for a check-then-act decision, such as "is the seat free?" followed by "book it".
- Dual writes (DB commit, then publish an event) without an outbox, so copies drift permanently when one side fails.
- Event consumers that are not idempotent or ignore ordering, so replayed or reordered events corrupt copies.
- No reconciliation job, so divergence from bugs is never detected.
- Confusing SERIALIZABLE isolation with linearizable replication.
- Caches with no TTL, so one missed invalidation leaves data stale forever.
- Updating (instead of deleting) cache entries on write, so concurrent updates land out of order.
- Picking a shard key that forces most transactions to span shards, then reaching for 2PC everywhere.
- Denormalising a fact into many documents or keys without naming who updates each copy.
- Relying on snapshot isolation to protect a multi-row invariant, and getting write skew.
Real-World Examples#
Amazon S3 originally offered eventual consistency for overwrites and deletes. In December 2020, AWS announced strong read-after-write consistency for all S3 GET, PUT and LIST operations at no extra cost. Applications that had built workarounds for stale listings could remove them.
Azure Cosmos DB exposes five named consistency levels (strong, bounded staleness, session, consistent prefix, eventual) as a per-account default that requests can relax. Session consistency, the default, gives each client read-your-writes and monotonic reads via a session token.
MongoDB added causally consistent sessions in version 3.6. Within a session, a client reading from secondaries still observes its own writes and reads in causal order.
Facebook's "Scaling Memcache at Facebook" (Nishtala et al., NSDI 2013) describes leases that stop stale cache fills and thundering herds, and invalidations driven from the MySQL commit log. Together these keep a huge look-aside cache close to the database while tolerating brief staleness.
Meta's TAO paper (Bronson et al., USENIX ATC 2013) describes a geographically distributed graph store for the social graph, built over MySQL with caching tiers. It is eventually consistent overall, but provides read-after-write consistency for writes made through the same cache tier: an example of combining a weak global model with session-like guarantees where users notice.
In the Interview#
Deep Dive: Checking consistency, from definitions to JepsenShow
Histories and linearization points. A history lists each operation's invocation and response with its arguments and result. A history is linearizable if you can assign each operation a linearization point inside its interval such that, in the resulting order, every read returns the most recent write. Overlapping operations can be ordered either way. Non-overlapping ones must keep their real-time order.
Why checking is hard. Deciding whether a history is linearizable is NP-complete in general (Gibbons and Korach, 1997), because the checker may have to try many orders for overlapping operations. Practical checkers prune aggressively:
- Knossos, Jepsen's original checker, explores orderings with memoisation.
- Porcupine partitions histories by key.
- Elle (Kingsbury and Alvaro, VLDB 2020) checks transactional isolation anomalies. It builds a dependency graph from carefully designed operations, such as appends to lists, that reveal the order in which writes were applied, and then searches for cycles. A cycle means no serial order exists.
What testing has found. Jepsen analyses have repeatedly found real systems violating their documented guarantees under partitions, clock skew or process pauses:
- lost acknowledged writes during leader changes;
- stale reads from leaders that did not know they had been deposed;
- isolation anomalies in "serializable" modes.
Vendors have fixed many of these issues. The lesson for designers: a consistency claim is only as good as its behaviour under failure, so look for public analyses and test the paths you depend on.
The deposed-leader stale read. This is a classic bug. A leader is partitioned away, and a new leader is elected and accepts writes. Meanwhile the old leader, still believing it leads, serves reads from its local state, which is now stale. Linearizable systems prevent it in one of two ways:
- Read through the log, or a read-index round. The leader confirms with a majority that it is still leader before answering. This costs one round trip.
- Leader leases. Followers promise not to elect a new leader for a lease period, so the leader can answer locally while its lease is valid. This is safe only if clock drift is bounded, which is why Spanner invests in TrueTime and other systems add drift margins.
Deep Dive: Tracking causality with logical clocksShow
Lamport clocks. Each process keeps a counter. It increments the counter on every event, attaches the counter to messages, and on receipt sets its counter to max(local, received) + 1.
- If A happened before B, then
L(A) < L(B). - The converse does not hold:
L(A) < L(B)does not mean A caused B. - Lamport timestamps give a total order that is consistent with causality, which is useful for tie-breaking, but they cannot detect concurrency.
Vector clocks. Each process keeps a vector with one counter per process. It increments its own entry on each event. On receipt, it takes the element-wise maximum with the received vector, then increments its own entry. Vector clocks can tell causality from concurrency:
- V(A) < V(B) element-wise means A happened before B;
- if neither vector dominates, A and B are concurrent.
Example with three replicas:
- A write at replica 1 has
[1,0,0]. - Replica 2 sees it and writes
[1,1,0], which descends from the first write. - Replica 3, without seeing either, writes
[0,0,1]. That write is concurrent with both, so it is a conflict to merge.
Dynamo and Riak use per-key version vectors (one entry per replica, not per client) to detect sibling versions.
The size problem. Vectors grow with the number of writers. Real systems bound them in three ways:
- tracking replicas rather than clients;
- pruning old entries (Dynamo truncated its vector clocks, accepting rare false conflicts);
- dotted version vectors (Preguiça et al., 2010), which avoid sibling explosion when many clients write through the same replica.
Hybrid logical clocks (HLC). Kulkarni and colleagues proposed HLC in 2014. An HLC combines physical time with a logical counter. Timestamps stay close to wall-clock time, so they are human-meaningful and can be used for snapshots "as of 10:00:05", while still respecting causality even when clocks drift. CockroachDB and YugabyteDB use HLCs to order transactions, and MongoDB uses a similar cluster time for causal sessions.
Causal tokens in practice. You rarely implement vector clocks yourself. The common production pattern is a causal token: an opaque version, LSN or cluster time returned by each write and sent with subsequent requests. Any replica that has applied at least that version may serve the request. This is how MongoDB causal sessions, Cosmos DB session tokens and read-your-writes routing with LSNs all work.
Deep Dive: How eventual is eventual? Probabilistically bounded stalenessShow
"Eventually" can be quantified. Peter Bailis and colleagues ("Probabilistically Bounded Staleness for Practical Partial Quorums", VLDB 2012) modelled Dynamo-style stores and asked two questions:
- what is the probability that a read returns the latest value t milliseconds after a write?
- how many versions old can it be?
The intuition. With N = 3, W = 1, R = 1, a read immediately after a write hits a replica that already has the write with probability about one in three. That one replica is the one that acknowledged. The other two receive the write after the replication delay. If replication to the other replicas takes a few milliseconds, then after 10 ms almost every read sees the new value.
The staleness window is therefore set by replication latency, not by the consistency level. Measurements using latency distributions from LinkedIn and Yammer showed that partial quorums (R = W = 1) returned consistent data with high probability within tens of milliseconds, and quorums lowered latency much less than expected.
Worked example. Suppose replication delay to the non-acknowledging replicas is roughly exponential with a mean of 5 ms. After a write at t = 0:
- The probability that a given non-acknowledging replica has the write by time t is
1 - e^(-t/5). - With R = 1 choosing a replica at random, P(read is fresh at t) = 1/3 + 2/3 × (1 - e^(-t/5)).
- At t = 0: 33%.
- At t = 5 ms: 1/3 + 2/3 × 0.63 = 75%.
- At t = 20 ms: 1/3 + 2/3 × 0.98 = 99%.
- At t = 50 ms: above 99.99%.
Raising R to 2 makes the read fresh unless both chosen replicas lack the write. At t = 0, one of the two is likely the acknowledging replica, so freshness jumps to about 67%, and it approaches 100% much faster after that.
Design implications:
- For many user-facing reads, "eventual" means milliseconds in the common case. The real risk is the tail: replicas lagging seconds or minutes during overload, GC pauses, or a replica rebuilding after failure.
- Therefore monitor lag (replication lag, consumer lag) and set alerting bounds. Stop routing reads to replicas beyond the bound, which turns eventual into bounded staleness.
- Read-your-writes and monotonic reads remove the most visible anomalies cheaply, even when global staleness is not tightly bounded.
- For operations protecting invariants, probability is not enough. "99.99% fresh" still means double bookings at scale, so use strong mechanisms there.
Deep Dive: Why CRDTs converge: semilattices in plain termsShow
CRDTs give strong eventual consistency: two replicas that have received the same set of updates are in the same state, whatever order the updates arrived in. The reason is a small piece of algebra, and once you see it you can tell whether any merge function is safe.
State-based CRDTs (CvRDTs). Each replica holds a state, and replicas occasionally send their whole state to each other. The receiver combines the incoming state with its own using a merge function. Convergence is guaranteed if merge has three properties:
- Commutative: merge(a, b) = merge(b, a). The order of gossip does not matter.
- Associative: merge(merge(a, b), c) = merge(a, merge(b, c)). The grouping of exchanges does not matter.
- Idempotent: merge(a, a) = a. Receiving the same state twice changes nothing.
States with such a merge form a join-semilattice: merge returns the "least upper bound" of two states, and every update only moves a replica's state upward in the lattice. Since every replica only climbs, and any two states have a unique least upper bound, all replicas that have seen the same updates sit at the same point.
Checking examples against the three rules:
- Max of two numbers. It is commutative, associative and idempotent, so a "highest score" register is a CRDT.
- Set union. It satisfies all three, so a grow-only set is a CRDT.
- Addition. It is not idempotent: receiving "+5" twice gives +10. That is why a naive replicated counter double-counts.
- The G-Counter fix. Keep one slot per replica, and merge by taking the maximum per slot, which is idempotent. The counter's value is the sum of the slots. For example, replica A's state is [A:7, B:3] and replica B's is [A:5, B:4]. The merge is [A:7, B:4], so the value is 11, no matter how many times or in what order the states are exchanged.
Operation-based CRDTs (CmRDTs). Replicas send operations instead of states. Concurrent operations must commute, and the delivery layer must provide exactly-once, causal delivery.
- Messages are smaller than whole states.
- But the delivery layer has to do more work.
- Delta-state CRDTs sit in between: they ship only the part of the state that changed, but merge it like a state, so duplicates and reordering are harmless.
Removals are the hard part. Removing an element from a set is not "moving up" in a union lattice. CRDTs handle it in one of two ways:
- Tombstones: remember what was removed. The 2P-Set does this, but an element can never be re-added.
- Unique tags per add (the OR-Set): a remove cancels only the tags it has observed.
Tombstones and tags grow forever unless they are garbage-collected once every replica has seen them. Deciding when that is safe requires knowing what every replica has seen, which is a form of coordination. Even CRDTs need a little agreement eventually, just off the critical path.
What CRDTs cannot do. The lattice moves only upward, so a CRDT cannot enforce a global upper bound. "At most 100 seats sold" requires knowing what other replicas are doing now. This is the formal reason invariants like uniqueness and capacity need coordination, and it matches the CALM theorem described on the CAP page.
Deep Dive: Strong consistency with clocks: Spanner, TrueTime and HLC databasesShow
Linearizable single-key operations need only a leader and a quorum. Strict serializability across many partitions and regions is harder. A read-only transaction touching 50 partitions must see one consistent snapshot without locking all 50. Two families of systems solve this with clocks.
Spanner and TrueTime. Spanner (Corbett et al., OSDI 2012) gives every transaction a commit timestamp, and makes timestamps respect real time. Google's TrueTime API returns an interval [earliest, latest] that is guaranteed to contain the true time. GPS receivers and atomic clocks in each data centre keep the uncertainty ε to a few milliseconds.
- Commit wait. A read-write transaction chooses a commit timestamp s no earlier than
TrueTime.now().latest. It then waits untilTrueTime.now().earliestis later than s before it makes the commit visible and releases its locks. - What the wait buys. Once the wait ends, s is definitely in the past everywhere. Any transaction that starts later, anywhere in the world, gets a larger timestamp. This is external consistency: strict serializability in real-time order.
- The cost. The wait is roughly 2ε per write, a few milliseconds, paid on top of the Paxos round trips. It is a small, explicit price for global real-time ordering.
- Lock-free snapshot reads. A read-only transaction picks a timestamp and reads every partition "as of" that timestamp, from any replica that is caught up to it. No locks are taken, and reads at a slightly older timestamp can be served by the nearest replica. These are the bounded-staleness and follower reads mentioned earlier.
HLC-based databases without atomic clocks. CockroachDB and YugabyteDB run on ordinary servers whose NTP-synchronised clocks may differ by tens or hundreds of milliseconds. They use hybrid logical clocks plus a configured maximum clock offset; CockroachDB's default is 500 ms.
- The uncertainty window. When a transaction reads a value whose timestamp is slightly ahead of its own, but within the maximum offset, it cannot tell whether that write happened before it in real time.
- Uncertainty restarts. In that case the transaction restarts at a higher timestamp, which costs latency for that transaction.
- The clock-drift safety net. Nodes whose clocks drift beyond the configured offset shut themselves down, because the guarantee depends on the bound.
- The resulting guarantee. Serializable transactions, plus linearizability for each key. Real-time order is guaranteed for transactions that touch common keys, but not necessarily for completely unrelated ones.
The pattern. Clocks do not replace consensus; they let a system order transactions across consensus groups without extra messages. The uncertainty ε becomes a direct latency cost (commit wait), or an occasional retry cost (uncertainty restarts). That is PACELC's "else, latency" made explicit in yet another form.
Deep Dive: Transactional models between serializable and eventualShow
Replica models describe single objects. Real applications also need multi-object guarantees. Between full serializability and "anything goes" lie several named transactional models.
Snapshot isolation (SI). Each transaction reads from a consistent snapshot taken when it starts, and commits only if no concurrent transaction wrote the same rows ("first committer wins"). Berenson and colleagues characterised it in "A Critique of ANSI SQL Isolation Levels" (SIGMOD 1995).
- What it prevents: dirty reads, non-repeatable reads, read skew and lost updates on the same row.
- What it allows: write skew. Two doctors are on call, and the rule is "at least one must stay on".
- Each doctor's transaction reads "two on call", so each decides it is safe to leave.
- Each transaction updates a different row: its own doctor's status.
- Neither write conflicts with the other, so both commit, and nobody is on call.
- Where it runs. Oracle's "serializable" level is SI. PostgreSQL's REPEATABLE READ is SI. PostgreSQL's SERIALIZABLE adds serializable snapshot isolation (Cahill, Röhm and Fekete, SIGMOD 2008; implemented in PostgreSQL as described by Ports and Grittner, VLDB 2012). SSI detects the dangerous read-write dependency patterns and aborts one of the transactions.
Parallel snapshot isolation (PSI). Walter (Sovran, Power, Aguilera and Li, SOSP 2011) relaxed SI for geo-replication.
- Each site commits transactions locally, in its own order.
- Causality is preserved across sites.
- Different sites may see unrelated transactions in different orders.
This lets each region commit at local latency, while still guaranteeing no write-write conflicts on objects that have a preferred site.
Read atomic and RAMP transactions. Bailis and colleagues ("Scalable Atomic Visibility with RAMP Transactions", SIGMOD 2014) targeted a common, specific need: atomic visibility. Either all of a transaction's writes are visible to a reader, or none are. Examples are a new friendship row together with both users' friend lists, or a secondary index entry together with its base row.
- How it works. Each write carries metadata naming its sibling writes. A reader that sees one write but not its siblings fetches the missing versions in a second round.
- What it costs. No locks and no coordination between writers, so it scales and stays available.
- What it does not prevent. It does not stop lost updates or write skew.
Where this leaves a designer:
| Need | Weakest sufficient model |
|---|---|
| Invariants across rows ("at least one on call", "total holds ≤ capacity") | Serializable (SSI or 2PL), or materialise the conflict into a single row that both transactions update |
| Reports and readers must not see half-applied changes | Snapshot reads or read atomic |
| One row updated concurrently | Row-level compare-and-set, or SI's first-committer-wins |
| Multi-region local commits, with causality | PSI-like designs, or per-region ownership |
The Jepsen project's "consistency models" map draws all of these, transactional and non-transactional, in one hierarchy. Viotti and Vukolić's survey "Consistency in Non-Transactional Distributed Storage Systems" (ACM Computing Surveys, 2016) catalogues more than 50 non-transactional models. These are good references when a vendor's documentation uses an unfamiliar name.
Key Takeaways#
- A consistency model is a contract about which values reads may return; stronger models allow fewer surprises but need more coordination.
- Linearizability means one apparent copy in real-time order; it protects locks, uniqueness and money, at the cost of round trips and partition availability.
- Sequential consistency keeps one global order without real-time recency; causal consistency keeps causes before effects and stays available.
- Session guarantees (read-your-writes, monotonic reads, monotonic writes, writes-follow-reads) fix the anomalies users notice, cheaply.
- Eventual consistency only promises convergence; weak consistency promises nothing and suits real-time data that is quickly superseded.
- BASE favours availability and convergence over ACID's immediate correctness; most systems are ACID at the core and BASE at the edges.
- Copies converge through event-based sync (CDC, outbox), read repair and background reconciliation (Merkle-tree anti-entropy, audit jobs).
- Databases expose models as settings (quorums, consistency levels, read and write concerns); choose the weakest model that keeps each feature correct, and measure staleness.
- Caches are the commonest source of stale reads: delete on write, bound every entry with a TTL, and use leases, versions or CDC invalidation to close races.
- Sharding breaks single-database transactions; choose shard keys that keep transactions on one shard, use sagas for the rest, and avoid hand-rolled 2PC.
- Replica models and isolation levels are separate dials; snapshot isolation still allows write skew.