Eventual Consistency in Database Systems
"Eventual consistency. This is a specific form of weak consistency; the storage system guarantees that if no new updates are made to the object, eventually all accesses will return the last updated value." — Werner Vogels, Eventually Consistent, All Things Distributed (2008; a revised version appeared in CACM in 2009)
Summary: As soon as a database keeps more than one copy of your data, a read can return an older value than the last write; consistency models name exactly how old, for whom, and in what order. Focus: Strong vs eventual, the four session guarantees, causal and bounded staleness, quorums (R+W>N), sloppy quorums, LWW conflicts, and the exact knob each product exposes: PostgreSQL remote_apply, MySQL semi-sync and GTID waits, Cassandra consistency levels, MongoDB readConcern/writeConcern/causal sessions, DynamoDB ConsistentRead, Cosmos DB's five levels, CockroachDB follower reads. Learning goal: For each read in your application, name the weakest guarantee that is still correct, pick the product knob that gives it, and route, wait or degrade the UX when the replica is behind.
This page is the complete reference for consistency between copies of data inside database systems: what a replica can show you, which guarantees you can ask for, and how PostgreSQL, MySQL, SQL Server, Oracle, SQLite, Redis, MongoDB, Cassandra, DynamoDB, Azure Cosmos DB, CockroachDB and Spanner expose them. It deliberately does not re-teach four neighbours. Streaming and logical replication, replica lag mechanics and failover tooling are in Replication, Read Replicas & Failover. Consensus (Raft/Paxos), leaseholders and two-phase commit are in Distributed SQL, Consensus & 2PC. Isolation between concurrent transactions on one primary (dirty read, write skew, Serializable) is in Isolation Levels; the two words "consistency" mean different things, and this page explains the difference once. The formal model zoo (linearizability vs serializability, sequential consistency, convergence proofs) belongs to the System Design chapter Consistency Models, and CAP/PACELC to CAP & PACELC.
Page map
| If you are looking for | Go to |
|---|---|
| A table you can memorise in one minute | Everything in one minute |
| Why databases give up strong consistency at all | Why eventual consistency exists |
| Bayou, Dynamo, Vogels, PBS, Jepsen: where the words come from | Where the vocabulary comes from |
| Strong vs eventual, convergence, isolation vs consistency | Strong, eventual, and the two meanings of "consistency" |
| Read-your-writes, monotonic reads/writes, writes-follow-reads, causal, bounded staleness, each with a timeline | The guarantees, one by one |
| PostgreSQL, MySQL, Cassandra, MongoDB, DynamoDB, Cosmos DB, CockroachDB, Spanner, SQL Server, Oracle, SQLite, Redis | What each product really offers |
R+W>N, sloppy quorums, hinted handoff, read repair, LWW, version vectors, session tokens, error codes | Mechanics |
Go and Laravel code: sticky routing, LSN fences, MongoDB causal sessions, Cassandra CL per query, DynamoDB ConsistentRead | Solving the classic problems |
| Optimistic UI, "saved" banners, read-after-write routing | UX patterns for staleness |
| Jepsen, Elle, Knossos, measuring staleness yourself | Testing consistency |
| Which level for which read | Choosing a consistency level |
| Monolith → microservices → multi-region | In architecture |
| Reproduce a stale read and a majority read | Lab |
| Wrong beliefs, a cheat sheet, every term defined | Misconceptions, Cheat sheet, Glossary |
Everything in one minute
The guarantees. Every row is unpacked in the guarantees section.
| Guarantee | In plain words | Tiny example of the violation | Typical way to get it |
|---|---|---|---|
| Strong (linearizable) | Every read sees the latest acknowledged write, for everyone | Ann saves, Bob reloads one second later and sees the old value | Read the leader/primary; DynamoDB ConsistentRead; Cosmos DB Strong; MongoDB "linearizable" |
| Eventual | If writes stop, all copies converge; no promise about when or about order | Like counter shows 41, then 40, then 42 | Async replicas; Cassandra ONE; DynamoDB default reads |
| Read-your-writes | I always see my own writes | You change your avatar and the next page shows the old one | Sticky routing; LSN/GTID fence; Cosmos DB Session |
| Monotonic reads | My reads never go back in time | A comment appears, then disappears on refresh | Pin a user to one replica; carry the max-seen position |
| Monotonic writes | My writes are applied in the order I made them | "set price 12" then "set price 10" end as 12 | Single leader; per-session ordering |
| Writes-follow-reads | A write I make after reading X is ordered after X everywhere | A reply is visible on a replica that does not yet have the question | Causal session; carry read position into the write |
| Consistent prefix | Readers see a prefix of the history, never gaps or reordering | "Yes!" appears before "Shall we have lunch?" | Single-log replication; Cosmos DB Consistent prefix |
| Causal | Cause before effect, for every reader | Bob sees Ann's reply to a post he cannot see yet | MongoDB causal sessions with "majority"; Cosmos DB Session covers one client |
| Bounded staleness | At most K versions or T seconds old | A dashboard 10 minutes behind during an incident | Cosmos DB Bounded staleness; CockroachDB with_max_staleness; MongoDB maxStalenessSeconds; Oracle STANDBY_MAX_DATA_DELAY |
The knobs, per product.
| Product | Default | Knob for stronger reads | Knob for cheaper/staler reads |
|---|---|---|---|
| PostgreSQL (streaming replicas) | Async replicas, primary reads are strong | synchronous_commit = remote_apply, LSN fence with pg_last_wal_replay_lsn() | Read from any hot standby |
| MySQL (binlog replicas) | Async replication | Semi-sync (durability only), WAIT_FOR_EXECUTED_GTID_SET, Group Replication group_replication_consistency | Read from any replica |
| Cassandra | Driver-defined (gocql: QUORUM) | QUORUM, LOCAL_QUORUM, EACH_QUORUM, ALL; SERIAL/LOCAL_SERIAL for LWT | ONE, LOCAL_ONE, ANY (writes only) |
| MongoDB | readConcern "local", { w: "majority" } for most deployments | "majority", "linearizable", causally consistent sessions | readPreference secondary + maxStalenessSeconds, "available" |
| DynamoDB | Eventually consistent reads | ConsistentRead: true (tables and LSIs only), MRSC global tables | Default reads (half the cost), GSIs, Streams |
| Azure Cosmos DB | Account-level default | Strong, Bounded staleness | Session, Consistent prefix, Eventual; override per request (weaker only) |
| CockroachDB | Serializable, reads from leaseholder | Default SELECT | AS OF SYSTEM TIME follower_read_timestamp(), with_max_staleness, with_min_timestamp |
The three things to do.
| Situation | Do this |
|---|---|
| A user just wrote and the next screen reads it | Route that read to the primary (time window or LSN/GTID/session-token fence); never to a random replica |
| A list, feed, count or report | Accept eventual (or bounded) staleness, label it in the UI, and keep it off the primary |
| Two writers may update the same item on different replicas | Do not rely on last-write-wins: use conditional writes (LWT, ConditionExpression), a single writer per key, or a CRDT/merge |
Why eventual consistency exists
A single database on a single machine has one copy, so "the latest value" is unambiguous. Databases add copies for three reasons: survive a machine or data-centre loss, serve more reads than one machine can, and serve readers close to where they are. The moment there are copies, a write reaches them at different times. The database can either wait for enough copies before answering (strong, slower, and unavailable when copies are unreachable), or answer now and let the copies catch up (fast and available, but a read can be stale). Vogels states the two reasons directly: inconsistency is tolerated for "improving read and write performance under highly concurrent conditions; and handling partition cases where a majority model would render part of the system unavailable even though the nodes are up and running."
| Weaker (eventual, session, bounded) | Stronger (linearizable, strict serializable) |
|---|---|
| Reads served by the nearest/any replica | Reads go to the leader, a quorum, or wait for replication |
| Writes acknowledged by one node or a local majority | Writes wait for remote replicas or a global majority |
| Stays available on both sides of a network partition | The minority side cannot serve (Jepsen: linearizability "cannot be totally or sticky available") |
| Bugs show up as stale or reordered data, silently | Bugs show up as latency, timeouts and unavailability, loudly |
| Cheap: DynamoDB eventual reads cost half; Cosmos DB weak reads use one replica | Expensive: Cosmos DB Strong across regions costs about two cross-region round trips per write |
The analogy we reuse on this page: a company notice board copied to branch offices. Head office pins a notice on its board, and a courier carries copies to each branch. Eventual consistency: every branch's board will eventually match head office, if head office stops posting. Read-your-writes: if you posted a notice, you only read the board in the office you posted in until the courier has delivered it. Monotonic reads: you always read the same branch's board, so you never see a notice and then later not see it. Causal: the courier never delivers a reply before the notice it replies to. Bounded staleness: the courier is never more than one hour or three notices behind. Strong: everyone phones head office before reading.
Three common misunderstandings, up front
- "Eventual consistency means the data will be right in a few milliseconds." The definition promises convergence if writes stop; it gives no time bound. Measured windows are usually small (Bailis et al. found Dynamo-style stores "frequently return consistent data within tens of milliseconds"), but a stuck replica, a long
VACUUMconflict or a network partition makes the window minutes or hours. Monitor lag; do not assume it. - "Only NoSQL is eventually consistent; my PostgreSQL is ACID." The moment you read from a PostgreSQL or MySQL async replica you are eventually consistent. Vogels: "Eventual consistency is not some esoteric property of extreme distributed systems."
- "Quorum reads and writes make Cassandra/Dynamo-style stores linearizable."
R+W>Nmakes the read and write sets overlap, but last-write-wins timestamps, partially failed writes and sloppy quorums still allow anomalies; Kleppmann's DDIA (secondary source, ch. 5) walks through the edge cases. For compare-and-set use Cassandra lightweight transactions or a consensus-based database.
Where the vocabulary comes from
1994, Bayou and session guarantees. Terry, Demers, Petersen, Spreitzer, Theimer and Welch at Xerox PARC built Bayou, a replicated store for mobile users who are only intermittently connected. They did not try to make replicas agree quickly; they gave each client session a view consistent with its own actions:
"Four per-session guarantees are proposed to aid users and applications of weakly consistent replicated data: Read Your Writes, Monotonic Reads, Writes Follow Reads, and Monotonic Writes." — Terry et al., Session Guarantees for Weakly Consistent Replicated Data, PDIS 1994
The paper also introduced the implementation every modern product copies: the client remembers what it wrote and read (a write-set and read-set, compacted into version vectors), and a server may serve the client only if it already has those writes. MongoDB's clusterTime, Cosmos DB's session token and a PostgreSQL LSN cookie are all this idea.
2007, Dynamo. Amazon's Dynamo paper (DeCandia et al., SOSP 2007) made the trade-off configurable per application: N replicas, R and W, a sloppy quorum with hinted handoff so the store stays "always writeable", vector clocks to detect conflicting versions, and Merkle-tree anti-entropy. It states the quorum rule: "Setting R and W such that R + W > N yields a quorum-like system." Cassandra descends from it; DynamoDB (the AWS service) shares the name but not the leaderless design.
2008/2009, Vogels. Werner Vogels' essay gave practitioners the vocabulary: strong, weak and eventual consistency, the inconsistency window, and the client-side variants (causal, read-your-writes, session, monotonic read, monotonic write), plus the N, W, R notation with the rule that "If W+R > N, then the write set and the read set always overlap and one can guarantee strong consistency." His Web-site rule is still the best UX heuristic: the inconsistency window "needs to be smaller than the time expected for the customer to return for the next page load."
2012, Probabilistically Bounded Staleness. Bailis, Venkataraman, Franklin, Hellerstein and Stoica (VLDB 2012) asked "how eventual is eventual consistency?" and "how consistent is eventual consistency?" and answered with two measurable quantities: t-visibility (probability a read t seconds after a write sees it) and k-staleness (probability a read returns one of the last k versions). Azure Cosmos DB exposes a PBS metric in its portal.
2016, Viotti & Vukolić; Jepsen. "Consistency in Non-Transactional Distributed Storage Systems" surveys "more than 50 different consistency notions" and orders them by strength (a partial order, not a line). Jepsen's consistency reference (jepsen.io/consistency) restates the models with availability classes (totally available, sticky available, unavailable) and is what Jepsen's database tests check against.
Strong, eventual, and the two meanings of "consistency" Must-know
In plain words: "strong" means a read anywhere behaves as if there were one copy; "eventual" means copies agree only after writes stop and propagation finishes.
Common misunderstanding: "Consistency here is the C in ACID." It is not. ACID's C is "the transaction keeps invariants (constraints) true"; isolation is about concurrent transactions on one primary. Replica consistency is about which version of the data a read returns when several copies exist. A PostgreSQL replica gives a perfectly isolated, snapshot-consistent view of an old state: isolated, but stale.
Definition: Strong consistency in database docs almost always means linearizability: "every operation appears to take place atomically, in some order, consistent with the real-time ordering of those operations" (Jepsen). Eventual consistency is a liveness property: if no new updates are made, all replicas eventually return the same last value. Convergence is the part that makes it useful: replicas that have seen the same set of updates hold the same state, which requires a deterministic conflict rule (LWW, merge, CRDT). Eventual consistency alone says nothing about what you read in the meantime; every other guarantee on this page restricts that.
| Property | Linearizable (strong) | Eventual |
|---|---|---|
| What a read returns | The latest completed write | Any value written earlier, including old ones |
| Real-time order | Respected | Not respected |
| Safety or liveness | Safety (nothing bad happens) | Liveness (something good eventually happens) |
| Availability during a partition | Not available on the minority side | Available everywhere |
| Typical cost | Leader or quorum round trip on every read | One local replica |
Isolation and replica consistency combine. Jepsen's strict serializable combines serializability and linearizability; Spanner calls it external consistency. A read-only transaction on a PostgreSQL standby is serializable-looking but not linearizable. Distributed SQL, Consensus & 2PC shows how consensus gives linearizable reads without a single primary.
The guarantees, one by one
Each block follows the same order: plain words, the usual wrong belief, the precise definition (Terry et al. 1994 and Jepsen wording), a timeline, real scenarios, which products give it, and how to get it. The client-centric guarantees (read-your-writes, monotonic reads, monotonic writes, writes-follow-reads) are promises to one session; causal and the stronger models are promises to everyone.
The picture orders the models the way Cosmos DB's documentation lists its levels and adds the product knobs under each. Treat it as a map, not a theorem: Viotti and Vukolić show the real relation is a partial order, and bounded staleness is not formally stronger than causal. The bottom axis is Jepsen's availability class: models on the left stay available on both sides of a partition, session and causal guarantees need the client to stick to one server, and linearizable reads stop on the minority side.
Read-your-writes Must-know
In plain words: after I change something, I see my change, even if other people do not yet.
Common misunderstanding: "The write returned OK, so any read afterwards sees it." With an async replica the commit returns before the replica replays it; the next request may land on the replica.
Definition: Terry et al.: the guarantee "ensures that the effects of any Writes made within a session are visible to Reads within that session." Jepsen notes it "does not apply to operations performed by different processes" and that it is sticky available: it survives partitions only if the client keeps talking to the same server.
Client (Ann) Primary (PostgreSQL) Replica (async, 300 ms behind)
1 POST /profile name='Sara' -> UPDATE users ...; COMMIT
2 <- 200 OK (WAL at 0/3000148)
3 GET /profile -----------------------------> SELECT name ... -> 'Sam' (replayed 0/3000060)
4 "My change was lost!" (presses Save again)
5 replays 0/3000148: 'Sara'Real scenarios: profile or settings page shows the old value after "Saved"; a new order is missing from "My orders" right after checkout; a user creates a project and the redirect to /projects/42 returns 404 from a replica; a password change that the next login request (read from a replica) does not see; a support agent edits a ticket and the list view shows the old status.
| Product | How you get read-your-writes |
|---|---|
| PostgreSQL | Read from primary; synchronous_commit = remote_apply with the replica in synchronous_standby_names; or LSN fence: pg_current_wal_lsn() after commit, pg_last_wal_replay_lsn() >= token on the replica |
| MySQL | Read from source; or remember the GTID of your write and SELECT WAIT_FOR_EXECUTED_GTID_SET(gtid, timeout) on the replica (0 = success, 1 = timeout); Group Replication AFTER/BEFORE |
| MongoDB | Causally consistent session with read concern "majority" and write concern "majority" (all four guarantees), or read from primary |
| Cassandra | W + R > RF (e.g. LOCAL_QUORUM writes and reads in the same DC) |
| DynamoDB | ConsistentRead: true on GetItem/Query/Scan of a table or LSI |
| Cosmos DB | Session (default choice for most apps): pass the session token |
| CockroachDB | Default reads (leaseholder); with follower reads use with_min_timestamp(<commit time>) |
| Laravel | 'sticky' => true (same request), PreventStaleDatabaseReads middleware (2 s window by default, across requests), usingWritePdo, onWriteConnection() |
Fix: route by position (LSN, GTID, cluster time, session token) when you can, by time window when you cannot, and to the primary as the fallback. Code in read-after-write.
Monotonic reads Must-know
In plain words: once I have seen a value, I never see an older one afterwards.
Common misunderstanding: "If every replica is only a little behind, it does not matter which one I read." Two replicas with different lag make a user's reads jump backwards: data appears, then disappears.
Definition: Terry et al.: "Read operations are made only to database copies containing all Writes whose effects were seen by previous Reads within the session." Jepsen: "intuitively, reads cannot go backwards." It is totally available (any node can serve some read) but the client must choose a fresh-enough node.
Client (Bob) Replica A (lag 0.1 s) Replica B (lag 5 s)
1 GET /posts/9/comments ------------> 12 comments
2 GET /posts/9/comments (load balancer picks B) ----------------> 10 comments <- two vanished
3 "The moderator deleted my comment?" (opens a support ticket)Real scenarios: a comment count goes 12 → 10 → 12 on refresh; an order status goes SHIPPED → PAID → SHIPPED; a pagination cursor built on page 1 from replica A finds missing rows on page 2 from replica B; an admin deletes a user, sees it gone, refreshes and sees it back.
| Product | How you get monotonic reads |
|---|---|
| PostgreSQL / MySQL replicas | Pin a session to one replica (hash of user id); or carry the max LSN/GTID seen and require replicas to be at least there |
| MongoDB | Causal session with "majority" read concern (monotonic reads hold even with { w: 1 } writes per MongoDB's table) |
| Cassandra | Quorum reads with read_repair = 'BLOCKING' (the default), which gives "monotonic quorum reads" |
| Cosmos DB | Session and stronger |
| DynamoDB | Strongly consistent reads; eventual reads may go backwards |
Fix: sticky replica per user, or a position token that only moves forward (store max(seen) per session). See monotonic reads across replicas.
Monotonic writes Important
In plain words: my writes are applied everywhere in the order I made them.
Common misunderstanding: "My code awaits each write before the next, so order is guaranteed." Not when two writes go to two different coordinators or leaders, or when order is decided by timestamps from clocks that disagree.
Definition: Terry et al.: "a Write is only incorporated into a server's database copy if the copy includes all previous session Writes." Jepsen restates it: if one process writes w1 and then w2, every process observes w1 before w2.
Client Node X (clock correct) Node Y (clock 2 s behind)
1 UPDATE price = 12 -----> ts = 10:00:05.000
2 UPDATE price = 10 ------------------------------------> ts = 10:00:03.500 (coordinated by Y)
3 LWW keeps the larger timestamp everywhere: price = 12 <- the second write lostReal scenarios: a document editor sends version N then N+1 through different gateways; an inventory correction followed by a sale applied in the reverse order; Cassandra updates from one client coordinated by nodes with skewed clocks (Cassandra docs: "Cassandra’s correctness does depend on these clocks").
| Product | Monotonic writes |
|---|---|
| Single-leader (PostgreSQL, MySQL, MongoDB primary) | Yes, while the leader does not change; a failover with lost async writes can break it |
| MongoDB causal session | With { w: "majority" } writes, yes |
| Cassandra | Use client-side timestamps (driver default in modern drivers) and NTP; or LWT for the critical path |
| Cosmos DB | Session and stronger |
Fix: one writer per key (single leader), client-supplied monotonic timestamps or version numbers, conditional writes (IF version = ?).
Writes-follow-reads Important
In plain words: if I read something and then write because of it, nobody sees my write without what I read.
Common misunderstanding: "That is the database's problem, not mine." In multi-leader or leaderless stores and in caches it is yours: the reply can replicate faster than the question.
Definition: Terry et al.: "in every copy of the database, Writes made during the session are ordered after any Writes whose effects were seen by previous Reads in the session." Jepsen calls it session causality: "Once you’ve read something, you can’t change that read’s past."
Ann Region EU Region US
1 posts "Shall we lunch?" stored
2 Bob (EU) reads it, replies "Yes!" stored after the question
3 replicates reply first -------> "Yes!" <- question not yet here
4 replicates question -------> "Shall we lunch?"
5 Carol (US) between 3 and 4 sees an answer to nothingReal scenarios: a reply visible before its parent post; an "approved" flag on a document that, on another replica, does not exist yet; a refund row replicated before its payment row, making a reconciliation job flag fraud.
| Product | Writes-follow-reads |
|---|---|
| Single primary + replicas replaying one log | Yes on every replica (log order), once the replica has both |
| MongoDB causal session | Yes with "majority" reads (also with { w: 1 } writes per MongoDB's table) |
| Cosmos DB Session | Yes: "within a single client session, reads are guaranteed to honor the read-your-writes, and write-follows-reads guarantees." |
| Cassandra, multi-leader setups | No; design the schema so the dependent row carries what it depends on |
Fix: keep causally related writes on one leader or one partition; send the read position with the write; or embed the parent in the child (denormalise the question text into the reply event).
Consistent prefix Good to know
In plain words: you may be behind, but what you see is the history up to some point, in order, with nothing skipped.
Common misunderstanding: "Behind is behind; order does not matter." A replica that applies a later transaction before an earlier one shows states that never existed.
Definition: reads observe a prefix of the global write order. Cosmos DB's version: writes in a transaction are seen together, and a reader sees "Doc1 v1 and Doc2 v1" or "Doc1 v2 and Doc2 v2", never a mix. A PostgreSQL physical standby or a MySQL replica applying the binlog in commit order gives this naturally; partitioned stores (one log per partition) give it only per partition.
Writer: T1 = {question}, T2 = {answer} (T1 committed before T2)
Partition 1 holds questions (lag 4 s) Partition 2 holds answers (lag 0 s)
1 Reader queries both partitions at t=2 s
2 sees the answer from P2, not the question from P1 -> prefix violated across partitionsReal scenarios: a chat across shards shows answers before questions; a ledger replica shows a debit without its credit leg (if the two legs are in different partitions); a Kafka-fed read model with one consumer per partition.
Fix: keep related writes in one transaction and one partition; or read through one log; or use a store that orders across partitions (Cosmos DB Consistent prefix and stronger, distributed SQL).
Causal consistency Important
In plain words: if one write could have influenced another, everybody sees them in that order; unrelated writes may appear in any order.
Common misunderstanding: "Read-your-writes plus monotonic reads is causal." Those are per-client. Causal consistency also covers chains across clients: Ann writes, Bob reads it and writes, Carol must not see Bob's write without Ann's.
Definition: Jepsen: "Causal consistency captures the notion that causally-related operations should appear in the same order on all processes—though processes may disagree about the order of causally independent operations." It is the strongest model that stays sticky available during partitions. Vogels' informal version: if A told B it updated an item, B's next read returns the update.
Ann Bob Carol
1 w1: post "lunch?"
2 reads w1
3 w2: reply "yes" (w1 -> w2 causally)
4 reads: may see nothing, or "lunch?",
or "lunch?" + "yes", but never "yes" aloneReal scenarios: comment threads; access control ("remove Bob from the album" then "upload private photo": Bob must not see the photo with the old ACL); a payment status page that a webhook consumer reads after the payment service wrote.
| Product | Causal |
|---|---|
| MongoDB causally consistent sessions | All four session guarantees, durably, only with read concern "majority" + write concern "majority"; "local" + { w: 1 } guarantees none of them |
| Cosmos DB Session | Session guarantees for one client (share the token to extend) |
| CockroachDB | with_min_timestamp(ts) enforces "causality between an operation at some point in time and any dependent reads" |
| PostgreSQL | remote_apply: "In simple cases, this allows for load balancing with causal consistency." |
Fix: pass the causal token across hops (MongoDB clusterTime + operationTime, a PostgreSQL LSN, a CockroachDB commit timestamp). Code in causal across services.
Bounded staleness Important
In plain words: you accept old data, but never older than a limit you choose: K versions or T seconds.
Common misunderstanding: "Bounded staleness is a time-to-live on a cache." It is enforced by the database: either reads refuse (or redirect) when a replica is too far behind, or writes slow down until replicas catch up.
Definition: Cosmos DB: "the lag of data between any two regions is always less than a specified amount", in versions (K) or time (T), whichever is reached first; when a region exceeds it, "writes for that partition are throttled until staleness is back within the configured upper bound." Other products bound staleness on the read side.
Primary commits at 12:00:00, 12:00:05, 12:00:10 ... Standby replay lag grows to 40 s
1 Session: ALTER SESSION SET STANDBY_MAX_DATA_DELAY = 30; -- Oracle Active Data Guard
2 SELECT ... on the standby -> ORA-3172 (apply lag too large)
3 application falls back to the primary, or shows "data delayed" bannerReal scenarios: analytics or search pages that may be minutes old but not hours; a mobile app's offline cache refreshed if older than T; multi-region catalog reads; a fraud model reading features with a freshness SLO.
| Product | Bounded staleness knob | What happens at the bound |
|---|---|---|
| Azure Cosmos DB | Account level: Bounded staleness (K, T) | Writes on the lagging partition are throttled |
| CockroachDB | AS OF SYSTEM TIME with_max_staleness('10s') (single statement) | Reads at the freshest local timestamp within the bound, or error with nearest_only |
| Spanner | Read-only transaction timestamp bound: bounded staleness | Picks a timestamp within the bound; docs suggest at least 10 s staleness for the benefit |
| MongoDB | readPreference with maxStalenessSeconds (minimum 90) | Driver stops choosing that secondary |
| Oracle Active Data Guard | ALTER SESSION SET STANDBY_MAX_DATA_DELAY = n (0 = same result as primary) | ORA-3172 |
| PostgreSQL / MySQL | No built-in; check pg_last_xact_replay_timestamp() / replica lag before routing | Your router decides |
Fix: state the bound in the requirement ("search may be 60 s old"), enforce it in routing, and alert on lag above it.
Probabilistically bounded staleness (PBS) Good to know
In plain words: instead of a guarantee, a measurement: "99.9% of reads 100 ms after a write see it."
Common misunderstanding: "Eventual means unpredictable." PBS shows it is predictable from latency distributions; it just is not guaranteed.
Definition: Bailis et al. define k-staleness (probability of returning one of the last k versions) and t-visibility (probability a read t seconds after a write commits sees it), and model Dynamo-style read/write paths as WARS (write send, ack, read send, read response latencies). Cosmos DB: the PBS metric "shows how eventual your eventual consistency is."
Real scenario: choosing between LOCAL_ONE and LOCAL_QUORUM for a feed: measure t-visibility in your cluster; if 99.99% of reads after 50 ms are fresh and the UI cannot reload faster than 500 ms, LOCAL_ONE is fine.
Fix: measure it yourself (the lab's stalereads program is a PBS t-visibility probe for PostgreSQL), and alert on replica lag percentiles, not averages.
Strong consistency (linearizable reads) Must-know
In plain words: behaves like one copy: once any client has seen a write, every later read by anyone sees it.
Common misunderstanding: "Strong means durable." Durability (survives crashes) is separate. MongoDB { w: 1 } on the primary plus "local" reads on the primary is read-your-writes for that client, yet the write can still roll back after failover; "majority" covers that.
Definition: linearizability, per object. Jepsen: "Linearizability is a single-object model, but the scope of “an object” varies." Across objects with transactions you need strict serializability.
Client A Leader Client B
1 write x=2 ---------------------> commit, ack
2 read x (starts after 1 finished)
3 must return 2 (a replica returning 1 violates linearizability)Real scenarios: uniqueness checks (usernames), balances before a debit, leader election and locks, idempotency-key lookups, inventory of the last item, "is this coupon already used?".
| Product | Linearizable read |
|---|---|
| PostgreSQL / MySQL | Read on the primary (not across failover with async replicas) |
| MongoDB | Read concern "linearizable" (single-document reads; may wait for majority) |
| DynamoDB | ConsistentRead: true; MRSC global tables for any Region |
| Cosmos DB | Strong ("offers a linearizability guarantee") |
| Cassandra | Lightweight transactions (IF ...) with SERIAL/LOCAL_SERIAL |
| CockroachDB, Spanner | Default reads |
| Redis | Primary reads only; WAIT adds replication acks but "WAIT does not make Redis a strongly consistent store" |
Fix: reserve strong reads for the decisions that need them; express the decision as a conditional write when possible (the write itself is then the check).
What each product really offers
| Product | Replication model | Default read | Strongest read | Staleness bound | Conflict handling |
|---|---|---|---|---|---|
| PostgreSQL | Single primary, physical streaming (async by default) | Wherever you connect | Primary; remote_apply makes sync standbys read-your-writes | None built in (recovery_min_apply_delay adds delay) | None needed (one writer) |
| MySQL / InnoDB | Single source, binlog replication (async default), semi-sync plugin, Group Replication | Wherever you connect | Source; GTID wait; GR BEFORE/AFTER | None built in | One writer (GR multi-primary: certification) |
| SQL Server | Always On availability groups, readable secondaries (sync or async commit) | Wherever you connect (read-only routing can send read-intent connections to secondaries) | Primary | None; "data latency between a primary database and the corresponding secondary database is only a few seconds" in many circumstances | One writer |
| Oracle | Data Guard; Active Data Guard real-time query | Wherever you connect | Primary; STANDBY_MAX_DATA_DELAY = 0 / ALTER SESSION SYNC WITH PRIMARY | STANDBY_MAX_DATA_DELAY (ORA-3172) | One writer |
| SQLite | One file; Litestream ships the WAL asynchronously | Local file | Local file on the writer | None | One writer |
| Redis | Async primary → replica | Wherever you connect | Primary | None; WAIT numreplicas timeout for acks | Last write on primary |
| MongoDB | Replica set: elected primary + secondaries | Primary, read concern "local" | "linearizable"; causal sessions with "majority" | maxStalenessSeconds (≥ 90) | Single primary; rollback of non-majority writes after failover |
| Cassandra / ScyllaDB | Leaderless, RF copies, coordinator per request | Per query CL (driver default) | ALL/QUORUM; LWT SERIAL | None; hints window max_hint_window (3 h default) | Per-cell last-write-wins by timestamp |
| DynamoDB | Managed; global tables across Regions | Eventually consistent | ConsistentRead; MRSC global tables | None | MREC global tables: "last writer wins" |
| Azure Cosmos DB | Managed, four-replica set per region, multi-region | Account default | Strong | Bounded staleness (K, T) | "Last Write Wins is the default conflict resolution policy"; custom for API for NoSQL |
| CockroachDB | Raft per range, leaseholder reads | Serializable leaseholder reads | Default | with_max_staleness, follower_read_timestamp() | Serializable (no conflicts to merge) |
| Spanner | Paxos per split, TrueTime | Strong | Strong (external consistency) | Bounded / exact staleness read-only transactions | Serializable |
PostgreSQL: async standbys, synchronous_commit, remote_apply Must-know
Streaming replication is asynchronous unless synchronous_standby_names lists standbys. synchronous_commit decides what a commit waits for: off, local, remote_write (standby OS has it), on (standby flushed it; the default), remote_apply. Only remote_apply touches visibility: "commits will wait until replies from the current synchronous standby(s) indicate they have received the commit record of the transaction and applied it, so that it has become visible to queries on the standby(s)". The manual warns it causes "much larger commit delays", and it can be set per transaction (SET LOCAL synchronous_commit = remote_apply) so only the writes that the next screen reads pay for it. With ANY 2 (s1, s2, s3) only two of three standbys are guaranteed to have applied, so a read on the third is still stale: route reads only to standbys you waited for, or use an LSN fence.
-- Primary: how far behind is each standby? (replay_lag ~ "delay before recent transactions became visible")
SELECT application_name, state, sync_state, replay_lsn, replay_lag
FROM pg_stat_replication;
-- After a write on the primary: the token
SELECT pg_current_wal_lsn(); -- e.g. 0/3000148
-- On a standby: has it replayed my write? how old is it?
SELECT pg_last_wal_replay_lsn() >= '0/3000148'::pg_lsn AS caught_up,
now() - pg_last_xact_replay_timestamp() AS approx_age;
-- Only this transaction waits for the sync standby to apply
BEGIN;
SET LOCAL synchronous_commit = remote_apply;
UPDATE users SET display_name = 'Sara' WHERE id = 7;
COMMIT;Related standby knobs: max_standby_streaming_delay (default 30 s) caps how long replay waits for conflicting standby queries, which directly raises lag; hot_standby_feedback avoids cancellations at the cost of bloat on the primary; recovery_min_apply_delay deliberately delays replay (useful for the lab and for "undo" standbys).
MySQL: async, semi-sync, GTID waits, Group Replication Important
"MySQL replication by default is asynchronous." Semi-sync (rpl_semi_sync_source_enabled, plugin) makes the source wait until at least rpl_semi_sync_source_wait_for_replica_count replicas have received and logged the transaction; it "requires only an acknowledgement from the replicas, not that the events have been fully executed and committed on the replica side". So semi-sync is a durability tool, not a read-your-writes tool. The wait point rpl_semi_sync_source_wait_point is AFTER_SYNC (default; all clients see the transaction only after the ack) or AFTER_COMMIT. On timeout (rpl_semi_sync_source_timeout) "the source reverts to asynchronous replication", silently weakening the guarantee.
For read-your-writes, capture the GTID set after your commit (for example @@GLOBAL.gtid_executed on the source) and on the replica run SELECT WAIT_FOR_EXECUTED_GTID_SET('uuid:1-123', 0.05); which returns 0 when applied and 1 on timeout. Group Replication has group_replication_consistency: EVENTUAL (default before the variable existed), BEFORE_ON_PRIMARY_FAILOVER, BEFORE (a read waits for preceding transactions), AFTER (a write waits until applied on all members), BEFORE_AND_AFTER.
Cassandra: consistency levels per request Must-know
Cassandra "supports a per-operation tradeoff between consistency and availability through Consistency Levels": ONE, TWO, THREE, QUORUM (majority of RF), ALL, LOCAL_QUORUM, EACH_QUORUM, LOCAL_ONE, ANY (writes only; may be satisfied by a stored hint). Writes always go to every replica; "The consistency level simply controls how many responses the coordinator waits for before responding to the client." The rule is Dynamo's: choose W and R with W + R > RF. LOCAL_QUORUM gives a weaker but common promise: "reads are guaranteed to see the latest write from within the same datacenter." Lightweight transactions (INSERT ... IF NOT EXISTS, UPDATE ... IF col = ?) run Paxos at the serial consistency SERIAL or LOCAL_SERIAL. Deep dive: Cassandra & ScyllaDB.
-- cqlsh
CONSISTENCY LOCAL_QUORUM;
SELECT qty FROM shop.carts WHERE id = 6c5e... AND item = 'book-42';
SERIAL CONSISTENCY LOCAL_SERIAL;
UPDATE shop.stock SET qty = 0 WHERE sku = 'book-42' IF qty = 1;MongoDB: read concern, write concern, read preference, causal sessions Must-know
Three independent dials. Read concern (what a read may return): "local" (default) "returns data from the instance with no guarantee that the data has been written to a majority of the replica set members (i.e. may be rolled back)"; "available" (lowest latency on sharded clusters, may return orphaned documents); "majority" "guarantees that the data read has been acknowledged by a majority of the replica set members"; "linearizable" (waits for concurrent majority writes, single document); "snapshot" (transactions and snapshot reads). Write concern (what an ack means): { w: 1 }, { w: "majority" } ("the default write concern for most MongoDB deployments"), j: true, wtimeout. Read preference (which member): primary, primaryPreferred, secondary, secondaryPreferred, nearest, plus maxStalenessSeconds ("90 seconds or longer"). Causally consistent sessions attach afterClusterTime to every read so the chosen member waits until it has the session's writes.
| Session read concern + write concern | Read own writes | Monotonic reads | Monotonic writes | Writes follow reads |
|---|---|---|---|---|
"majority" + "majority" | Yes | Yes | Yes | Yes |
"majority" + { w: 1 } (durable view) | No | Yes | No | Yes |
"local" + "majority" | No | No | Yes | No |
"local" + { w: 1 } | No | No | No | No |
Source: MongoDB manual, Causal Consistency and Read and Write Concerns (the table, with the note that weaker combinations may hold "in some situations, but not necessarily in all situations"). Deep dive: MongoDB in Depth.
DynamoDB: ConsistentRead and global tables Must-know
"Eventually consistent is the default read consistent model for all read operations." GetItem, Query, Scan and BatchGetItem accept ConsistentRead; when true, DynamoDB "returns a response with the most up-to-date data, reflecting the updates from all prior write operations that were successful". Costs: "Eventually consistent reads are half the cost of strongly consistent reads." Limits: "Strongly consistent reads from a global secondary index or a DynamoDB stream are not supported" (a GSI query with ConsistentRead fails with a ValidationException). Global tables: MREC (default) replicates "typically within a second" and resolves concurrent writes with "last writer wins"; MRSC replicates synchronously and needs exactly three Regions (three replicas or two plus a witness). Comparison with Cassandra: Wide-Column & Key-Value at Scale.
Azure Cosmos DB: five levels Important
"From strongest to weakest, the levels are": Strong, Bounded staleness, Session, Consistent prefix, Eventual. The account default applies to every read; a request or SDK client can override it, but only towards weaker reads ("Overriding the default consistency level applies only to reads within the SDK client"). Strong and Bounded staleness read from two of four replicas (a "minority quorum"), so reads cost twice the RUs of the single-replica levels. Session uses a partition-bound session token returned after each write; if the client has not written to a physical partition, its reads there "behave as reads with Eventual Consistency." Eventual: "a client might read values older than those values it read in the past" (no monotonic reads). Multi-region Strong costs roughly two times the RTT between the two farthest regions per write.
CockroachDB: follower reads and bounded staleness Good to know
Reads normally go to the range's leaseholder (linearizable, serializable). "A stale follower read is a historical read taken from the nearest replica." Two kinds: exact staleness (AS OF SYSTEM TIME follower_read_timestamp(), also via SET TRANSACTION AS OF SYSTEM TIME ... or default_transaction_use_follower_reads = on) and bounded staleness (with_max_staleness('10s'), with_min_timestamp(ts), single-statement, optional nearest_only that errors instead of going remote). Global tables give strong reads from every region at the price of slower writes. Docs: "You should use stale follower reads only when your application can tolerate reading stale data". Consensus background: Distributed SQL, Consensus & 2PC.
-- CockroachDB
SELECT price FROM products AS OF SYSTEM TIME with_max_staleness('10s') WHERE id = 42;
SELECT price FROM products AS OF SYSTEM TIME with_min_timestamp('2026-11-25 10:00:05+00') WHERE id = 42;
SELECT now() - follower_read_timestamp(); -- how stale exact-staleness reads are right nowMechanics
Quorums: N, R, W and R+W>N Must-know
In plain words: if every write is acknowledged by W of the N copies and every read asks R copies, and R + W > N, at least one copy you read has the latest acknowledged write.
Common misunderstanding: "Higher W is always safer." W = N makes every write fail when any one replica is down (Vogels: "With N=3 and W=3 and only two nodes available, the system will have to fail the write.").
Definition: Vogels: "If W+R > N, then the write set and the read set always overlap"; "Weak/eventual consistency arises when W+R <= N". Common choices: N=3, W=2, R=2 (Dynamo's typical (3,2,2)); R=1, W=N for read-heavy; W=1, R=N for write-heavy. The coordinator reads R copies and returns the version with the newest timestamp (Cassandra) or all causally unrelated versions (Dynamo).
| N, W, R | Overlap? | Tolerates down for writes / reads | Typical use |
|---|---|---|---|
3, 2, 2 (QUORUM/QUORUM) | Yes | 1 / 1 | Default "strong-ish" Cassandra |
3, 1, 1 (ONE/ONE) | No | 2 / 2 | Metrics, feeds, caches |
3, 3, 1 (ALL/ONE) | Yes | 0 / 2 | Rare writes, many reads |
3, 1, 3 (ONE/ALL) | Yes | 2 / 0 | Write-heavy, rare critical reads |
2 DCs × 3, LOCAL_QUORUM both | Within a DC | 1 per DC | Multi-DC apps homed to one DC |
2 DCs × 3, EACH_QUORUM writes + LOCAL_QUORUM reads | Yes, everywhere | 1 per DC, both DCs up for writes | Cross-DC read-your-writes |
Why overlap is not linearizability: a write that reached only one replica before failing is "not acknowledged" yet can be returned by a later read and then vanish; concurrent writes are ordered by timestamps, not real time; read repair may not have finished between two readers. That is why Cassandra adds blocking read repair for "monotonic quorum reads" and LWT for compare-and-set.
Sloppy quorums and hinted handoff Important
In plain words: when a replica that should take the write is down, another node takes it with a note ("hint") saying where it belongs, and hands it over later.
Common misunderstanding: "A quorum write landed, so a quorum read will see it." With a sloppy quorum the W nodes that acked may not be among the R nodes you read.
Definition: Dynamo: "all read and write operations are performed on the first N healthy nodes from the preference list, which may not always be the first N nodes encountered while walking the consistent hashing ring." The stand-in keeps the hinted replica "in a separate local database that is scanned periodically" and delivers it when the owner recovers. Cassandra keeps hints for max_hint_window (3 hours by default, nodetool setmaxhintwindow); a node down longer needs repair. ANY accepts a write that only a hint holds: no replica has it yet.
Preference list for key k: A, B, C (D is next on the ring)
1 A is down. Write k=v2 with W=2 -> B acks, D acks (hint: "belongs to A")
2 Read k with R=2 from A (back up, still v1) and C (v1) -> returns v1 although W+R>N
3 D hands v2 to A -> later reads see v2Real scenarios: writes stay available during a rack outage (the point of Dynamo's shopping cart); stale reads right after a node returns; data loss if the hint-holder dies before handoff. See Consistent Hashing for the ring.
Read repair and anti-entropy (pointer) Good to know
Three convergence paths, from cheap to thorough. Hinted handoff on the write path; read repair on the read path: the coordinator notices mismatched replicas and writes the newest version back (Cassandra's table option read_repair = 'BLOCKING' waits for that repair, 'NONE' skips it and loses monotonic quorum reads); anti-entropy repair: replicas compare Merkle trees and stream differing ranges (nodetool repair, full, sub-range or incremental). Cassandra: hints and read repair are "only best-effort", and "to guarantee eventual consistency Cassandra implements anti-entropy repair". Tombstones must be repaired before gc_grace_seconds or deleted data resurrects. Mechanism in depth: Merkle Trees, Read Repair & Anti-Entropy.
Conflicts and last-write-wins (LWW) Must-know
In plain words: when two copies accepted different writes for the same item, the one with the larger timestamp wins and the other is thrown away, without an error.
Common misunderstanding: "LWW keeps the latest write." It keeps the write with the largest timestamp; with clock skew that can be the older write, and concurrent writes lose data by design.
Definition: Cassandra: "Updates resolve according to the conflict resolution rule of last write wins", per column, with timestamps from the client or the coordinator. Dynamo used LWW for session data and application merge for the shopping cart. DynamoDB MREC global tables and Cosmos DB multi-write default to last-writer-wins.
Client 1 (EU) Client 2 (US)
1 read cart = [book] read cart = [book]
2 write cart = [book, pen] ts=100
3 write cart = [book, mug] ts=101
4 after replication, everywhere: [book, mug] <- pen silently lost| Strategy | Who uses it | Loses data? | Use when |
|---|---|---|---|
| Last-write-wins (timestamp) | Cassandra, DynamoDB global tables (MREC), Cosmos DB (default policy) | Yes, concurrent writes | Whole-value overwrites where the latest intent wins (session blobs, profile fields) |
| Per-column LWW | Cassandra | Only on the same column | Different fields updated concurrently |
| Siblings + application merge | Dynamo | No | Carts, sets; app merges |
| CRDT (counters, sets, maps) | Libraries and stores built on CRDTs; Cassandra collections merge per element | No (by construction) | Counters, likes, membership |
| Conditional write / consensus | Cassandra LWT, DynamoDB ConditionExpression, MongoDB primary, distributed SQL | No (one writer wins, other fails) | Money, stock, uniqueness |
Mechanism of merging: CRDTs.
Version vectors and vector clocks (pointer) Good to know
A version vector is a list of (replica, counter) pairs; comparing two tells you whether one version descends from the other or they are concurrent. Bayou used them to implement session guarantees (a session's reads and writes compact into "two version vectors"); Dynamo uses vector clocks "to capture causality between different versions of the same object" and returns concurrent versions as siblings for the client to reconcile. LWW throws that information away. Details: Vector Clocks & Causality.
Session tokens: how products implement session guarantees Important
| Product | Token | Where you get it | How a replica uses it |
|---|---|---|---|
| PostgreSQL | WAL LSN (pg_lsn) | pg_current_wal_lsn() after commit | Serve if pg_last_wal_replay_lsn() >= token |
| MySQL | GTID set | @@GLOBAL.gtid_executed on the source after commit | WAIT_FOR_EXECUTED_GTID_SET(set, timeout) |
| MongoDB | operationTime + $clusterTime | session.OperationTime(), ClusterTime() | Read carries afterClusterTime; member waits |
| Cosmos DB | Session token (per partition) | Response header after each write | Replica serves if it has that token or newer |
| CockroachDB | Commit timestamp | cluster_logical_timestamp() in the transaction | with_min_timestamp(ts) |
| Laravel | Last-write time in the HTTP session | PreventStaleDatabaseReads | Reads use the write connection for N seconds |
Bayou's trick also applies: if the client "latches on" to one server, the checks can be skipped; that is what sticky routing is.
Every knob on one page Must-know
| Product | Knob | Values | Scope |
|---|---|---|---|
| PostgreSQL | synchronous_commit | off, local, remote_write, on, remote_apply | Server, session, SET LOCAL per transaction |
| PostgreSQL | synchronous_standby_names | FIRST n (...), ANY n (...) | Server |
| PostgreSQL | max_standby_streaming_delay, hot_standby_feedback, recovery_min_apply_delay | Duration / bool / duration | Standby |
| MySQL | rpl_semi_sync_source_enabled, ..._wait_for_replica_count, ..._timeout, ..._wait_point | bool, n, ms, AFTER_SYNC/AFTER_COMMIT | Source |
| MySQL | group_replication_consistency | EVENTUAL, BEFORE_ON_PRIMARY_FAILOVER, BEFORE, AFTER, BEFORE_AND_AFTER | Global or session |
| Cassandra | Consistency level; serial consistency; read_repair | ONE ... ALL; SERIAL/LOCAL_SERIAL; BLOCKING/NONE | Per query; per table |
| MongoDB | readConcern, writeConcern, readPreference, maxStalenessSeconds, causalConsistency | see above | Client, database, collection, operation, session |
| DynamoDB | ConsistentRead | true/false | Per request |
| Cosmos DB | Default consistency; request override | Five levels | Account; request (weaker only) |
| CockroachDB | AS OF SYSTEM TIME, default_transaction_use_follower_reads | timestamp functions; on/off | Statement, transaction, session |
| Oracle ADG | STANDBY_MAX_DATA_DELAY | NONE, 0, seconds | Session |
| Redis | WAIT numreplicas timeout | ints | Per connection, after writes |
Errors you will see Important
| Product | Error | Meaning | Retry? |
|---|---|---|---|
| Cassandra | UnavailableException (gocql RequestErrUnavailable) | Coordinator knows too few replicas are alive for the CL | Retry later or lower CL deliberately; do not auto-downgrade money paths |
| Cassandra | WriteTimeoutException / ReadTimeoutException | Replicas did not answer in time; a write may still have applied | Only idempotent statements |
| MongoDB | Write concern error with wtimeout | Not replicated to the majority in time; "the data eventually replicates or rolls back" | Check, then retry idempotently |
| MongoDB | maxStalenessSeconds below 90 | Rejected by the driver/server | Fix config |
| DynamoDB | ValidationException on a GSI with ConsistentRead | Strong reads unsupported on GSIs | No; read the base table |
| Oracle ADG | ORA-3172 | Apply lag above STANDBY_MAX_DATA_DELAY | Fall back to primary |
| MySQL | WAIT_FOR_EXECUTED_GTID_SET returns 1 | Timeout waiting for the GTID | Fall back to source |
| PostgreSQL standby | Query canceled due to a recovery conflict | Replay needed to remove rows your snapshot sees | "Canceled queries may be retried immediately" |
| CockroachDB | Error from a bounded-staleness read with nearest_only | No local replica can serve within the bound | Drop nearest_only or relax the bound |
Solving the classic problems
The Go snippets live in one module (docs/snippets/database/eventual-consistency-databases/go), each directory its own main that exits cleanly when its environment variables are missing. The Laravel snippets use Laravel 13 APIs documented on the Database page (sticky, PreventStaleDatabaseReads, usingWritePdo, withoutAffectingStickiness) plus mongodb/laravel-mongodb and aws/aws-sdk-php.
Read-after-write: the profile that "did not save"
| Solution | How | Advantage | Cost / limitation |
|---|---|---|---|
| Read from primary always | No replicas for this table | Simple, strong | Primary carries all reads |
| Sticky per request | Laravel 'sticky' => true | One config line | Only the same request; the redirect after POST is a new request |
| Time window per session | Laravel PreventStaleDatabaseReads::for(5); custom cookie in Go | Covers the redirect and the next pages | Guess: lag above the window still leaks; window too long loads the primary |
| Position fence (LSN / GTID / cluster time) | Store token after write; replica serves only if caught up | Exact; replicas used whenever fresh | Needs a token store (cookie/session) and a check per read |
remote_apply / GR AFTER | Commit waits for replica apply | Readers need nothing special | Every such write pays replay latency; a slow standby slows commits |
-- PostgreSQL position fence (the queries the Go and Laravel code run)
SELECT pg_current_wal_lsn()::text; -- primary, after COMMIT
SELECT pg_last_wal_replay_lsn() >= $1::pg_lsn; -- replica, before reading
-- MySQL equivalent
SELECT WAIT_FOR_EXECUTED_GTID_SET('3E11FA47-71CA-11E1-9E33-C80AA9429562:1-5', 0.05);Go: LSN-fenced router. Writes return a token, the handler puts it in a short-lived cookie, reads use the replica only when it has replayed the token, waiting up to 50 ms before falling back to the primary.
// Read-your-writes routing for PostgreSQL primary + streaming replicas.
//
// After a write, the router remembers the primary's WAL position (LSN) and
// hands it to the client as a token (here: a cookie). A later read goes to the
// replica only if the replica has replayed at least that LSN; otherwise it
// falls back to the primary. Clients that never wrote read from the replica.
package main
import (
"context"
"database/sql"
"errors"
"fmt"
"log"
"net/http"
"os"
"time"
_ "github.com/jackc/pgx/v5/stdlib"
)
const lsnCookie = "min_lsn"
// Router sends writes to the primary and reads to a replica that is fresh enough.
type Router struct {
Primary *sql.DB
Replica *sql.DB
// MaxWait is how long a read may wait for the replica to catch up
// before falling back to the primary.
MaxWait time.Duration
}
// Write runs fn in a transaction on the primary and returns the LSN token
// the caller must present on its next read.
func (r *Router) Write(ctx context.Context, fn func(*sql.Tx) error) (string, error) {
tx, err := r.Primary.BeginTx(ctx, nil)
if err != nil {
return "", err
}
if err := fn(tx); err != nil {
_ = tx.Rollback()
return "", err
}
if err := tx.Commit(); err != nil {
return "", err
}
// Read after COMMIT: the current WAL position is >= our commit record.
var lsn string
err = r.Primary.QueryRowContext(ctx, `SELECT pg_current_wal_lsn()::text`).Scan(&lsn)
return lsn, err
}
// ReadDB returns the pool that can serve a read for a client holding token.
func (r *Router) ReadDB(ctx context.Context, token string) *sql.DB {
if token == "" {
return r.Replica // this client never wrote: any replica will do
}
deadline := time.Now().Add(r.MaxWait)
for {
var caughtUp sql.NullBool
err := r.Replica.QueryRowContext(ctx,
`SELECT pg_last_wal_replay_lsn() >= $1::pg_lsn`, token).Scan(&caughtUp)
if err == nil && caughtUp.Valid && caughtUp.Bool {
return r.Replica
}
if err != nil || time.Now().After(deadline) {
return r.Primary // replica down or too far behind: pay the primary
}
time.Sleep(10 * time.Millisecond)
}
}
func (r *Router) updateProfile(w http.ResponseWriter, req *http.Request) {
userID, name := req.FormValue("id"), req.FormValue("name")
lsn, err := r.Write(req.Context(), func(tx *sql.Tx) error {
_, err := tx.ExecContext(req.Context(),
`UPDATE users SET display_name = $1 WHERE id = $2`, name, userID)
return err
})
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
// Short-lived token: after a minute every replica has caught up anyway.
http.SetCookie(w, &http.Cookie{Name: lsnCookie, Value: lsn, MaxAge: 60, HttpOnly: true, Path: "/"})
http.Redirect(w, req, "/profile?id="+userID, http.StatusSeeOther)
}
func (r *Router) showProfile(w http.ResponseWriter, req *http.Request) {
token := ""
if c, err := req.Cookie(lsnCookie); err == nil {
token = c.Value
}
db := r.ReadDB(req.Context(), token)
var name string
err := db.QueryRowContext(req.Context(),
`SELECT display_name FROM users WHERE id = $1`, req.FormValue("id")).Scan(&name)
if errors.Is(err, sql.ErrNoRows) {
http.NotFound(w, req)
return
}
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
fmt.Fprintf(w, "display name: %s\n", name)
}
func main() {
primaryDSN, replicaDSN := os.Getenv("PRIMARY_DSN"), os.Getenv("REPLICA_DSN")
if primaryDSN == "" || replicaDSN == "" {
fmt.Println("set PRIMARY_DSN and REPLICA_DSN, e.g. postgres://postgres:pg@localhost:5432/postgres")
return
}
primary, err := sql.Open("pgx", primaryDSN)
if err != nil {
log.Fatal(err)
}
replica, err := sql.Open("pgx", replicaDSN)
if err != nil {
log.Fatal(err)
}
r := &Router{Primary: primary, Replica: replica, MaxWait: 50 * time.Millisecond}
http.HandleFunc("POST /profile", r.updateProfile)
http.HandleFunc("GET /profile", r.showProfile)
log.Fatal(http.ListenAndServe(":8080", nil))
}Laravel: read/write connections with sticky.
<?php
// config/database.php (excerpt): one primary for writes, replicas for reads.
// 'sticky' => true sends every read of THIS request to the primary once the
// request has written something (read-your-writes inside one request only).
return [
'connections' => [
'pgsql' => [
'driver' => 'pgsql',
'read' => [
'host' => [
env('DB_REPLICA_1', '10.0.0.11'),
env('DB_REPLICA_2', '10.0.0.12'),
],
],
'write' => [
'host' => [env('DB_PRIMARY', '10.0.0.10')],
],
'sticky' => true,
'port' => env('DB_PORT', '5432'),
'database' => env('DB_DATABASE', 'shop'),
'username' => env('DB_USERNAME', 'app'),
'password' => env('DB_PASSWORD', ''),
'charset' => 'utf8',
'prefix' => '',
'search_path' => 'public',
'sslmode' => 'prefer',
],
],
];Laravel: across requests, and forcing individual reads. PreventStaleDatabaseReads tracks writes "in the user's session"; "By default, requests within two seconds of a write will use the write connection for reads on that connection." withoutAffectingStickiness stops bookkeeping writes from pinning the rest of the request to the primary.
<?php
// Read-your-writes in Laravel 13, from cheapest to most precise.
// 1. bootstrap/app.php: across requests, for 5 seconds after this session wrote,
// read from the write connection (default is 2 seconds).
use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Middleware;
use Illuminate\Foundation\Http\Middleware\PreventStaleDatabaseReads;
return Application::configure(basePath: dirname(__DIR__))
->withRouting(web: __DIR__.'/../routes/web.php')
->withMiddleware(function (Middleware $middleware): void {
$middleware->web(append: [
PreventStaleDatabaseReads::for(5),
]);
})
->create();
// 2. In a controller or job: force one read to the primary.
//
// use App\Models\Order;
// use Illuminate\Support\Facades\DB;
//
// $order = Order::onWriteConnection()->findOrFail($id); // Eloquent
// $rows = DB::connection()->usingWritePdo( // a whole callback
// fn ($db) => $db->table('order_lines')->where('order_id', $id)->get()
// );
//
// 3. Bookkeeping writes that must NOT pin the rest of the request to the primary:
//
// DB::withoutAffectingStickiness(function () use ($id) {
// DB::table('orders')->where('id', $id)->update(['viewed_at' => now()]);
// });Laravel: LSN fence instead of a time window (PostgreSQL; uses scalar() on the read connection, useWriteConnectionWhenReading() and hasModifiedRecords() from Illuminate\Database\Connection).
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Symfony\Component\HttpFoundation\Response;
/**
* PostgreSQL read-your-writes by WAL position instead of a time window.
*
* After a request that wrote, remember the primary's LSN in the session.
* On the next request, read from a replica only if it has replayed that LSN;
* otherwise read from the primary for this request.
*/
class LsnFence
{
public function handle(Request $request, Closure $next): Response
{
$db = DB::connection('pgsql');
$minLsn = $request->session()->get('_min_lsn');
if ($minLsn !== null) {
// Runs on a read replica (no write happened yet in this request).
$caughtUp = $db->scalar(
'select coalesce(pg_last_wal_replay_lsn() >= ?::pg_lsn, true)',
[$minLsn]
);
$db->useWriteConnectionWhenReading(! $caughtUp);
}
$response = $next($request);
if ($db->hasModifiedRecords()) {
// $useReadPdo = false: ask the primary, after our COMMIT.
$lsn = $db->scalar('select pg_current_wal_lsn()::text', [], false);
$request->session()->put('_min_lsn', $lsn);
}
return $response;
}
}Monotonic reads across several replicas
| Solution | How | Advantage | Cost / limitation |
|---|---|---|---|
| Sticky replica per user | replica = replicas[hash(user_id) % n] | No state | Rebalances when a replica is removed; uneven load |
| Max-seen position | Keep max(lsn) of every read in the session; read only from replicas at or past it | Survives replica changes | One extra check per read |
| Read your own primary region | Multi-region: home users to a region | Natural for Cosmos DB/Cassandra LOCAL_* | Users who travel |
// Sticky replica per user: same user, same replica, so reads never go backwards
// (unless that replica is replaced, then fall back to the max-seen-LSN check).
func replicaFor(userID uint64, replicas []*sql.DB) *sql.DB {
return replicas[userID%uint64(len(replicas))]
}// Laravel: pick a read host per user by building a named connection at runtime.
config(['database.connections.pgsql.read.host' => [
$replicas[crc32((string) auth()->id()) % count($replicas)],
]]);
DB::purge('pgsql'); // next query reconnects with the pinned hostCausal across requests and services: MongoDB causal sessions
The order service writes "PAID", then redirects to a page (or calls a service) that reads from a secondary. Without a causal session the read may hit a secondary that has not applied the write. With one, the driver sends afterClusterTime and the secondary waits.
// MongoDB causally consistent session: write on the primary, read from a
// secondary, and still read your own write (read concern "majority" +
// write concern "majority", per the MongoDB causal consistency table).
package main
import (
"context"
"fmt"
"log"
"os"
"time"
"go.mongodb.org/mongo-driver/v2/bson"
"go.mongodb.org/mongo-driver/v2/mongo"
"go.mongodb.org/mongo-driver/v2/mongo/options"
"go.mongodb.org/mongo-driver/v2/mongo/readconcern"
"go.mongodb.org/mongo-driver/v2/mongo/readpref"
"go.mongodb.org/mongo-driver/v2/mongo/writeconcern"
)
func main() {
uri := os.Getenv("MONGODB_URI") // e.g. mongodb://localhost:27017/?replicaSet=rs0
if uri == "" {
fmt.Println("set MONGODB_URI to a replica set URI")
return
}
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
client, err := mongo.Connect(options.Client().ApplyURI(uri))
if err != nil {
log.Fatal(err)
}
defer func() { _ = client.Disconnect(context.Background()) }()
// Reads may go to secondaries (cheap, possibly stale) ...
orders := client.Database("shop").Collection("orders", options.Collection().
SetReadConcern(readconcern.Majority()).
SetWriteConcern(writeconcern.Majority()).
SetReadPreference(readpref.SecondaryPreferred(readpref.WithMaxStaleness(90*time.Second))))
// ... but inside a causally consistent session each read waits until the
// chosen member has applied everything this session already wrote or read.
sess, err := client.StartSession(options.Session().SetCausalConsistency(true))
if err != nil {
log.Fatal(err)
}
defer sess.EndSession(ctx)
sctx := mongo.NewSessionContext(ctx, sess)
if _, err := orders.UpdateOne(sctx,
bson.D{{Key: "_id", Value: "o-1001"}},
bson.D{{Key: "$set", Value: bson.D{{Key: "status", Value: "PAID"}}}},
options.UpdateOne().SetUpsert(true)); err != nil {
log.Fatal(err)
}
var got bson.M
if err := orders.FindOne(sctx, bson.D{{Key: "_id", Value: "o-1001"}}).Decode(&got); err != nil {
log.Fatal(err)
}
fmt.Println("read in same session:", got["status"]) // PAID, even from a secondary
// Carrying causality to another request or service: ship the session's
// cluster time and operation time, and advance a fresh session with them.
clusterTime, opTime := sess.ClusterTime(), sess.OperationTime()
next, err := client.StartSession(options.Session().SetCausalConsistency(true))
if err != nil {
log.Fatal(err)
}
defer next.EndSession(ctx)
if err := next.AdvanceClusterTime(clusterTime); err != nil {
log.Fatal(err)
}
if err := next.AdvanceOperationTime(opTime); err != nil {
log.Fatal(err)
}
nctx := mongo.NewSessionContext(ctx, next)
if err := orders.FindOne(nctx, bson.D{{Key: "_id", Value: "o-1001"}}).Decode(&got); err != nil {
log.Fatal(err)
}
fmt.Println("read in next request:", got["status"]) // PAID
}<?php
namespace App\Services;
use Illuminate\Support\Facades\DB;
use MongoDB\BSON\Timestamp;
use MongoDB\Driver\ReadConcern;
use MongoDB\Driver\ReadPreference;
use MongoDB\Driver\WriteConcern;
/**
* MongoDB causally consistent session from Laravel (mongodb/laravel-mongodb).
* Reads may be served by secondaries and still observe this session's writes.
*/
class OrderStatusService
{
public function markPaidAndRead(string $orderId): array
{
/** @var \MongoDB\Client $client */
$client = DB::connection('mongodb')->getClient();
$orders = $client->selectCollection('shop', 'orders', [
'readConcern' => new ReadConcern(ReadConcern::MAJORITY),
'writeConcern' => new WriteConcern(WriteConcern::MAJORITY),
'readPreference' => new ReadPreference(
ReadPreference::SECONDARY_PREFERRED,
null,
['maxStalenessSeconds' => 90],
),
]);
$session = $client->startSession(['causalConsistency' => true]);
try {
$orders->updateOne(
['_id' => $orderId],
['$set' => ['status' => 'PAID']],
['upsert' => true, 'session' => $session],
);
// Same session: the secondary waits until it has applied the update.
$order = $orders->findOne(['_id' => $orderId], ['session' => $session]);
// Hand these to the next request (e.g. store in the HTTP session).
return [
'status' => $order['status'] ?? null,
'clusterTime' => $session->getClusterTime(),
'operationTime' => $session->getOperationTime(),
];
} finally {
$session->endSession();
}
}
public function readAfter(string $orderId, object $clusterTime, Timestamp $operationTime): ?string
{
$client = DB::connection('mongodb')->getClient();
$session = $client->startSession(['causalConsistency' => true]);
$session->advanceClusterTime($clusterTime);
$session->advanceOperationTime($operationTime);
try {
$order = $client->selectCollection('shop', 'orders', [
'readConcern' => new ReadConcern(ReadConcern::MAJORITY),
'readPreference' => new ReadPreference(ReadPreference::SECONDARY_PREFERRED),
])->findOne(['_id' => $orderId], ['session' => $session]);
return $order['status'] ?? null;
} finally {
$session->endSession();
}
}
}The cross-request part is the key: ClusterTime()/OperationTime() (Go) and getClusterTime()/getOperationTime() (PHP) are the token, AdvanceClusterTime/AdvanceOperationTime apply it to a new session. Only the "majority"/"majority" combination gives all four guarantees durably.
Per-query consistency in Cassandra
| Query | CL | Why |
|---|---|---|
| Add to cart, then show cart | LOCAL_QUORUM write + LOCAL_QUORUM read | Overlap within the DC: read-your-writes |
| Trending items, counters on a dashboard | LOCAL_ONE | Staleness acceptable; lowest latency |
| Reserve the last copy | LWT IF qty = 1, serial LOCAL_SERIAL, commit LOCAL_QUORUM | Compare-and-set needs consensus, not quorum overlap |
| Cross-DC "must be in both DCs" | EACH_QUORUM write | Every DC has a majority |
// Cassandra consistency level per query with gocql (compile-only example).
// Cheap default (LOCAL_ONE), LOCAL_QUORUM where read-your-writes matters,
// and LOCAL_SERIAL for a lightweight transaction (compare-and-set).
package main
import (
"fmt"
"log"
"os"
"strings"
"time"
"github.com/gocql/gocql"
)
func main() {
hosts := os.Getenv("CASSANDRA_HOSTS") // e.g. "10.0.0.1,10.0.0.2,10.0.0.3"
if hosts == "" {
fmt.Println("set CASSANDRA_HOSTS to run against a cluster")
return
}
cluster := gocql.NewCluster(strings.Split(hosts, ",")...)
cluster.Keyspace = "shop"
cluster.Consistency = gocql.LocalOne // default for every query that does not override it
cluster.Timeout = 2 * time.Second
session, err := cluster.CreateSession()
if err != nil {
log.Fatal(err)
}
defer session.Close()
cartID := gocql.TimeUUID()
// Write with LOCAL_QUORUM: 2 of 3 replicas in this DC must acknowledge (RF=3).
if err := session.Query(
`INSERT INTO carts (id, item, qty) VALUES (?, ?, ?)`, cartID, "book-42", 1).
Consistency(gocql.LocalQuorum).Exec(); err != nil {
log.Fatal(err) // e.g. *gocql.RequestErrUnavailable or *gocql.RequestErrWriteTimeout
}
// Read with LOCAL_QUORUM: W + R = 2 + 2 > RF = 3, so this read overlaps the write.
var qty int
if err := session.Query(
`SELECT qty FROM carts WHERE id = ? AND item = ?`, cartID, "book-42").
Consistency(gocql.LocalQuorum).Scan(&qty); err != nil {
log.Fatal(err)
}
fmt.Println("qty after own write:", qty)
// A dashboard tolerates staleness: LOCAL_ONE (the cluster default) is enough.
var n int
if err := session.Query(`SELECT count(*) FROM carts_by_day WHERE day = ?`, "2026-11-25").
Scan(&n); err != nil {
log.Fatal(err)
}
fmt.Println("carts today (may lag a little):", n)
// Lightweight transaction: Paxos round at LOCAL_SERIAL, commit at LOCAL_QUORUM.
previous := map[string]interface{}{}
applied, err := session.Query(
`UPDATE stock SET qty = ? WHERE sku = ? IF qty = ?`, 0, "book-42", 1).
Consistency(gocql.LocalQuorum).
SerialConsistency(gocql.LocalSerial).
MapScanCAS(previous)
if err != nil {
log.Fatal(err)
}
fmt.Println("reserved last copy:", applied, "current row if not applied:", previous)
}Laravel: there is no maintained Cassandra driver for PHP 8 (the DataStax PHP driver is "in maintenance mode" and lists PHP 5.6 to 7.1), so Laravel apps usually reach Cassandra through a small Go/Java service or an HTTP data API that exposes the consistency level as a parameter. Keep the CL decision in that service, next to the query.
Confirmation pages on DynamoDB
// DynamoDB: eventually consistent reads by default, ConsistentRead per request.
package main
import (
"context"
"fmt"
"log"
"os"
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/config"
"github.com/aws/aws-sdk-go-v2/service/dynamodb"
"github.com/aws/aws-sdk-go-v2/service/dynamodb/types"
)
func main() {
if os.Getenv("AWS_REGION") == "" {
fmt.Println("set AWS_REGION (and credentials) to run against DynamoDB")
return
}
ctx := context.Background()
cfg, err := config.LoadDefaultConfig(ctx)
if err != nil {
log.Fatal(err)
}
db := dynamodb.NewFromConfig(cfg)
key := map[string]types.AttributeValue{"pk": &types.AttributeValueMemberS{Value: "ORDER#1001"}}
// 1. Write the new status.
if _, err := db.UpdateItem(ctx, &dynamodb.UpdateItemInput{
TableName: aws.String("orders"),
Key: key,
UpdateExpression: aws.String("SET #s = :s"),
ExpressionAttributeNames: map[string]string{"#s": "status"},
ExpressionAttributeValues: map[string]types.AttributeValue{":s": &types.AttributeValueMemberS{Value: "PAID"}},
}); err != nil {
log.Fatal(err)
}
// 2. Read it back on the confirmation page: strongly consistent (twice the read cost).
out, err := db.GetItem(ctx, &dynamodb.GetItemInput{
TableName: aws.String("orders"),
Key: key,
ConsistentRead: aws.Bool(true),
})
if err != nil {
log.Fatal(err)
}
fmt.Println("status:", out.Item["status"])
// 3. A list page on a global secondary index: GSIs only support eventually
// consistent reads, so ConsistentRead must stay unset (false).
page, err := db.Query(ctx, &dynamodb.QueryInput{
TableName: aws.String("orders"),
IndexName: aws.String("by_customer"),
KeyConditionExpression: aws.String("customer_id = :c"),
ExpressionAttributeValues: map[string]types.AttributeValue{":c": &types.AttributeValueMemberS{Value: "C-7"}},
})
if err != nil {
log.Fatal(err)
}
fmt.Println("orders on list page (may lag):", page.Count)
}<?php
namespace App\Services;
use Aws\DynamoDb\DynamoDbClient;
use Aws\DynamoDb\Marshaler;
/**
* DynamoDB from Laravel with the AWS SDK for PHP v3 (aws/aws-sdk-php).
* Default reads are eventually consistent; ask for ConsistentRead per request.
*/
class OrderReader
{
private Marshaler $marshaler;
public function __construct(private DynamoDbClient $dynamo)
{
$this->marshaler = new Marshaler();
}
/** Confirmation page right after checkout: must see the write. */
public function statusAfterWrite(string $orderId): ?string
{
$result = $this->dynamo->getItem([
'TableName' => 'orders',
'Key' => $this->marshaler->marshalItem(['pk' => 'ORDER#'.$orderId]),
'ConsistentRead' => true, // strongly consistent: twice the read capacity
]);
if (! isset($result['Item'])) {
return null;
}
return $this->marshaler->unmarshalItem($result['Item'])['status'] ?? null;
}
/** Order history list on a GSI: eventual only (GSIs reject ConsistentRead). */
public function history(string $customerId): array
{
$result = $this->dynamo->query([
'TableName' => 'orders',
'IndexName' => 'by_customer',
'KeyConditionExpression' => 'customer_id = :c',
'ExpressionAttributeValues' => $this->marshaler->marshalItem([':c' => $customerId]),
]);
return array_map(
fn (array $item) => $this->marshaler->unmarshalItem($item),
$result['Items'] ?? [],
);
}
}The pattern: strongly consistent GetItem on the base table where the user expects their write; eventual queries on GSIs for lists, with the UX patterns below to cover GSI lag.
Concurrent writers: do not let LWW decide money
| Data | Conflict strategy |
|---|---|
| Balances, stock, seat maps | Single writer per key or conditional writes: Cassandra IF, DynamoDB ConditionExpression, SQL UPDATE ... WHERE version = ? |
| Shopping cart, tags, followers | Merge (set union) or a CRDT; tombstones for removals |
| Profile fields | Per-field LWW is acceptable; record updated_at from one clock source |
| Counters | CRDT G-counters, atomic increments on one leader, or sharded counters with periodic sums |
-- DynamoDB-style condition expressed in SQL terms: the write is the check
UPDATE stock SET qty = qty - 1, version = version + 1
WHERE sku = 'book-42' AND qty >= 1 AND version = 17; -- 0 rows -> lost the race, re-read and retryUX patterns for staleness
The database's inconsistency window becomes a UX problem only when a human notices. Vogels' rule ("smaller than the time expected for the customer to return for the next page load") turns into concrete patterns:
| Pattern | What the user sees | How | Use with |
|---|---|---|---|
| Optimistic UI | The change immediately, with a subtle "saving..." state | Client updates local state on submit; rolls back with an error toast if the request fails | Likes, toggles, renames, chat messages |
| Return the written object | The confirmation page renders from the write response, not a re-read | RETURNING *, DynamoDB ReturnValues: ALL_NEW, MongoDB findOneAndUpdate | Checkout, form submit, profile save |
| Read-after-write routing | The next pages from the primary or a caught-up replica | Sticky, PreventStaleDatabaseReads, LSN/GTID fence | Any multi-page flow after a write |
| Pending state | "Processing: this may take a minute" | Status column PENDING → DONE; poll or push | Async pipelines, search indexing, GSI-backed lists |
| Version-aware polling | Spinner until version ≥ expected | Client sends If-None-Match/?min_version= and retries | Read models fed by CDC/queues |
| Staleness label | "Updated 2 minutes ago" | Show max(updated_at) or replica lag | Dashboards, analytics |
| Merge local + server | Your own new item at the top of a list that is otherwise eventual | Insert the just-created row client-side until the server list contains it | Feeds, comments, order history |
What not to do: hide staleness with "refresh in a few seconds" advice, or retry reads in a loop against the same lagging replica.
Testing consistency
Jepsen runs a database under a realistic client workload while injecting faults (network partitions, process pauses and crashes, clock skew), records every operation's invocation and completion, then checks the history against a consistency model. Knossos checks linearizability of single-object histories; Elle checks transactional isolation anomalies from histories of list-append and register workloads. Jepsen's published analyses of individual databases are the best evidence of what a product's documented knob delivers under faults. A consistency model in Jepsen's words "is a safety property which declares what a system can do."
What you can do in your own pipeline:
| Test | How | Catches |
|---|---|---|
| Read-after-write probe | Write on primary, read on replica immediately, count misses (stalereads lab program) | Missing read-your-writes routing; lag regressions |
| Lag SLO alert | pg_stat_replication.replay_lag, MySQL Seconds_Behind_Source / performance_schema, Cassandra hints, Cosmos DB PBS metric | Windows growing beyond what UX assumes |
| Fault injection in staging | docker pause a replica, tc netem delay, kill the primary mid-write | Code paths that assume "write ok ⇒ readable" |
| History checking | Record operations with timestamps; check monotonic reads per user offline | Load-balancer reshuffles, cache layering bugs |
| Contract tests per endpoint | Declare per endpoint "needs RYW / tolerates T seconds"; assert router choice | Endpoints silently moved to replicas |
Choosing a consistency level
| Read or write | Recommended guarantee | Product knob | Reason |
|---|---|---|---|
| Page right after the user's own write | Read-your-writes | LSN/GTID fence, PreventStaleDatabaseReads, Cosmos DB Session, MongoDB causal session, DynamoDB ConsistentRead | The user notices; others do not |
| Uniqueness, balance, stock decision | Linearizable / conditional write | Primary, LWT, ConditionExpression, "linearizable" | A stale read causes a wrong decision |
| Comment threads, permissions changes | Causal | MongoDB "majority" causal sessions; single leader | Effect must not precede cause |
| Feeds, counts, recommendations | Eventual | Any replica, LOCAL_ONE, eventual reads | Cheap and good enough |
| Dashboards, search, analytics | Bounded staleness | Cosmos DB Bounded, CockroachDB with_max_staleness, Oracle STANDBY_MAX_DATA_DELAY, lag-checked routing | Old is fine; very old is an incident |
| Multi-region reads of rarely changing data | Bounded or exact staleness | CockroachDB follower reads, Spanner stale reads, global tables | Local latency |
| Writes that must survive a primary loss | Durability, not visibility | PostgreSQL synchronous_commit = on with sync standby, MySQL semi-sync, MongoDB { w: "majority" } | RPO 0; visibility is a separate choice |
| Background jobs reading what the request wrote | Read-your-writes across processes | Pass the token in the job payload, or read from the primary | The job runs milliseconds after commit |
In architecture: from a single process to a distributed system
Replica consistency appears the moment one logical piece of data lives in two places: a replica, a cache, a search index, another service's copy, another region. Every one of those is an eventually consistent copy, and the same four session guarantees describe what users can see.
Monolith: one process, one database
How it shows up: with one primary and no replicas there is no replica lag; but a cache (Redis) or a search index (Elasticsearch, PostgreSQL FTS in a separate job) already is an eventually consistent copy.
Simplest correct usage: read from the primary; invalidate caches after commit; render confirmation pages from the write's RETURNING data.
Example (simple): a Laravel shop on one PostgreSQL: Order::create() then redirect()->route('orders.show', $order); no replica, no issue.
Example (complex): the same shop adds one read replica for reports and turns on 'sticky' => true. The "My orders" page after checkout is a new request, so sticky does not help; the bug appears only under load when lag exceeds a few hundred milliseconds. Fix: PreventStaleDatabaseReads::for(5), or route /orders* to the primary, and keep only /reports* on the replica.
Modular monolith and multiple databases
How it shows up: modules own their data; one module reads another's data through an API or a replicated read model fed by events. That read model is eventually consistent by construction.
Example: Catalog publishes PriceChanged via the outbox; Checkout keeps a local prices table. A user who just changed a price in the admin (Catalog) and immediately opens checkout sees the old price. Options: show the price from the Catalog API on that one screen, carry a version (price_version >= 18) and wait briefly, or accept and re-validate the price at payment time (the usual answer: the write path re-checks).
Microservices: tokens across hops
What survives: each service's own database guarantees. What does not: any guarantee between services; the user's request crosses several stores with different lag. Make the causal token part of the API.
Browser Orders API (PostgreSQL primary + replicas) Notifications service (MongoDB)
1 POST /orders -> INSERT order; COMMIT; lsn = 0/5A0001F0
publish OrderPlaced {order_id, lsn} (outbox)
2 302 -> GET /orders/77 (cookie min_lsn=0/5A0001F0) -> replica caught up? else primary
3 consume OrderPlaced; write notification
(causal session, w: "majority")
4 GET /notifications (token: clusterTime from step 3, via the orders page) -> secondary waits until appliedRules: put the read position in events and redirects; consumers that read back the producer's database must read at or after that position (or from the primary); idempotent consumers absorb redelivery (Idempotent Consumers); never let a saga step make a money decision from a replica.
Distributed data: replicas, caches, multi-region
Read replicas: the whole of this page; lag is visible in replay_lag and grows with long standby queries (max_standby_streaming_delay), heavy writes and network. Caches: a cache is a replica without a log; use delete-after-commit, short TTLs and versioned values (details in Isolation Levels: cache lost update). Multi-region: choose per table: single-writer region with local stale reads (Cosmos DB Session/Bounded, CockroachDB follower reads, Spanner stale reads), or multi-writer with LWW and conflict-free data types, or synchronous (DynamoDB MRSC, Cosmos DB Strong, Spanner) and pay the cross-region RTT on every write. Failover: with async replication a promoted replica may miss the last acknowledged writes, breaking even read-your-writes on the primary; semi-sync, synchronous_commit = on with a sync standby, and MongoDB { w: "majority" } close that (see Replication & Failover). Consensus systems avoid replica lag for strong reads but pay a quorum round trip (Distributed SQL).
Scaling path: 1×, 10×, 100×
| Load | What changes | Consistency consequence |
|---|---|---|
| 1× (one primary) | Everything on the primary; maybe a cache | Only cache staleness; invalidate after commit |
| 10× (read replicas, connection pooling, queues) | Reports and lists move to replicas; jobs run asynchronously | Add read-your-writes routing (window or LSN fence); pass tokens into jobs; alert on replay_lag p99 |
| 100× (sharding, multi-region, polyglot stores) | Per-region replicas, Cassandra/DynamoDB for hot paths, search and analytics copies | Per-query consistency levels; session tokens across services; LWW only where data allows; conditional writes for invariants; staleness labels in the UI |
At every step the same rule holds: decide per read what is the weakest guarantee that is still correct, and make the code say it explicitly (a CL argument, a ConsistentRead, a routing token), not a global default.
Lab
Docker was not available when this page was written, so the expected output below is derived from the documented behaviour cited on this page, not from a recorded run. Two terminals per experiment.
Setup: PostgreSQL primary + async streaming replica with a deliberate 3-second replay delay.
docker network create eclab
docker run -d --name pgp --network eclab -e POSTGRES_PASSWORD=pg -p 5432:5432 postgres:17 \
-c wal_level=replica -c max_wal_senders=5 -c hot_standby=on
docker exec pgp psql -U postgres -c "CREATE ROLE repl WITH REPLICATION LOGIN PASSWORD 'repl';"
docker exec pgp bash -c "echo 'host replication repl all md5' >> \$PGDATA/pg_hba.conf"
docker exec pgp psql -U postgres -c "SELECT pg_reload_conf();"
docker run -d --name pgr --network eclab -e PGPASSWORD=repl -p 5433:5432 --entrypoint bash postgres:17 -c '
D=/var/lib/postgresql/data
if [ ! -f $D/PG_VERSION ]; then
until pg_basebackup -h pgp -U repl -D $D -R -X stream; do sleep 1; done
echo "recovery_min_apply_delay = 3s" >> $D/postgresql.auto.conf
chown -R postgres $D && chmod 700 $D
fi
exec gosu postgres postgres -c hot_standby=on'
# terminal A (primary): docker exec -it pgp psql -U postgres
# terminal B (replica): docker exec -it pgr psql -U postgres-- terminal A (primary)
CREATE TABLE users (id int PRIMARY KEY, display_name text NOT NULL);
INSERT INTO users VALUES (7, 'Sam');
CREATE TABLE counters (id int PRIMARY KEY, v int NOT NULL);
INSERT INTO counters VALUES (1, 0);Experiment 1: the stale read (read-your-writes violation). Paste steps 1 to 3 quickly (the window is 3 seconds), or raise recovery_min_apply_delay to 30s for this experiment.
A (primary) B (replica)
1 UPDATE users SET display_name='Sara' WHERE id=7; -- autocommit, returns at once
2 SELECT pg_current_wal_lsn(); -- e.g. 0/3000148
3 SELECT display_name FROM users WHERE id=7; -- 'Sam' (stale)
4 SELECT pg_last_wal_replay_lsn() >= '0/3000148'; -- f
5 -- wait 3 s
6 SELECT display_name FROM users WHERE id=7; -- 'Sara'Experiment 2: measure it from Go. With PRIMARY_DSN=postgres://postgres:pg@localhost:5432/postgres?sslmode=disable and REPLICA_DSN=...:5433/..., run the probe; with the 3 s delay every read is stale. Remove the delay on the replica (ALTER SYSTEM SET recovery_min_apply_delay = 0; SELECT pg_reload_conf(); in terminal B; the parameter is reloadable) and run again: a few or zero stale reads, depending on your machine.
// Lab helper: measure how often a read on an async PostgreSQL replica,
// issued right after a commit on the primary, returns the old value.
// Run it once with synchronous_commit=on and once with remote_apply.
package main
import (
"context"
"database/sql"
"fmt"
"log"
"os"
"time"
_ "github.com/jackc/pgx/v5/stdlib"
)
func main() {
primaryDSN, replicaDSN := os.Getenv("PRIMARY_DSN"), os.Getenv("REPLICA_DSN")
if primaryDSN == "" || replicaDSN == "" {
fmt.Println("set PRIMARY_DSN and REPLICA_DSN (see the Lab section)")
return
}
mode := os.Getenv("SYNC_COMMIT") // "on" (default) or "remote_apply"
if mode == "" {
mode = "on"
}
ctx := context.Background()
primary, err := sql.Open("pgx", primaryDSN)
if err != nil {
log.Fatal(err)
}
replica, err := sql.Open("pgx", replicaDSN)
if err != nil {
log.Fatal(err)
}
// One pinned connection so SET applies to every UPDATE below.
conn, err := primary.Conn(ctx)
if err != nil {
log.Fatal(err)
}
defer conn.Close()
if _, err := conn.ExecContext(ctx, "SET synchronous_commit = "+pqIdent(mode)); err != nil {
log.Fatal(err)
}
const n = 200
stale := 0
var worst time.Duration
for i := 1; i <= n; i++ {
start := time.Now()
if _, err := conn.ExecContext(ctx, `UPDATE counters SET v = $1 WHERE id = 1`, i); err != nil {
log.Fatal(err)
}
var seen int
if err := replica.QueryRowContext(ctx, `SELECT v FROM counters WHERE id = 1`).Scan(&seen); err != nil {
log.Fatal(err)
}
if seen != i {
stale++
}
if d := time.Since(start); d > worst {
worst = d
}
}
fmt.Printf("synchronous_commit=%s: %d/%d reads stale, slowest write+read %v\n", mode, stale, n, worst)
}
// pqIdent allows only the two values this lab uses.
func pqIdent(mode string) string {
if mode == "remote_apply" {
return "remote_apply"
}
return "on"
}$ go run ./stalereads
synchronous_commit=on: 200/200 reads stale, ... # with recovery_min_apply_delay = 3s
synchronous_commit=on: 0..20/200 reads stale, ... # without the delay (varies)Experiment 3: remote_apply closes the window, and shows its price. Make the replica synchronous: on the primary ALTER SYSTEM SET synchronous_standby_names = 'walreceiver'; SELECT pg_reload_conf(); (the default application_name of a standby started this way is walreceiver; check SELECT application_name FROM pg_stat_replication;). First see the price with one timed statement while the 3 s delay is still set: in terminal A run \timing on, SET synchronous_commit = remote_apply; and one UPDATE counters SET v = v + 1 WHERE id = 1;; it takes just over 3 seconds, because the commit waits for replay. Then remove the delay (as in Experiment 2) and run SYNC_COMMIT=remote_apply go run ./stalereads. Expected: 0 stale reads, with every commit paying the replay round trip. That is the cost of making a replica read-your-writes for everyone.
Setup: MongoDB 3-member replica set.
for i in 1 2 3; do docker run -d --name m$i --network eclab mongo:8.0 --replSet rs0 --bind_ip_all; done
docker exec m1 mongosh --quiet --eval 'rs.initiate({_id:"rs0",members:[{_id:0,host:"m1:27017",priority:2},{_id:1,host:"m2:27017"},{_id:2,host:"m3:27017"}]})'
# terminal A: docker exec -it m1 mongosh (primary)Experiment 4: read concern "local" vs "majority". Freeze replication on both secondaries with db.fsyncLock() (they keep heartbeating, so m1 stays primary), then write with { w: 1 }.
A (m1, primary) m2 / m3
1 db.fsyncLock() (on both)
2 db.orders.insertOne({_id: 1, status: "NEW"}, {writeConcern: {w: 1}}) // acknowledged
3 db.orders.find({_id: 1}).readConcern("local") // { _id: 1, status: "NEW" } may still roll back
4 db.orders.find({_id: 1}).readConcern("majority") // nothing: not majority-committed yet
5 db.orders.insertOne({_id: 2}, {writeConcern: {w: "majority", wtimeout: 2000}})
// write concern error after 2 s: not replicated to a majority (the write is on the primary)
6 db.fsyncUnlock() (on both)
7 db.orders.find({_id: 1}).readConcern("majority") // { _id: 1, status: "NEW" }Experiment 5: causal session from Go. The member names m1..m3 resolve only inside the eclab network, so run the program there (for example in a golang container attached to eclab) with MONGODB_URI=mongodb://m1:27017,m2:27017,m3:27017/?replicaSet=rs0; go run ./mongocausal prints PAID twice, including from the second session advanced with the first one's cluster and operation time.
Cleanup: docker rm -f pgp pgr m1 m2 m3 && docker network rm eclab.
Common misconceptions
| Belief | Reality |
|---|---|
| "Eventual consistency has a time bound" | No; convergence only if writes stop. Bounded staleness is a separate, stronger promise |
| "My SQL database is strongly consistent" | Only on the primary; any async replica read is eventual |
| "MySQL semi-sync makes replica reads fresh" | Replicas only received and logged the events; they may not have applied them |
"synchronous_commit = on gives read-your-writes on the sync standby" | on waits for flush, not replay; only remote_apply waits for visibility |
"R+W>N is linearizable" | It gives overlap, not linearizability: LWW, partial writes and sloppy quorums break it |
| "LWW keeps the latest write" | It keeps the largest timestamp; concurrent writes and clock skew lose data silently |
| "MongoDB causal sessions work with any concerns" | All four guarantees hold durably only with "majority" read and write concern |
| "Cosmos DB Session is causal for everyone" | It covers one client session (or clients sharing the token); others see eventual |
"DynamoDB ConsistentRead works on every index" | Tables and LSIs only; GSIs and Streams are always eventual |
"Laravel sticky fixes read-after-write" | Only within the same request; use PreventStaleDatabaseReads or a token for the redirect |
| "Replica lag is a few milliseconds" | Usually; minutes during bulk loads, long standby queries or network trouble |
| "Monotonic reads come for free with replicas" | Two replicas with different lag make reads go backwards |
| "Strong reads are always safer" | They also fail or block during partitions; choose per read |
Cheat sheet
| Topic | What to remember |
|---|---|
| Eventual | Converges if writes stop; no time bound; no order |
| Session guarantees | Read-your-writes, monotonic reads, monotonic writes, writes-follow-reads (Terry 1994) |
| Causal | Cause before effect for everyone; strongest sticky-available model |
| Bounded staleness | K versions or T time; Cosmos DB throttles writes, others refuse or reroute reads |
| Quorum | R+W>N overlaps; W=N fails writes when one node is down |
| Sloppy quorum | Available writes on stand-ins with hints; overlap not guaranteed |
| Convergence paths | Hinted handoff, read repair, anti-entropy (Merkle trees) |
| LWW | Largest timestamp wins; use conditional writes for invariants |
| PostgreSQL | remote_apply for visibility; LSN fence with pg_last_wal_replay_lsn(); watch replay_lag |
| MySQL | Semi-sync = durability; WAIT_FOR_EXECUTED_GTID_SET = read-your-writes; GR group_replication_consistency |
| Cassandra | Per-query CL; LOCAL_QUORUM both ways; LWT LOCAL_SERIAL for CAS |
| MongoDB | "majority" + "majority" + causal session = all four guarantees |
| DynamoDB | ConsistentRead: true = 2× cost, not on GSIs; global tables MREC are LWW |
| Cosmos DB | Strong, Bounded staleness, Session, Consistent prefix, Eventual; override only weaker |
| CockroachDB | Follower reads: follower_read_timestamp(), with_max_staleness, with_min_timestamp |
| Laravel | sticky, PreventStaleDatabaseReads::for(n), usingWritePdo, onWriteConnection(), withoutAffectingStickiness |
Self-check: questions & answers
- Must-know asked in almost every interview
- Important frequent; expected at senior level
- Good to know extra depth that sets you apart
1 — A user saves a profile and is redirected; the next page shows the old name. Laravel has 'sticky' => true. Why did it not help, and what does? Must-know
Answer
Answer: sticky only affects the current request; the redirect is a new request that reads from a replica. Use PreventStaleDatabaseReads (a time window in the session) or an LSN/GTID token, or render the confirmation from the write's returned data. See read-after-write.
2 — PostgreSQL with synchronous_standby_names = 'FIRST 1 (s1)' and synchronous_commit = on: is a read on s1 right after commit guaranteed fresh? Important
Answer
Answer: No. on waits for the standby to flush the WAL, not to replay it. Only remote_apply waits until the commit "has become visible to queries on the standby(s)".
3 — Cassandra, RF=3, writes at ONE, reads at QUORUM. Is read-your-writes guaranteed? Important
Answer
Answer: No: W + R = 1 + 2 = 3, not greater than RF. The read set can miss the single replica that took the write. Use QUORUM writes (2 + 2 > 3) or ALL reads.
4 — Why can a quorum system still return an older value after a newer one was returned? Good to know
Answer
Answer: A failed write may have reached one replica; a quorum read that includes it returns the new value, the next quorum read without it returns the old one. Cassandra's blocking read repair exists to give "monotonic quorum reads"; with read_repair = 'NONE' that guarantee is gone.
5 — Which MongoDB read/write concern combination gives all four causal guarantees durably, and what does "local" + { w: 1 } give? Good to know
Answer
Answer: "majority" + "majority" in a causally consistent session gives all four. "local" + { w: 1 } cannot guarantee any of them.
6 — A DynamoDB order history page uses a GSI by customer. Product asks for "always show the order just placed". What do you do? Must-know
Answer
Answer: GSIs do not support ConsistentRead. Read the new order by key from the base table with ConsistentRead: true and merge it into the list client-side, or show it from the write response.
7 — What is the difference between Cosmos DB Session and Consistent prefix? Important
Answer
Answer: Session gives one client read-your-writes and writes-follow-reads (plus monotonic reads/writes) via a session token; Consistent prefix only guarantees readers never see writes out of order or partial transactional batches, but may be arbitrarily behind and may not show your own write.
8 — Two regions accept writes to the same cart item with LWW. What goes wrong and what are the alternatives? Must-know
Answer
Answer: Concurrent writes overwrite each other: one region's addition disappears silently. Alternatives: merge (set union/CRDT), a single home region per cart, or conditional writes.
9 — Why is MySQL semi-sync not a read-your-writes solution, and what is? Must-know
Answer
Answer: Semi-sync only waits until a replica has received and logged the events, "not that the events have been fully executed and committed on the replica side", and silently falls back to async on timeout. Use WAIT_FOR_EXECUTED_GTID_SET with the GTID of the write, read from the source, or Group Replication AFTER/BEFORE.
10 — A dashboard may be up to 30 s old. Which knobs implement that in Cosmos DB, CockroachDB, MongoDB and Oracle? Good to know
Answer
Answer: Cosmos DB Bounded staleness with T = 30 s (writes throttle if exceeded); CockroachDB AS OF SYSTEM TIME with_max_staleness('30s'); MongoDB cannot go below maxStalenessSeconds 90, so use 90 or check lag yourself; Oracle Active Data Guard ALTER SESSION SET STANDBY_MAX_DATA_DELAY = 30 (ORA-3172 when exceeded).
11 — How would you prove that your read-after-write routing works? Important
Answer
Answer: Inject lag (recovery_min_apply_delay, paused replica), run a write-then-read probe through the real routing code and assert zero stale reads, and keep a lag SLO alert in production. For a database's own claims, read its Jepsen analysis.
Glossary
| Term | Meaning |
|---|---|
| Replica consistency | Which version of data a read returns when several copies exist (different from ACID consistency and isolation) |
| Strong consistency | In database docs, usually linearizability: reads see the latest completed write |
| Linearizability | Every operation appears atomic at one point between its start and end, respecting real-time order (single object) |
| Strict serializable | Serializable transactions that also respect real-time order (Spanner's external consistency) |
| Eventual consistency | If no new updates are made, all copies eventually return the last updated value |
| Weak consistency | No guarantee that a read after a write returns it (Vogels' umbrella term) |
| Convergence | Replicas that have seen the same updates hold the same state |
| Inconsistency window | Vogels: time between an update and when every observer is guaranteed to see it |
| Staleness | How old the data a read returns is, in versions or time |
| Staleness bounds | Limits on staleness (K versions, T seconds) enforced by bounded staleness, or measured probabilistically by PBS |
| Linearizability vs eventual | Safety with real-time recency on every read vs liveness-only convergence once writes stop |
| Session guarantees | Terry et al.'s four per-session guarantees for weakly consistent replicated data |
| Read-your-writes (read my writes) | A session's reads observe its own earlier writes |
| Monotonic reads | A session never reads an older state than it already read |
| Monotonic writes | A session's writes are applied everywhere in session order |
| Writes-follow-reads (session causality) | A session's write is ordered after writes it previously read |
| Session consistency | Vogels/Cosmos DB: read-your-writes (and more) for the life of a session |
| Consistent prefix | Readers see some prefix of the write history, never gaps or reorderings |
| Causal consistency | Causally related operations are seen in the same order by everyone |
| Sequential consistency | All processes see one total order consistent with each process's order, without real-time constraints |
| Bounded staleness | Reads lag by at most K versions or T time |
| PBS | Probabilistically Bounded Staleness: expected staleness from latency distributions (Bailis et al. 2012) |
| t-visibility | PBS: probability a read t seconds after a write commits observes it |
| k-staleness | PBS: probability a read returns one of the last k versions |
| WARS | PBS model of write/ack/read/response latencies in Dynamo-style stores |
| Totally / sticky available | Jepsen availability classes: every node can progress / progress if clients stay on one node |
| Quorum | A subset of replicas whose size guarantees overlap with other quorums (majority) |
| N, R, W | Replicas, replicas read, replicas that must acknowledge a write |
| R+W>N | Overlap condition: some replica in every read has the latest acknowledged write |
| Partial (non-strict) quorum | R+W<=N; reads may miss the latest write |
| Sloppy quorum | Dynamo: reads/writes use the first N healthy nodes, possibly outside the key's home replicas |
| Hinted handoff | A stand-in node stores a write with a hint and delivers it when the owner returns |
| max_hint_window | Cassandra limit (3 h default) on how long hints are collected for a down node |
| Read repair | Coordinator writes the newest version to stale replicas it noticed during a read |
| Blocking read repair | Cassandra default: the read waits for repair, giving monotonic quorum reads |
| Anti-entropy | Background comparison and sync of replicas (Merkle trees, nodetool repair) |
| Merkle tree | Hash tree over key ranges; mismatching subtrees locate differing data |
| Last-write-wins (LWW) | Conflict rule keeping the value with the largest timestamp |
| Siblings | Concurrent versions returned to the client for reconciliation (Dynamo, Riak) |
| Version vector | (replica, counter) pairs that tell whether versions are ordered or concurrent |
| Vector clock | Dynamo's version vector per object version |
| CRDT | Conflict-free replicated data type: merges deterministically without coordination |
| Tunable consistency | Choosing consistency per request (Cassandra CL, DynamoDB ConsistentRead, Cosmos DB override) |
| Consistency level (CL) | Cassandra: how many replicas must respond (ONE, QUORUM, LOCAL_QUORUM, ALL...) |
| LOCAL_QUORUM / EACH_QUORUM | Majority in the coordinator's DC / in every DC |
| LOCAL_ONE / ANY | One replica in the local DC / any node, including a hint (writes only) |
| Lightweight transaction (LWT) | Cassandra Paxos-based compare-and-set (IF ...) at SERIAL/LOCAL_SERIAL |
| synchronous_commit | PostgreSQL: what a commit waits for (off to remote_apply) |
| remote_apply | PostgreSQL: commit waits until sync standbys replayed it and it is visible there |
| synchronous_standby_names | PostgreSQL list (FIRST n/ANY n) of standbys commits wait for |
| LSN | PostgreSQL WAL position; pg_current_wal_lsn(), pg_last_wal_replay_lsn() |
| replay_lag | pg_stat_replication column approximating the delay before commits become visible on a standby |
| recovery_min_apply_delay | PostgreSQL standby setting that delays replay on purpose |
| max_standby_streaming_delay | PostgreSQL: how long replay may wait for conflicting standby queries (30 s default) |
| hot_standby_feedback | PostgreSQL: standby tells primary which rows it still needs, avoiding cancellations |
| Semi-sync | MySQL semisynchronous replication: commit waits for a replica to receive and log events |
| AFTER_SYNC / AFTER_COMMIT | MySQL semi-sync wait points (rpl_semi_sync_source_wait_point) |
| GTID | MySQL global transaction identifier; WAIT_FOR_EXECUTED_GTID_SET waits for a set |
| group_replication_consistency | MySQL Group Replication: EVENTUAL, BEFORE_ON_PRIMARY_FAILOVER, BEFORE, AFTER, BEFORE_AND_AFTER |
| readConcern | MongoDB: which data a read may return (local, available, majority, linearizable, snapshot) |
| writeConcern | MongoDB: acknowledgment level (w, j, wtimeout) |
| readPreference | MongoDB: which member serves reads (primary ... nearest) |
| maxStalenessSeconds | MongoDB read preference option; minimum 90 seconds |
| Causally consistent session | MongoDB session that orders operations via afterClusterTime |
| afterClusterTime / operationTime / clusterTime | MongoDB logical times carried by causal sessions |
| Rollback (MongoDB) | Non-majority writes undone after a failover |
| ConsistentRead | DynamoDB request parameter for strongly consistent reads (tables, LSIs) |
| GSI / LSI | DynamoDB global / local secondary index; GSIs are eventual only |
| MREC / MRSC | DynamoDB global tables: multi-Region eventual (LWW) / strong consistency |
| Cosmos DB consistency levels | Strong, Bounded staleness, Session, Consistent prefix, Eventual |
| Session token | Cosmos DB partition-bound token a client presents to read its writes |
| Follower read | CockroachDB read served by a non-leaseholder replica at a past timestamp |
| AS OF SYSTEM TIME | CockroachDB/Spanner-style historical read clause |
| follower_read_timestamp() | CockroachDB function returning a timestamp likely servable locally |
| with_max_staleness / with_min_timestamp | CockroachDB bounded staleness functions |
| Exact staleness | Read at a fixed past timestamp (CockroachDB, Spanner) |
| STANDBY_MAX_DATA_DELAY | Oracle Active Data Guard session limit on apply lag; ORA-3172 if exceeded |
| Readable secondary | SQL Server Always On secondary that serves read-only queries with data latency |
| WAIT (Redis) | Blocks until N replicas acknowledged previous writes; not strong consistency |
| Litestream | SQLite WAL streaming replication (asynchronous) |
| Sticky routing | Keep a client on one server (or on the primary) to get session guarantees |
| PreventStaleDatabaseReads | Laravel 13 middleware: reads use the write connection for N seconds after a session's write |
| sticky (Laravel) | Read/write connection option: after a write, the same request reads from the write connection |
| usingWritePdo / onWriteConnection | Laravel: force reads in a callback / an Eloquent query to the write connection |
| withoutAffectingStickiness | Laravel: run writes that should not pin later reads to the primary |
| Optimistic UI | Client shows the change before the server confirms it, rolling back on failure |
| Read-after-write routing | Sending reads that follow a write to a source known to include it |
| Jepsen | Fault-injection testing of databases against consistency models |
| Knossos / Elle | Jepsen checkers for linearizability / transactional anomalies |
| CAP / PACELC | Partition forces consistency vs availability; else latency vs consistency |
| Bayou | Xerox PARC replicated store (1994) where session guarantees were defined |
| Dynamo | Amazon's 2007 leaderless key-value store: sloppy quorums, hinted handoff, vector clocks |
References
- Werner Vogels, "Eventually Consistent" (revised), All Things Distributed, 2008; a revised version appeared in CACM in 2009. allthingsdistributed.com
- Terry, Demers, Petersen, Spreitzer, Theimer, Welch, "Session Guarantees for Weakly Consistent Replicated Data", PDIS 1994. Cornell course copy
- DeCandia et al., "Dynamo: Amazon's Highly Available Key-value Store", SOSP 2007. PDF
- Bailis, Venkataraman, Franklin, Hellerstein, Stoica, "Probabilistically Bounded Staleness for Practical Partial Quorums", VLDB 2012. PDF
- Viotti & Vukolić, "Consistency in Non-Transactional Distributed Storage Systems", 2016. arXiv:1512.00168
- Jepsen: Consistency, Read Your Writes, Monotonic Reads, Monotonic Writes, Writes Follow Reads, Causal, Linearizable
- Martin Kleppmann, Designing Data-Intensive Applications, chapters 5 and 9 (secondary source for quorum edge cases and linearizability)
- PostgreSQL: WAL configuration (
synchronous_commit), Replication settings, Log-shipping standby servers / synchronous replication, Hot standby, System administration functions, Monitoring statistics (pg_stat_replication) - MySQL 8.4 Reference Manual (read via web.archive.org): Semisynchronous Replication, Replication source options, GTID functions, Group Replication consistency guarantees
- Apache Cassandra: Dynamo architecture (tunable consistency), Hints, Read repair
- MongoDB manual: Read Concern, "local", "majority", Write Concern, Causal Consistency and Read and Write Concerns, maxStalenessSeconds
- AWS: DynamoDB read consistency, Global tables: how it works, AWS SDK for PHP DynamoDB API
- Microsoft: Azure Cosmos DB consistency levels, Cosmos DB conflict resolution policies, SQL Server readable secondary replicas
- CockroachDB: Follower Reads
- Google Cloud: Spanner timestamp bounds
- Oracle Database 19c: Managing a physical standby (STANDBY_MAX_DATA_DELAY)
- Redis: WAIT; Litestream: How it works
- Laravel 13: Database: read and write connections, sticky, PreventStaleDatabaseReads; framework source: PreventStaleDatabaseReads.php, Connection.php; mongodb/laravel-mongodb Connection.php; PHP: MongoDB\Driver\Manager::startSession, MongoDB\Driver\Session; DataStax PHP driver README
- Go: gocql, mongo-go-driver v2, aws-sdk-go-v2 dynamodb, pgx v5