Skip to content

Consistency Models: Linearizability vs Serializability, Causal, Client-Centric, Convergence ​

"Linearizability provides the illusion that each operation applied by concurrent processes takes effect instantaneously at some point between its invocation and its response" — Maurice Herlihy and Jeannette Wing, Linearizability: A Correctness Condition for Concurrent Objects, ACM TOPLAS, 1990

Summary: A consistency model is the contract between a replicated system and its clients: which results a read is allowed to return, given everything that was written and when. This page lays out the whole map, from linearizability and strict serializability at the top to eventual consistency at the bottom, and shows how real products expose each level. Focus: Linearizability (single-copy, real-time order), sequential consistency, causal and causal+, PRAM/FIFO, eventual and strong eventual consistency, the four session guarantees, the transactional family (serializable, strict serializable, snapshot isolation, read committed), why linearizability and serializability are different axes, linearizable reads in Raft and Paxos systems (ReadIndex, lease reads, quorum reads), clocks (Lamport, vector, HLC, TrueTime), product behaviour (Spanner, CockroachDB, Cassandra, DynamoDB, MongoDB, Redis, PostgreSQL), convergence, testing with Jepsen, Elle, Knossos and Porcupine, and how to choose per use case. Learning goal: For any feature, say which consistency model it needs and what the user would see under a weaker one; recognise an anomaly in a history; configure the product to deliver that model (read concern, ConsistentRead, IF NOT EXISTS, version tokens, sticky reads); and test the claim with a checker instead of trusting the brochure.

This chapter sits in the Consistency & Distributed Data group, right after CAP Under a Real Partition, CP vs AP, PACELC (which says that you must choose under a partition) and before ACID vs BASE and Replication Topologies (which say how replicas are wired). It owns the distributed framing of consistency. Single-database anomalies (dirty read, write skew, phantoms) are taught in Isolation Levels; replication mechanics and lag in Replication, Read Replicas & Failover; consensus internals in Distributed SQL, Consensus & 2PC; clocks in depth in Vector Clocks, Lamport Clocks & Distributed Causality; repair and anti-entropy in Merkle Trees, Read Repair, Anti-Entropy & Tombstones; merge-by-construction in CRDTs.

Page map ​

If you are looking forGo to
The whole page in three tablesEverything in one minute
What a consistency model actually isWhy it exists
Lamport, Herlihy and Wing, Terry, COPS, Spanner, JepsenWhere it comes from
Linearizability and CAS registersLinearizability
Sequential consistencySequential
Causal, causal+, PRAM/FIFOCausal, PRAM
Eventual, strong eventual, convergenceEventual and convergence
Read-your-writes, monotonic reads/writes, writes-follow-readsSession guarantees
Serializable vs strict serializable vs snapshot isolation vs read committedTransactional models
The difference between linearizability and serializabilityLinearizability vs serializability
ReadIndex, lease reads, quorum readsLinearizable reads in consensus systems
Lamport, vector, HLC, TrueTime, clock skewClocks
What Spanner, CockroachDB, Cassandra, DynamoDB, MongoDB, Redis, PostgreSQL really give youProducts
Knobs and error messagesMechanics
CodeGo, Laravel
Stale profile, double booking, lost comment reply, clock skewSolving the classic problems
Jepsen, Elle, Knossos, PorcupineTesting consistency
Which model for which featureChoosing
Monolith to multi-regionIn architecture
Run the checker and the session clientLab
Wrong beliefs, summary, quiz, termsMisconceptions, Cheat sheet, Self-check, Glossary

Everything in one minute ​

Single-object models, strongest first.

ModelIn plain wordsTiny example of what it forbidsAvailable under partition?Product example
LinearizableBehaves like one copy; every operation takes effect at one instant inside its callWrite of 1 returns OK; a read that starts afterwards returns 0Noetcd default reads; MongoDB "linearizable" read concern; Cassandra LWT on one partition
SequentialOne total order everyone agrees on, each client's own order kept; may lag real timeClient sees its own write, then later does notNoCPU memory model in Lamport's paper; follower reads of a Raft log
Causal (+ causal+)Cause before effect for everybody; unrelated writes may be seen in different ordersReply "yes" visible before the question "lunch?"Sticky availableMongoDB causally consistent sessions; COPS
PRAM / FIFOEach writer's writes are seen in the order it issued themSeeing a user's second edit before their firstSticky availableSingle-partition queues; per-key ordered logs
Session guaranteesOne client never contradicts its own historyYour own comment missing after you posted itRYW sticky; MR/MW/WFR totallyLaravel sticky, version tokens, MongoDB sessions
EventualIf writes stop, replicas end up equalNothing in the short termYesDynamoDB default reads; Cassandra ONE; Redis replicas
Strong eventualReplicas that saw the same updates are equal, with no conflict stepTwo replicas with the same updates disagreeingYesCRDT-based stores and libraries (see CRDTs)

Transactional models, strongest first.

ModelIn plain wordsWhat it adds over the next oneProduct example
Strict serializable / external consistencyTransactions run one at a time, in an order that respects real timeReal-time orderSpanner (default); a single-node SERIALIZABLE database
SerializableTransactions equal some one-at-a-time orderNo write skew, no phantomsCockroachDB SERIALIZABLE (default); PostgreSQL SSI
Snapshot isolationEach transaction reads a consistent snapshot; first committer wins on the same rowNo non-repeatable reads, no lost updates on one rowPostgreSQL REPEATABLE READ; Oracle's strongest level (HAT survey: not serializable); MongoDB "snapshot" transactions
Read committedEvery statement sees only committed dataNo dirty readsPostgreSQL default; CockroachDB READ COMMITTED; DynamoDB item reads

Tools that deliver a model, and their price.

ToolDeliversPriceSection
Single leader + consensus (Raft, Paxos)Linearizable writesOne quorum round trip per writeConsensus reads
ReadIndex or quorum readLinearizable readsOne heartbeat or quorum round per readConsensus reads
Leader lease readLinearizable reads, if clocks behaveCorrectness depends on bounded clock skewConsensus reads
TrueTime commit waitStrict serializability across the planetAbout 2 x epsilon of waiting per commitClocks
HLC + uncertainty windowSerializability, single-key linearizability while skew is under --max-offsetRead restartsClocks
Version token (LSN, GTID, operationTime)Read-your-writes, monotonic reads on replicasFallback to primary when replicas lagSession guarantees
Dependency tracking (COPS) or causal sessionsCausal+Metadata per write, delayed visibilityCausal
CRDTs, anti-entropy, read repairConvergenceMerge semantics must fit the dataEventual
Strict serializableSerializableRepeatable readSnapshot isolationCursor stabilityMonotonic atomic viewRead committedRead uncommittedLinearizableSequentialCausalWrites follow readsPRAMMonotonic readsMonotonic writesRead your writesmulti-object transactionssingle-object operationsunavailable during a partitionsticky available (client stays on one node)totally availableArrow = implies (stronger to weaker). After jepsen.io/consistency/models.

The map is Jepsen's hierarchy redrawn. An arrow means "implies": every strict serializable history is linearizable and serializable; every linearizable history is sequential; and so on down. Colour is the price in availability. Jepsen's own summary: "All models at or stronger than cursor stability, snapshot isolation, and sequential cannot be totally available in asynchronous networks. All models at or stronger than read your writes can be at most sticky available."

Why it exists ​

The moment you keep two copies of a value (a replica, a cache, a second region), a read can be answered by a copy that has not heard about the latest write. A consistency model is the written-down answer to "what may that read return?" Jepsen defines it precisely: "A consistency model is a safety property which declares what a system can do. Formally, a consistency model defines a set of histories that a system can legally execute." A history is the list of operations with their invocation time, response time and result. A model is a filter over histories: legal or not.

Stronger modelWeaker model
Easy to reason about: "it acts like one machine"Every feature must think about stale or reordered data
Needs coordination: a leader, a quorum, waitingEach replica answers alone
Higher latency, especially across regions (one round trip or more per operation)Local latency
Unavailable on the minority side of a partitionAvailable on both sides
Lower throughput per key (contention, consensus)Scales with replicas
Bugs show up as errors and timeoutsBugs show up as wrong data, days later

The analogy we reuse on this page: the shared wall calendar and the family's phones. One paper calendar on the kitchen wall is linearizable: there is one copy, and the moment someone writes "dentist, Tuesday 3 pm", anyone who looks afterwards sees it. Now everyone has a synced phone calendar. Eventual consistency is "the phones sync whenever they get Wi-Fi". Read-your-writes is "at least my own phone shows what I just added". Monotonic reads is "my phone never shows an older version of the week than it already showed me". Causal consistency is "if Mum moved the dentist because Dad's flight changed, nobody sees the new dentist time without also seeing the flight change". Serializability is about a whole planning session: "swap Tuesday and Thursday" must happen completely or not at all, as if one person did it alone.

Three common misunderstandings, up front ​

  1. "Strong consistency" means one thing. Vendors use it for linearizable reads (etcd), for "read from the leader" (DynamoDB ConsistentRead), for serializable transactions (CockroachDB) and for external consistency (Spanner). Always ask: single object or transactions, and is real-time order included?
  2. "Serializable is stronger than linearizable." They are different axes. Serializability is about multi-object transactions and says nothing about real time; linearizability is about single operations and says everything about real time. Peter Bailis: "Linearizability is a guarantee about single operations on single objects." Their combination is strict serializability.
  3. "The C in CAP is the C in ACID." CAP's C is linearizability (Kleppmann: "Consistency in CAP actually means linearizability"). ACID's C is "the application's invariants hold", which the database helps with through isolation, the I.

Where it comes from ​

1978, happened-before. Leslie Lamport's Time, Clocks, and the Ordering of Events in a Distributed System defined "happened before" as a partial order of events and logical clocks that respect it. Every causal model on this page is built on that relation.

1979, sequential consistency. Lamport's How to Make a Multiprocessor Computer That Correctly Executes Multiprocess Programs called a multiprocessor sequentially consistent if "the result of any execution is the same as if the operations of all the processors were executed in some sequential order, and the operations of each individual processor appear in this sequence in the order specified by its program."

1988, PRAM. Lipton and Sandberg relaxed coherent memory so that each processor's writes are seen in order, but different processors' writes may interleave differently (Jepsen's PRAM page).

1990, linearizability. Herlihy and Wing added the real-time constraint and showed that it composes: if every object is linearizable, the whole system is. They also placed it next to the database notion: "Linearizability can be viewed as a special case of strict serializability where transactions are restricted to consist of a single operation applied to a single object."

1994, session guarantees. Terry, Demers, Petersen, Spreitzer, Theimer and Welch, working on Bayou at Xerox PARC, defined four guarantees a single client can get even from a "read-any/write-any" replicated store: "Read Your Writes - read operations reflect previous writes. Monotonic Reads - successive reads reflect a non-decreasing set of writes. Writes Follow Reads - writes are propagated after reads on which they depend. Monotonic Writes - writes are propagated after writes that logically precede them."

2000 to 2012, CAP and its fallout. Brewer's conjecture (2000) and Gilbert and Lynch's proof (2002) made linearizability the "C" every architect argues about; see CAP and PACELC.

2011, causal+. Lloyd, Freedman, Kaminsky and Andersen's COPS paper named "causal consistency with convergent conflict handling, or causal+" and showed it scales across data centres.

2012, Spanner. Google's OSDI paper delivered externally consistent transactions at global scale with TrueTime: "if a transaction T1 commits before another transaction T2 starts, then T1’s commit timestamp is smaller than T2’s."

2013, HATs. Bailis et al.'s Highly Available Transactions sorted every isolation level and session guarantee into "achievable without coordination" and "not": Read Committed and the session guarantees can be highly available; Snapshot Isolation and Repeatable Read cannot.

2013 to now, Jepsen. Kyle Kingsbury's Jepsen analyses, the Knossos and Elle checkers and the jepsen.io consistency map turned "which model does this database really provide" into something you test.

text
     Year   Idea                                    What it gave practitioners
1    1978   Happened-before, Lamport clocks          Causality without synchronised clocks
2    1979   Sequential consistency                    One agreed order, per-process order kept
3    1988   PRAM (pipelined RAM)                      Per-writer FIFO order only
4    1990   Linearizability (Herlihy and Wing)        Real-time single-copy semantics, composable
5    1994   Session guarantees (Bayou)                RYW, MR, WFR, MW for one client
6    2002   CAP proof (Gilbert and Lynch)             Linearizable + available + partitions: pick two
7    2011   COPS causal+                              Causal + convergence at data-centre scale
8    2012   Spanner TrueTime, external consistency    Strict serializability across continents
9    2013   Highly Available Transactions             Which levels need coordination
10   2014   Hybrid logical clocks                     Physical-time-like timestamps that respect causality
11   2013+  Jepsen, Knossos, Elle, Porcupine          Consistency claims checked against histories

The concept catalogue ​

Each block follows the same order: plain words, the usual wrong belief, a definition, a timeline, real scenarios, what products provide, and how to use it.

Linearizability Must-know ​

In plain words: the system behaves as if there were a single copy of the data, and every operation takes effect at one instant somewhere between the moment you call it and the moment it returns.

Common misunderstanding: "If replication is synchronous, reads are linearizable." Not necessarily: a follower that has received a write may not have applied it, and an old leader that has been deposed but does not know it can still answer reads. Linearizability is a property of the whole read and write path, including failover.

Definition: a history is linearizable if there is a total order of all operations that (1) is legal for the object's sequential specification (a register returns the last value written), and (2) respects real-time order: if operation A returned before operation B was invoked, A comes before B. Jepsen's wording: "every operation appears to take place atomically, in some order, consistent with the real-time ordering of those operations". It is also called atomic consistency, single-copy semantics or "the C in CAP". Because it is local (composable), you can reason per key.

text
     Client A                     Client B                     Client C
1    write(x=1) invoked
2                                 read(x) invoked
3                                 read(x) returns 1            (point after A's write took effect)
4                                                              read(x) invoked (after B returned)
5                                                              read(x) returns 0  <- ILLEGAL: value went back in time
6    write(x=1) returns ok
     Overlapping operations may be ordered either way; non-overlapping ones may not.
ABCABCwrite(1) ... okread() = 1read() = 0write(1) ... okread() = 0read() = 1NOT linearizableLinearizableC started after B returned, yet saw the older valueorder: B read 0, A write 1, C read 1timetimeBar = invocation to response. Dot = the instant the operation appears to take effect (linearization point).Both histories are sequentially consistent; only real-time order separates them.

CAS registers. The model you test most often is a register with read, write and compare-and-set (CAS). Linearizable CAS is what makes leader election, distributed locks, unique usernames and "reserve the last seat" correct: two concurrent cas(free -> taken) calls must not both succeed. etcd transactions (Txn with a Compare on mod_revision), Cassandra UPDATE ... IF, DynamoDB ConditionExpression on one item and Redis SET key value NX on a single primary all expose a CAS on one key.

Real scenario: username registration ("is sara free? take it"); seat or inventory reservation for the last unit; leader election and fencing tokens (Leader Election, Distributed Locking); a feature-flag service where "turned off" must be off for every server right now; a bank balance check before a withdrawal on a single account key.

What provides it:

ProductLinearizable operationHowCaveat
etcdAll reads and writes by defaultRaft; reads use ReadIndexRequests in "serializable" mode are local and may be stale
MongoDBReads with readConcern: "linearizable" on the primary, writes with w: "majority"Primary confirms it is still primary with a majoritySingle document only; slower; needs maxTimeMS
Cassandra / ScyllaDBLightweight transactions (IF NOT EXISTS, IF col = ?)Paxos per partition"non-negligible performance cost"; only within one partition
DynamoDBConditional writes on one item; ConsistentRead: true reads on the base tableLeader of the item's partitionNot for GSIs or Streams; global tables need MRSC
SpannerEvery read-write transaction and strong readPaxos + TrueTimeCommit wait adds latency
CockroachDBSingle-key operations while clock skew is within --max-offsetRaft + leaseholder + HLCNot claimed across keys (see clocks)
Redis (single primary)Commands on the primary, while it stays primarySingle-threaded executionAsync replication: a failover can lose acknowledged writes
PostgreSQL (single primary)Any statement on the primaryOne process tree, one WALReads on standbys are not linearizable

Fix / how to use it: route the operations that must be linearizable (claims, reservations, locks, uniqueness) to the consensus-backed or primary path and keep it small; express them as one CAS on one key; and test them with a linearizability checker (Go).

Sequential consistency Important ​

In plain words: everyone sees the same single order of operations, and each client's own operations stay in the order it issued them, but the order may lag behind the wall clock.

Common misunderstanding: "Sequential is basically linearizable." The missing piece is exactly the one users notice: real time. Under sequential consistency, a write can return OK and a different client can still read the old value afterwards, because that client is allowed to be "behind" in the agreed order. What it does forbid is going back: Jepsen notes "once a process A has observed some operation from process B, it can never observe a state prior to B."

Definition: Lamport 1979, quoted above. Viotti and Vukolić decompose it as SingleOrder plus per-process order (no RealTime constraint).

text
     Client A                  Client B
1    write(x=1) -> ok
2                              read(x) -> 0     legal under sequential: B's read ordered before A's write
3                              read(x) -> 1
4                              read(x) -> 0     ILLEGAL: B already saw 1 and cannot go back

Real scenario: a chat room where everybody must see messages in one agreed order but a few hundred ms of delay is fine; a replicated state machine whose followers serve reads from their applied state (they are sequential, not linearizable); multicore CPU memory (Lamport's original setting).

What provides it:

Product / settingBehaviour
Raft or Paxos follower reads (etcd serializable mode)One log order; a follower can be behind: sequential-like, stale
Total order broadcast (Kafka single partition)Every consumer sees the same order of one partition, each at its own speed
x86-TSO, ARM, Java/Go memory modelsWeaker than sequential by default; sequential only for data-race-free programs

Fix / how to use it: if a feature can tolerate "late but never out of order", follower reads of a consensus log are much cheaper than linearizable reads. If the user will compare with a side channel ("I just told you on the phone"), you need linearizability.

Causal consistency and causal+ Must-know ​

In plain words: if one write could have influenced another (I read your post and replied), everyone sees them in that order; writes that are unrelated may appear in different orders for different people.

Common misunderstanding: "Causal consistency needs synchronised clocks." It needs dependency tracking: vector clocks, explicit dependency lists (COPS), or a session token (MongoDB's operationTime and cluster time). Wall clocks cannot express "B saw A".

Definition: causally related operations (program order, reads-from, and their transitive closure: Lamport's happened-before) are seen in the same order by every process. Concurrent operations may be seen in any order. Causal+ (COPS) adds convergent conflict handling: replicas that saw the same writes end in the same state. Jepsen's example: Attiya asks "lunch?", Barbarella says "yes", Cyrus says "no"; observers may see "yes" and "no" in either order, but nobody sees an answer before the question.

text
     DC Europe                         DC Asia                          Observer in DC US
1    Ana posts photo P (w1)
2    Ana removes boss from ACL (w2)
3                                      Ben reads ACL (sees w2)
4                                      Ben comments "nice!" on P (w3, depends on w1)
5                                                                       receives w3 first
6                                                                       causal: w3 held back until w1 arrives
7                                                                       eventual only: comment on a photo that does not exist yet

Real scenario: social feeds (comment before the post it replies to); access control ("remove boss from album, then upload party photos": the classic COPS motivating example); chat with threads; collaborative editing; shopping carts where "remove item" must not be seen before "add item".

What provides it:

ProductMechanismGuaranteeCondition
MongoDB causally consistent sessionsoperationTime + cluster time; drivers set afterClusterTimeRYW, MR, MW, WFR within the session"majority" read concern and "majority" write concern
COPS / Eiger (research)Explicit dependency lists per writeCausal+ across data centresDependencies checked before a write becomes visible
Dynamo-style stores with version vectorsVersion vectors, siblingsDetects concurrency, app mergesClients must resolve siblings
CRDT libraries (Automerge, Yjs)Causal delivery + merge functionsStrong eventual + causalData must fit a CRDT (CRDTs)

Jepsen also notes causal consistency is "sticky available": during a partition every client can make progress, as long as it stays on the same server.

Fix / how to use it: carry causality with the request. In MongoDB, use one causally consistent session per logical user flow, with majority read and write concern, and pass the session's operationTime between services. In your own replica-read layer, a version token per session gives the session-level part (Session guarantees).

PRAM and FIFO consistency Good to know ​

In plain words: each writer's own writes arrive everywhere in the order that writer made them; writes from different writers may be interleaved differently on each replica.

Common misunderstanding: "FIFO is causal." FIFO misses writes-follow-reads: if Ben replies after reading Ana's post, FIFO does not stop someone seeing the reply first, because the two writes have different writers.

Definition: Jepsen: "It enforces that any pair of writes executed by a single process are observed (everywhere) in the order the process executed them". And: "PRAM is exactly equivalent to read your writes, monotonic writes, and monotonic reads."

text
     Ana (writer)            Replica R1             Replica R2
1    w1: title="Draft"
2    w2: title="Final"
3                            applies w1, w2         applies w1, w2      FIFO: never w2 then w1
4    Ben writes w3 after reading w2
5                            applies w3             applies w3 before w1 allowed: different writer

Real scenario: a Kafka partition keyed by user (per-key order, see Ordering & Partitioning); TCP within one connection; a per-device sync log.

What provides it: a single ordered log per writer or per key (Kafka partition, Redis Stream, PostgreSQL logical replication slot per table) gives FIFO for that writer or key.

Fix / how to use it: key messages and replicated writes by the entity whose order matters; when cross-entity causality matters, step up to causal.

Eventual consistency, strong eventual consistency and convergence Must-know ​

In plain words: if everyone stops writing, all copies eventually become the same. Until then, a read can return anything that was ever written, old or new, in any order.

Common misunderstanding: "Eventually means within a second." Eventual consistency has no time bound and no ordering guarantee at all; DynamoDB documents a typical figure for global tables ("typically within a second") but that is an operational observation, not part of the model. It also does not say which value wins.

Definition: eventual consistency: liveness only, convergence after writes stop. Strong eventual consistency (Shapiro et al. 2011): any two replicas that have delivered the same set of updates are in the same state, with no rollback and no conflict-resolution round. Convergence is the mechanism: anti-entropy (Merkle-tree comparison), read repair, hinted handoff, gossip, and a deterministic merge (last-writer-wins by timestamp, version vectors with siblings, or a CRDT).

text
     Client           Replica A           Replica B           Replica C
1    write x=1  ->    x=1 (ack)
2    read x     ->                        x=0  (stale read: legal)
3                     gossip / hinted handoff -> x=1         x=0
4                     anti-entropy (Merkle compare) ------>   x=1
5    read x     ->                                            x=1  converged

Real scenario: like counters and view counts; product catalogue reads behind a CDN; DNS; search indexes fed from a database; analytics; presence ("online" dots); shopping-cart merge in Amazon's Dynamo.

What provides it:

ProductDefaultConvergence mechanism
DynamoDBEventually consistent reads (half the price of strong)Replication within the Region; MREC for global tables
CassandraTunable: ONE, QUORUM, LOCAL_QUORUM, ALLRead repair, hinted handoff, anti-entropy repair (Merkle trees), LWW by write timestamp
Redis replicas / Redis ClusterAsynchronous replicationFull or partial resync; "last failover wins"
PostgreSQL / MySQL read replicasAsynchronous streamingWAL / binlog replay
CDNs, DNSTTL-basedExpiry and revalidation

Cassandra's tunable levels are "a version of Dynamo’s R + W > N consistency mechanism": with QUORUM writes and QUORUM reads the replica sets overlap, which gives read-your-writes for completed writes but, without LWT, not linearizability (two concurrent quorum writes are ordered by client timestamps).

Fix / how to use it: decide the merge rule before you go eventual (LWW loses concurrent updates; use CRDTs or siblings where losing an update matters); make reads idempotent and UIs tolerant of "a few seconds old"; add session guarantees for the user's own data. Mechanics of repair live in Merkle Trees & Anti-Entropy and Gossip Protocols.

Session guarantees (client-centric consistency) Must-know ​

In plain words: you cannot promise every user the latest data, but you can promise each user that the system never contradicts what they did or saw.

Common misunderstanding: "Sticky sessions on the load balancer give read-your-writes." They pin the user to an application server, not to a database replica; the app server still reads from whichever replica the pool hands out. And Laravel's sticky option only lasts for the current request.

Definition (Terry et al. 1994, Jepsen):

GuaranteePromiseAnomaly it preventsAvailability (Jepsen)
Read-your-writes (RYW, read-my-writes)A read reflects this session's earlier writes"I saved my profile and the old name is back"Sticky available
Monotonic reads (MR)Successive reads never go back to an older stateA comment appears, then disappears on refreshTotally available
Monotonic writes (MW)This session's writes are applied everywhere in orderSecond edit applied before the first, first winsTotally available
Writes-follow-reads (WFR, session causality)A write is ordered after the writes this session readReply visible before the message it answersTotally available
text
     User session          App server         Primary (LSN)        Replica R1 (replayed)
1    POST /profile  ->     UPDATE ...   ->    commit at 0/3000148
2                          token = 0/3000148 stored in session
3    GET /profile   ->     R1 replayed >= 0/3000148 ?            0/3000100
4                          no -> read from primary: new name (RYW holds)
5    GET /profile   ->     R1 replayed >= 0/3000148 ?            0/3000200
6                          yes -> read from R1, token.read = 0/3000200 (MR holds from now on)
Browsersession cookieApp server APOST /profileApp server BGET /profilePrimarypg_current_wal_lsn()Replica 1replayed 0/3000100Replica 2replayed 0/30002001. UPDATE, COMMITtoken 0/3000148token in sessiontoken sent back2. replayed >= token?3a. no: read primary3b. yes: read hereSame idea, other products:MongoDB: operationTime,driver sets afterClusterTimeCockroachDB: AS OFSYSTEM TIME timestampRaft / etcd: log indexor revision

Real scenario: profile edits and settings pages; posting a comment and seeing it; checkout flow (cart, then order summary); admin panels where an operator changes a price and immediately checks it; mobile apps that switch between Wi-Fi and cellular (different edge, different replica).

What provides it:

Product / featureRYWMRMWWFRScope
Laravel sticky => trueSame request onlySame request onlyYes (one primary)Yes (one primary)One HTTP request
Laravel PreventStaleDatabaseReads (13.x)For N seconds (default 2) after a writeSame windowYesYesOne session, default connection
LSN / GTID version token (this page's code)YesYesYesYesWhatever carries the token
MongoDB causally consistent session, majority/majorityYesYesYesYesOne session (token passable)
DynamoDB ConsistentRead: trueYes (base table, LSI)YesYesYesPer read, costs 2x
Cassandra QUORUM write + QUORUM readYes for completed writesNot guaranteed with failed writesLWW by timestampNoPer request
PostgreSQL synchronous_commit = remote_applyYes on synchronous standbysYesYesYesAll sessions; slower commits

Fix / how to use it: keep a version token (the primary's LSN, a MySQL GTID set, MongoDB operationTime, a Raft index) in the user's session or a response header; read from a replica only if it has applied at least that token; otherwise wait briefly or read from the primary. Code in Go and Laravel.

Transactional models: serializable, strict serializable, snapshot isolation, read committed Must-know ​

In plain words: transactional models say how groups of reads and writes over many rows interleave; single-object models say how one key behaves over time. A distributed database must answer both questions.

Common misunderstanding: "My database is serializable, so a read after a commit sees the commit." Serializability alone allows the database to order your later read before the earlier commit. Jepsen points out the extreme: "a serializable database can always return the empty state for any reads, by appearing to execute those reads at time 0." Real systems do not do that on purpose, but serializable reads from a lagging replica or at a stale timestamp do exactly a mild version of it.

Definition:

  • Serializable: the outcome equals some serial execution of the committed transactions. No real-time constraint, no per-process constraint.
  • Strict serializable (strong 1SR, external consistency in Spanner's vocabulary): serializable, and the serial order respects real time. Jepsen: "You can think of strict serializability as serializability’s total order of transactional multi-object operations, plus linearizability’s real-time constraints."
  • Snapshot isolation (SI): each transaction reads from a snapshot taken at its start and commits only if no concurrent transaction wrote the same rows (first committer wins). Allows write skew.
  • Read committed (RC): each read sees only committed data; different statements may see different snapshots.

The anomalies themselves (dirty read, non-repeatable read, phantom, lost update, write skew) are taught with two-session timelines in Isolation Levels; here the question is what changes when data is distributed.

text
     T1 (writer, region A)                    T2 (reader, region B, starts after T1 commits)
1    BEGIN; UPDATE accounts SET bal=bal-100 WHERE id=1;
2    COMMIT;  -- returns at 10:00:00.000
3                                             BEGIN;  -- 10:00:00.050, user saw T1's confirmation
4                                             SELECT bal FROM accounts WHERE id=1;
5    serializable only:      may read the pre-T1 balance (T2 ordered first); still a valid serial order
6    strict serializable:    must read the post-T1 balance

Real scenario: money transfer then statement page; "approve order" then the warehouse dashboard; inventory decrement in one region and a stock check in another; a migration script that writes and a verifier that reads.

What provides it:

ProductDefault levelStrongest levelReal-time order?
SpannerSerializable with external consistency (repeatable read also offered)External consistencyYes, via TrueTime commit wait
CockroachDBSERIALIZABLESERIALIZABLESingle-key linearizable while skew within --max-offset; "causal reverse" possible across keys
PostgreSQLREAD COMMITTEDSERIALIZABLE (SSI)On the primary, yes in practice; on standbys, no
MySQL InnoDBREPEATABLE READSERIALIZABLE (2PL)On the primary only
MongoDBTransactions use snapshot reads with readConcern: "snapshot"Snapshot isolationWith majority writes, on the primary
DynamoDBRead committed per item; TransactWriteItems serializableSerializable for transactionsStrongly consistent reads on base tables
CassandraNo multi-partition ACID transactions in the DML docs used here; LWT per partitionLinearizable per partition with LWTPer partition

Bailis's HAT result in one line: Read Committed and the session guarantees can be provided with high availability; "Snapshot Isolation and Repeatable Read isolation are not HAT-compliant", and neither is serializability.

Fix / how to use it: pick the level per transaction class (see Choosing); if a flow crosses a user-visible commit and then reads, make sure the read path is strict (primary, leaseholder, ConsistentRead) or carries a token.

Linearizability vs serializability Must-know ​

In plain words: linearizability answers "does one key behave like one copy, in real time?" Serializability answers "do whole transactions behave like they ran one at a time, in some order?" Strict serializability answers yes to both.

Common misunderstanding: "Serializable implies linearizable." Bailis: "Unlike linearizability, serializability does not—by itself—impose any real-time constraints on the ordering of transactions." And in the other direction, linearizable single keys do not prevent write skew across two keys.

Definition: see the grid. Linearizability is composable (per-object linearizable implies system linearizable); serializability is not composable (two serializable databases together are not serializable without a coordinator).

Some total order, no real-time ruleTotal order that respects real timeSingle objectone key / registerTransactionsmany objects at onceSequential consistencyper-client program order kepta client may lag behind othersLamport 1979; CPU memory modelsLinearizabilityacts like one copy, changes instantlyetcd default reads, Raft ReadIndex or lease reads,MongoDB "linearizable" read concernHerlihy and Wing 1990; CAP's CSerializabilitytransactions equal some serial runmay order a later txn before an earlier oneCockroachDB SERIALIZABLE (claimed level),any SERIALIZABLE read on a lagging replicaStrict serializabilityserializable + linearizableSpanner "external consistency",a single-node SERIALIZABLE database:one clock already gives real-time orderLinearizability is the single-operation, single-object special case of strict serializability (Herlihy and Wing).
text
     Linearizable but not serializable (two keys, each linearizable, no transactions)
1    T1: read x=0, read y=0, write x=1 (doctor 1 goes off call: "y is still on")
2    T2: read x=0, read y=0, write y=1 (doctor 2 goes off call: "x is still on")
3    every single operation is linearizable; together: nobody on call (write skew)

     Serializable but not linearizable (stale snapshot)
4    T1 commits balance=0 at 10:00:00.000 and the user sees "done"
5    T2 starts 10:00:00.050 on a replica with snapshot 09:59:59.900, reads balance=100
6    serial order T2, T1 is legal; real time is violated

Real scenario: on-call schedules and meeting-room bookings need serializability (multi-row invariant); leader election and username claims need linearizability (single-key, real time); a ledger with a "your transfer is done" confirmation needs both.

What provides it: see the products table.

Fix / how to use it: state both properties when you specify a requirement: "serializable transactions over orders and stock, and the order page must reflect a confirmed payment" means strict serializability on that read path.

Linearizable reads in consensus systems: ReadIndex, lease reads, quorum reads Important ​

In plain words: writes through Raft or Paxos are linearizable because they go through the log; reads are the tricky part, because the node answering may be an old leader that has not noticed it was replaced.

Common misunderstanding: "Reads from the Raft leader are linearizable." Only if the leader first proves it is still leader. The Raft paper: "Linearizable reads must not return stale data, and Raft needs two extra precautions to guarantee this without using the log."

Definition:

TechniqueHowCostRisk
Log readPut the read through the log like a writeFull consensus round + diskNone, slow
ReadIndexLeader records its commit index, confirms leadership with a heartbeat round to a majority, waits until applied up to that index, then readsOne network round, no disk writeNone (needs a committed no-op from the current term)
Lease readLeader holds a time-based lease; reads locally while the lease is validNo network round"this would rely on timing for safety (it assumes bounded clock skew)"
Follower read with ReadIndexFollower asks the leader for the read index, waits to apply it, reads locallyOne round to the leaderNone
Quorum read (Dynamo-style)Read from R replicas, take the newest; with read repair before returningR repliesLinearizable only with "write back before return" and no concurrent sloppy quorums
Stale / follower readRead local stateNoneSequential at best, stale
text
     Old leader L1 (partitioned)       New leader L2 (majority side)        Client
1    still believes it is leader
2                                      elected in term 8, commits x=2
3                                                                           read x via L1 with lease expired?
4    lease read with skewed clock:     returns x=1  <- stale, not linearizable
5    ReadIndex: heartbeat to majority fails -> L1 cannot serve the read (correct)

Real scenario: etcd reads (linearizable by default, and the store behind the Kubernetes API server); CockroachDB leaseholder reads; MongoDB linearizable read concern; any homegrown Raft service that answers reads from "the leader" without a ReadIndex round.

What provides it:

ProductDefault readLinearizable readCheaper option
etcdLinearizable (ReadIndex)DefaultSerializable mode (clientv3.WithSerializable()): local, may be stale
CockroachDBLeaseholder read (strongly consistent)DefaultFollower reads AS OF SYSTEM TIME follower_read_timestamp()
MongoDBGlobal default read concern"linearizable" on primary"majority" on secondaries (causal in sessions)
SpannerStrong readDefaultBounded or exact staleness reads

Fix / how to use it: use the product's linearizable mode for coordination data and its stale mode for dashboards; never implement lease reads yourself without a clock-skew bound and monitoring.

Clocks: Lamport, vector, hybrid logical clocks, TrueTime Important ​

In plain words: to order events across machines you need either a coordinator, a logical clock that tracks causality, or physical clocks with a known error bar.

Common misunderstanding: "NTP keeps clocks within a millisecond, so timestamp order is real-time order." NTP gives a typical offset, not a bound; a paused VM, a leap-second bug or a bad upstream can move a clock by seconds. Last-writer-wins by wall clock then silently discards the newer write.

Definition (one line each; depth in Vector Clocks & Causality):

ClockWhat it capturesSizeUsed by
Lamport clockA total order consistent with happened-before (if a → b then L(a) < L(b), not the reverse)One integerRaft terms and log indexes are in this spirit; Kafka offsets per partition
Vector clock / version vectorExact happened-before and concurrency detectionOne counter per nodeDynamo-style siblings, CRDT delivery
Hybrid logical clock (HLC)Physical-time-like timestamp + logical counter; respects causality64 bits + counterCockroachDB ("Time and hybrid logical clocks" in its transaction layer docs)
TrueTimeInterval [earliest, latest] guaranteed to contain absolute timeTwo timestampsSpanner

The HLC paper: "we propose a hybrid logical clock, HLC, that combines the best of logical clocks and physical clocks." Spanner's paper reports that TrueTime's uncertainty epsilon "is typically a sawtooth function of time, varying from about 1 to 7 ms over each poll interval."

Spanner (TrueTime): wait out the uncertainty, then acknowledgeTT.now() = [earliest, latest]commit waits = TT.now().latestTT.after(s) true: replyepsilon is typically 1-7 ms (about 4 ms) in the 2012 paper; every later transaction gets a larger timestamp.CockroachDB (HLC, no atomic clocks): read with an uncertainty windowread timestamp tvalue written at t+120 mst + max-offset (default 500ms)A value inside [t, t+max-offset] might have committed before the read started: push t past it, refresh reads, or restart(ReadWithinUncertaintyIntervalError). A node whose clock drifts past 80% of max-offset vs half the cluster shuts down.
text
     Spanner commit (TrueTime)                      CockroachDB read (HLC + uncertainty)
1    acquire locks, s = TT.now().latest             txn timestamp t = local HLC now
2    Paxos-replicate the commit record              read key k: newest version at 10:00:00.120 > t?
3    commit wait: until TT.after(s) is true         is it within [t, t + max-offset]?
4    release locks, reply                           yes -> uncertain: push t past it, refresh reads
5    any later txn gets a larger timestamp           refresh fails -> ReadWithinUncertaintyIntervalError, retry

Clock skew and the uncertainty window. CockroachDB documents the contract: "While serializable consistency is maintained under SERIALIZABLE isolation regardless of clock skew, skew outside the configured clock offset bounds can result in violations of single-key linearizability between causally dependent transactions." The bound is --max-offset, "Default: 500ms", and "when a node detects that its clock is out of sync with at least half of the other nodes in the cluster by 80% of the maximum offset allowed, it crashes immediately." Cockroach Labs' own summary: "While Spanner provides linearizability, CockroachDB only goes as far as to claim serializability".

Real scenario: LWW conflict resolution in Cassandra (client or coordinator timestamps); ordering events in logs from many hosts; global databases; expiring leases.

What provides it: see the table; the Go HLC snippet shows the algorithm in 60 lines.

Fix / how to use it: use logical or hybrid clocks for ordering, physical clocks only with a bound you monitor (chrony/NTP offset alerts, AWS Time Sync / PTP where available), and never use wall-clock LWW for data where concurrent updates both matter.

How products expose their models Must-know ​

In plain words: every product has a default that is weaker than you think and a switch that makes it stronger and slower. Know both.

Common misunderstanding: "We use a strongly consistent database, so we are fine." Most incidents come from the read path you added later: a replica, a cache, a search index, a GSI, a follower read.

Definition: the matrix below lists, per product, the default, the strongest option and the switch.

ProductDefault for readsStrongest optionSwitch / knobWatch out
SpannerStrong reads, externally consistent RW transactionsExternal consistencyStale reads at a chosen timestamp or bounded stalenessCommit wait (about 2 x epsilon)
CockroachDBSERIALIZABLE, leaseholder readsSERIALIZABLE (+ single-key linearizable)AS OF SYSTEM TIME follower_read_timestamp() for follower reads--max-offset (500ms), 40001 retries
CassandraConsistency level per request (set it explicitly in the driver; ONE is fast and weakest)LWT: IF NOT EXISTS / IF with SERIAL / LOCAL_SERIALCONSISTENCY QUORUM in cqlsh, driver settingsLWT is per partition and costly; mixing LWT and non-LWT writes on the same data breaks it
DynamoDBEventually consistent (ConsistentRead: false)ConsistentRead: true; transactions; MRSC global tablesConsistentRead on GetItem, Query, ScanNot on GSIs or Streams; costs 2x read units
MongoDBGlobal default read concern (normally "local"), global default write concern majority"linearizable" reads; causally consistent sessionsreadConcern, writeConcern, readPreference, startSession({causalConsistency: true})Causal only with majority/majority; one thread per session
Redis / Redis ClusterPrimary is linearizable while it lives; replicas asyncWAIT numreplicas timeout (durability, not consistency)WAIT, min-replicas-to-write"WAIT does not make Redis a strongly consistent store"; failover can lose acked writes
PostgreSQLPrimary: whatever isolation level; standbys: stalesynchronous_commit = remote_apply + synchronous_standby_namesSession tokens via pg_current_wal_lsn() / pg_last_wal_replay_lsn()remote_apply adds replay latency to every commit
etcdLinearizableLinearizableSerializable request mode (WithSerializable())"serializable" here means local and possibly stale

Real scenario: a team moves reads to DynamoDB GSIs for a new access pattern and breaks read-your-writes; a Cassandra cluster with ONE writes and ONE reads shows "unlike" bounces; a Redis lock survives a failover twice; a MongoDB secondary read shows yesterday's order status.

Fix / how to use it: write the consistency requirement next to each read path in the design doc and map it to the product switch from this table.

Mechanics ​

What each guarantee costs in round trips ​

Back-of-envelope figures with an inter-region RTT of about 70 ms (labelled estimate; measure yours):

OperationCoordinationSame-region latencyCross-region latency
Eventually consistent readNone1 local hop1 local hop
Read from leader with ReadIndexHeartbeat to majority+1 intra-region RTT+1 inter-region RTT if voters are spread
Linearizable write (Raft/Paxos)Majority append+1 RTT + fsync+1 inter-region RTT (about 70 ms)
Spanner RW commitPaxos + commit wait+ about 2 x epsilon+ RTT + about 2 x epsilon
Session-token replica readOne pg_last_wal_replay_lsn() check+1 tiny query, or primary fallbackLocal unless the replica lags
PostgreSQL remote_apply commitStandby applies WAL before reply+ replay time on standby+ RTT + replay

Knobs ​

sql
-- PostgreSQL: version tokens for read-your-writes
SELECT pg_current_wal_lsn();                                   -- on the primary, after COMMIT: e.g. 0/3000148
SELECT pg_last_wal_replay_lsn() >= '0/3000148'::pg_lsn AS ok;  -- on a standby
SELECT now() - pg_last_xact_replay_timestamp() AS replay_lag;  -- monitoring
-- PostgreSQL: make every commit visible on synchronous standbys before it returns
ALTER SYSTEM SET synchronous_standby_names = 'ANY 1 (standby_a, standby_b)';
ALTER SYSTEM SET synchronous_commit = 'remote_apply';
SELECT pg_reload_conf();

-- CockroachDB: follower read with bounded, known staleness
SELECT * FROM orders AS OF SYSTEM TIME follower_read_timestamp() WHERE id = 42;
SHOW TRANSACTION ISOLATION LEVEL;                               -- serializable

-- Cassandra CQL: linearizable claim on one partition (Paxos)
INSERT INTO usernames (name, user_id) VALUES ('sara', 7) IF NOT EXISTS;
UPDATE seats SET holder = 7 WHERE event = 'e1' AND seat = 'A12' IF holder = null;
-- cqlsh: CONSISTENCY QUORUM; SERIAL CONSISTENCY LOCAL_SERIAL;
ProductKnobValuesEffect
MongoDBreadConcernlocal, available, majority, linearizable, snapshotWhat a read may return
MongoDBwriteConcernw: 1, w: "majority", j: true, wtimeoutWhen a write is acknowledged
MongoDBcausalConsistency session optiontrue (default for startSession without snapshot)Driver attaches afterClusterTime
DynamoDBConsistentReadtrue / falseStrong vs eventual read, 2x cost
CassandraConsistency levelONE, LOCAL_ONE, QUORUM, LOCAL_QUORUM, EACH_QUORUM, ALLReplicas that must answer
CassandraSerial consistencySERIAL, LOCAL_SERIALPaxos scope for LWT
CockroachDB--max-offsetdefault 500msUncertainty window and self-termination threshold
PostgreSQLsynchronous_commitoff, local, remote_write, on, remote_applyHow far a commit waits
PostgreSQLmax_standby_streaming_delaydefault 30sHow long replay may pause for standby queries (lag source)
RedisWAIT n ms / min-replicas-to-writeintegersAcknowledgement from replicas; not consensus
etcdRequest consistencylinearizable (default), serializableReadIndex vs local read
Laravelsticky, PreventStaleDatabaseReads::for(n)bool, secondsRead from write connection after writes

Error messages you will actually see ​

ProductMessage / codeMeaningWhat to do
CockroachDBReadWithinUncertaintyIntervalError (SQLSTATE 40001)A value inside the uncertainty window forced a restartRetry the transaction; reduce clock skew
PostgreSQLSQLSTATE 40001 could not serialize access due to read/write dependencies among transactionsSerializable (SSI) conflictRetry with backoff
CockroachDBSQLSTATE 40001 transaction retry errorsSerializable conflict or pushed timestampRetry the whole transaction
CassandraLWT result row [applied] = FalseCAS lost; current values returnedTreat as a normal "taken" outcome
CassandraLWT write timeoutPaxos round timed out; outcome unknownRe-read at SERIAL before retrying
Redis Cluster-MOVED / -ASKSlot moved; client must redirectSmart client handles it; not a consistency signal
PostgreSQL standbyStandby query cancelled after max_standby_streaming_delay (default 30 s)Replay needed to proceed; the docs call this a conflict with about-to-be-applied WALRetry, hot_standby_feedback, or read primary

Go ​

Before ​

Writes go to the leader, reads to "any replica". No session guarantee at all; it works on a laptop and fails users in production.

go
// Package before shows the common first version of read scaling: writes go
// to the leader, every read goes to "any replica". It works in development
// (replicas are never behind on a laptop) and surprises users in production:
// a user saves a form, the redirect reads from a lagging replica, and the old
// value comes back. Nothing here is a bug in the code; the design simply
// promises no session guarantee at all.
package before

import (
	"context"
	"math/rand/v2"

	"academy/consistency-models/session"
)

// Store routes writes to the leader and reads to a random replica.
type Store struct {
	Leader   session.Leader
	Replicas []session.Replica
	Rand     *rand.Rand
}

// Put writes through the leader and forgets the version it got back.
func (s *Store) Put(ctx context.Context, key, value string) error {
	_, err := s.Leader.Put(ctx, key, value, 0)
	return err
}

// Get reads from any replica, however far behind it is.
func (s *Store) Get(ctx context.Context, key string) (string, error) {
	r := s.Replicas[s.Rand.IntN(len(s.Replicas))]
	v, _, err := r.Get(ctx, key)
	return v, err
}

After: a session-guarantee client with version tokens ​

The client keeps a Token{Write, Read}: the highest log position it wrote and the highest it has read. A replica serves the read only if it has applied at least the floor required by the enabled guarantees; otherwise the client waits up to MaxWait or reads the leader. The token encodes as "w.r", so it can travel in a cookie or header across application servers.

go
// Package session layers Terry et al.'s session guarantees (read-your-writes,
// monotonic reads, writes-follow-reads, monotonic writes) on top of a
// single-leader store with asynchronously replicated followers. The client
// carries a version token: the highest log position it wrote and the highest
// position it has read. A replica may serve a read only if it has applied at
// least that position; otherwise the client waits briefly or goes to the leader.
//
// The version is a position in the leader's replication log: a PostgreSQL
// LSN, a MySQL GTID set, a MongoDB operationTime or a Raft index all play this
// role in real systems.
package session

import (
	"context"
	"errors"
	"fmt"
	"strconv"
	"strings"
	"time"
)

// Version is a position in the leader's log. Larger means "includes more writes".
type Version uint64

// Replica can report how far it has applied the log and serve reads.
type Replica interface {
	Name() string
	Applied(ctx context.Context) (Version, error)
	// Get returns the value and the applied position the read was served at.
	Get(ctx context.Context, key string) (value string, asOf Version, err error)
}

// Leader accepts writes. after is the client's dependency: the leader must not
// order the write before it (trivial for one leader; real work for multi-leader).
type Leader interface {
	Replica
	Put(ctx context.Context, key, value string, after Version) (Version, error)
}

// Guarantee is a bit set of session guarantees.
type Guarantee uint8

const (
	ReadYourWrites Guarantee = 1 << iota
	MonotonicReads
	WritesFollowReads
	MonotonicWrites
	All = ReadYourWrites | MonotonicReads | WritesFollowReads | MonotonicWrites
)

// Token is the session state. It is small enough to live in a cookie, an
// HTTP header or a server-side session, so the guarantee survives load
// balancing across application servers.
type Token struct {
	Write Version // highest version this session wrote
	Read  Version // highest version this session observed
}

// Encode renders the token as "w.r", e.g. for a header value.
func (t Token) Encode() string { return fmt.Sprintf("%d.%d", t.Write, t.Read) }

// DecodeToken parses Encode's output. An empty string is the zero token.
func DecodeToken(s string) (Token, error) {
	if s == "" {
		return Token{}, nil
	}
	w, r, ok := strings.Cut(s, ".")
	if !ok {
		return Token{}, errors.New("session: malformed token")
	}
	wv, err := strconv.ParseUint(w, 10, 64)
	if err != nil {
		return Token{}, fmt.Errorf("session: write part: %w", err)
	}
	rv, err := strconv.ParseUint(r, 10, 64)
	if err != nil {
		return Token{}, fmt.Errorf("session: read part: %w", err)
	}
	return Token{Write: Version(wv), Read: Version(rv)}, nil
}

// Stats counts where reads were served, for dashboards and the lab.
type Stats struct {
	ReplicaReads  int
	LeaderReads   int // fell back because no replica was fresh enough
	WaitedForLag  int // a replica caught up while we waited
	CheckFailures int // a replica could not report its position
}

// Client routes one session's operations. It is not safe for concurrent use;
// one session is one logical sequence of operations, as in Terry et al.
type Client struct {
	Leader     Leader
	Replicas   []Replica
	Guarantees Guarantee
	MaxWait    time.Duration // how long to wait for a lagging replica; 0 = never wait
	Poll       time.Duration // polling interval while waiting

	Token Token
	Stats Stats
	next  int // round-robin cursor
}

// floor is the minimum applied position a replica needs to serve this session.
func (c *Client) floor() Version {
	var f Version
	if c.Guarantees&ReadYourWrites != 0 && c.Token.Write > f {
		f = c.Token.Write
	}
	if c.Guarantees&MonotonicReads != 0 && c.Token.Read > f {
		f = c.Token.Read
	}
	return f
}

// Get reads key from the first replica that satisfies the session floor.
func (c *Client) Get(ctx context.Context, key string) (string, error) {
	floor := c.floor()
	for range c.Replicas {
		r := c.Replicas[c.next%len(c.Replicas)]
		c.next++
		applied, err := r.Applied(ctx)
		if err != nil {
			c.Stats.CheckFailures++
			continue
		}
		if applied < floor && !c.waitFor(ctx, r, floor) {
			continue
		}
		v, asOf, err := r.Get(ctx, key)
		if err != nil || asOf < floor { // re-check: the read itself is the proof
			continue
		}
		c.Stats.ReplicaReads++
		c.observe(asOf)
		return v, nil
	}
	v, asOf, err := c.Leader.Get(ctx, key)
	if err != nil {
		return "", err
	}
	c.Stats.LeaderReads++
	c.observe(asOf)
	return v, nil
}

func (c *Client) waitFor(ctx context.Context, r Replica, floor Version) bool {
	if c.MaxWait <= 0 {
		return false
	}
	poll := c.Poll
	if poll <= 0 {
		poll = time.Millisecond
	}
	deadline := time.Now().Add(c.MaxWait)
	for time.Now().Before(deadline) {
		select {
		case <-ctx.Done():
			return false
		case <-time.After(poll):
		}
		if applied, err := r.Applied(ctx); err == nil && applied >= floor {
			c.Stats.WaitedForLag++
			return true
		}
	}
	return false
}

func (c *Client) observe(v Version) {
	if v > c.Token.Read {
		c.Token.Read = v
	}
}

// Put writes through the leader, passing the session's dependency so that
// writes-follow-reads and monotonic writes hold even if writes are later
// replicated to other leaders or regions in a different order.
func (c *Client) Put(ctx context.Context, key, value string) error {
	var after Version
	if c.Guarantees&WritesFollowReads != 0 && c.Token.Read > after {
		after = c.Token.Read
	}
	if c.Guarantees&MonotonicWrites != 0 && c.Token.Write > after {
		after = c.Token.Write
	}
	v, err := c.Leader.Put(ctx, key, value, after)
	if err != nil {
		return err
	}
	if v > c.Token.Write {
		c.Token.Write = v
	}
	return nil
}

The in-memory cluster used by the tests and the lab, with followers that apply the log only when told:

go
package session

import (
	"context"
	"fmt"
	"sync"
)

// Cluster is an in-memory single-leader store with followers that apply the
// leader's log only when told to. Tests and the lab use it to create replica
// lag on purpose; it is not a database.
type Cluster struct {
	mu       sync.Mutex
	log      []entry
	leader   *node
	replicas []*node
}

type entry struct{ key, value string }

type node struct {
	c       *Cluster
	name    string
	applied Version
	data    map[string]string
}

// NewCluster creates a leader and n followers, all empty.
func NewCluster(n int) *Cluster {
	c := &Cluster{}
	c.leader = &node{c: c, name: "leader", data: map[string]string{}}
	for i := 0; i < n; i++ {
		c.replicas = append(c.replicas, &node{c: c, name: fmt.Sprintf("replica-%d", i+1), data: map[string]string{}})
	}
	return c
}

// Leader returns the writable node.
func (c *Cluster) Leader() Leader { return leaderNode{c.leader} }

// Replicas returns the followers as read-only replicas.
func (c *Cluster) Replicas() []Replica {
	out := make([]Replica, len(c.replicas))
	for i, r := range c.replicas {
		out[i] = r
	}
	return out
}

// Head is the leader's latest log position.
func (c *Cluster) Head() Version {
	c.mu.Lock()
	defer c.mu.Unlock()
	return Version(len(c.log))
}

// ApplyTo makes follower i apply the log up to position v (never backwards).
func (c *Cluster) ApplyTo(i int, v Version) {
	c.mu.Lock()
	defer c.mu.Unlock()
	r := c.replicas[i]
	if v > Version(len(c.log)) {
		v = Version(len(c.log))
	}
	for r.applied < v {
		e := c.log[r.applied]
		r.data[e.key] = e.value
		r.applied++
	}
}

func (n *node) Name() string { return n.name }

func (n *node) Applied(context.Context) (Version, error) {
	n.c.mu.Lock()
	defer n.c.mu.Unlock()
	return n.applied, nil
}

func (n *node) Get(_ context.Context, key string) (string, Version, error) {
	n.c.mu.Lock()
	defer n.c.mu.Unlock()
	return n.data[key], n.applied, nil
}

type leaderNode struct{ *node }

func (l leaderNode) Put(_ context.Context, key, value string, after Version) (Version, error) {
	c := l.c
	c.mu.Lock()
	defer c.mu.Unlock()
	if after > l.applied {
		return 0, fmt.Errorf("session: dependency %d not yet applied on leader (at %d)", after, l.applied)
	}
	c.log = append(c.log, entry{key, value})
	l.data[key] = value
	l.applied = Version(len(c.log))
	return l.applied, nil
}
go
package session

import (
	"context"
	"testing"
	"time"
)

func TestReadYourWritesFallsBackToLeaderWhenReplicasLag(t *testing.T) {
	ctx := context.Background()
	cl := NewCluster(2)
	c := &Client{Leader: cl.Leader(), Replicas: cl.Replicas(), Guarantees: All}

	if err := c.Put(ctx, "profile:7:name", "Sara"); err != nil {
		t.Fatal(err)
	}
	// No replica has applied anything yet.
	got, err := c.Get(ctx, "profile:7:name")
	if err != nil || got != "Sara" {
		t.Fatalf("got %q, %v; want Sara from the leader", got, err)
	}
	if c.Stats.LeaderReads != 1 || c.Stats.ReplicaReads != 0 {
		t.Fatalf("stats %+v", c.Stats)
	}
}

func TestReplicaServesOnceCaughtUp(t *testing.T) {
	ctx := context.Background()
	cl := NewCluster(2)
	c := &Client{Leader: cl.Leader(), Replicas: cl.Replicas(), Guarantees: All}
	_ = c.Put(ctx, "k", "v1")
	cl.ApplyTo(1, cl.Head()) // only replica-2 caught up

	got, _ := c.Get(ctx, "k")
	if got != "v1" || c.Stats.ReplicaReads != 1 {
		t.Fatalf("got %q stats %+v; want v1 from replica-2", got, c.Stats)
	}
}

func TestMonotonicReadsNeverGoBackwards(t *testing.T) {
	ctx := context.Background()
	cl := NewCluster(2)
	writer := &Client{Leader: cl.Leader(), Replicas: cl.Replicas(), Guarantees: All}
	_ = writer.Put(ctx, "k", "v1")
	_ = writer.Put(ctx, "k", "v2")
	cl.ApplyTo(0, 2) // replica-1 has v2
	cl.ApplyTo(1, 1) // replica-2 still has v1

	reader := &Client{Leader: cl.Leader(), Replicas: cl.Replicas(), Guarantees: MonotonicReads}
	first, _ := reader.Get(ctx, "k") // replica-1: v2, token.Read = 2
	second, _ := reader.Get(ctx, "k")
	if first != "v2" || second != "v2" {
		t.Fatalf("reads %q then %q; monotonic reads must not return v1 after v2", first, second)
	}

	naive := &Client{Leader: cl.Leader(), Replicas: cl.Replicas()} // no guarantees
	a, _ := naive.Get(ctx, "k")
	b, _ := naive.Get(ctx, "k")
	if a != "v2" || b != "v1" {
		t.Fatalf("naive reads %q then %q; expected the anomaly v2 then v1", a, b)
	}
}

func TestWaitForLaggingReplica(t *testing.T) {
	ctx := context.Background()
	cl := NewCluster(1)
	c := &Client{Leader: cl.Leader(), Replicas: cl.Replicas(), Guarantees: ReadYourWrites,
		MaxWait: 200 * time.Millisecond, Poll: time.Millisecond}
	_ = c.Put(ctx, "k", "v1")
	go func() {
		time.Sleep(5 * time.Millisecond)
		cl.ApplyTo(0, cl.Head())
	}()
	got, _ := c.Get(ctx, "k")
	if got != "v1" || c.Stats.WaitedForLag != 1 || c.Stats.LeaderReads != 0 {
		t.Fatalf("got %q stats %+v; want a replica read after waiting", got, c.Stats)
	}
}

func TestTokenRoundTrip(t *testing.T) {
	tok := Token{Write: 42, Read: 40}
	back, err := DecodeToken(tok.Encode())
	if err != nil || back != tok {
		t.Fatalf("round trip %v -> %q -> %v, %v", tok, tok.Encode(), back, err)
	}
	if _, err := DecodeToken("nonsense"); err == nil {
		t.Fatal("malformed token accepted")
	}
}

func TestTokenCarriedAcrossApplicationServers(t *testing.T) {
	ctx := context.Background()
	cl := NewCluster(1)
	appA := &Client{Leader: cl.Leader(), Replicas: cl.Replicas(), Guarantees: All}
	_ = appA.Put(ctx, "cart:9", "3 items")
	header := appA.Token.Encode() // sent back to the browser

	tok, _ := DecodeToken(header) // next request lands on another server
	appB := &Client{Leader: cl.Leader(), Replicas: cl.Replicas(), Guarantees: All, Token: tok}
	if got, _ := appB.Get(ctx, "cart:9"); got != "3 items" {
		t.Fatalf("got %q; token did not carry the session floor", got)
	}
}

Example: a linearizability checker for a CAS register ​

A small Wing-and-Gong-style search, the algorithm family Knossos and Porcupine implement: choose an operation that may take effect next (for linearizability: no other pending operation returned before it was called; for sequential consistency: the next operation of some client), apply it to the sequential register model, recurse, and memoise (set of linearized operations, register state). Timed-out operations are Pending: they may or may not have taken effect.

go
// Package linearizability checks recorded histories of a single register
// (read, write, compare-and-set) against linearizability and, for contrast,
// sequential consistency. It is a small search in the spirit of Wing & Gong
// and Lowe (the algorithm family Porcupine and Knossos implement): pick an
// operation that may legally take effect next, apply it to the sequential
// model, recurse, and memoise (set of linearized ops, model state) so that the
// same dead end is never explored twice.
package linearizability

import (
	"fmt"
	"math"
	"strings"
)

// Kind is the operation type on the register.
type Kind int

const (
	Read  Kind = iota // returns the current value in Out
	Write             // sets the value to Arg
	CAS               // if value == Arg then value = Arg2; OK reports success
)

// Op is one completed (or pending) operation as a client observed it.
// Call and Return are timestamps from one monotonic clock on the test runner.
type Op struct {
	Client  int
	Kind    Kind
	Arg     int   // Write: new value. CAS: expected value.
	Arg2    int   // CAS: new value.
	Out     int   // Read: value returned.
	OK      bool  // CAS: whether it reported success.
	Call    int64 // invocation time
	Return  int64 // response time; ignored when Pending
	Pending bool  // timed out or crashed: may or may not have taken effect
}

func (o Op) String() string {
	switch o.Kind {
	case Read:
		return fmt.Sprintf("c%d read()=%d", o.Client, o.Out)
	case Write:
		return fmt.Sprintf("c%d write(%d)", o.Client, o.Arg)
	default:
		return fmt.Sprintf("c%d cas(%d->%d)=%v", o.Client, o.Arg, o.Arg2, o.OK)
	}
}

// Result is the verdict. Order is a witness linearization (indices into the
// history) when OK; Longest is the longest legal prefix found when not OK,
// which is where a human starts debugging.
type Result struct {
	OK      bool
	Order   []int
	Longest []int
}

// step applies op to state. It reports the new state and whether the
// observed output is legal for the sequential register.
func step(state int, op Op) (int, bool) {
	switch op.Kind {
	case Read:
		if op.Pending {
			return state, true
		}
		return state, op.Out == state
	case Write:
		return op.Arg, true
	default: // CAS
		if op.Pending { // outcome unknown: take the branch the state allows
			if state == op.Arg {
				return op.Arg2, true
			}
			return state, true
		}
		if state == op.Arg {
			return op.Arg2, op.OK
		}
		return state, !op.OK
	}
}

type candidateFn func(ops []Op, done []bool) []int

// Check reports whether history is linearizable for a register that starts
// at init: some total order exists that respects real time (if a returned
// before b was called, a comes first) and the register's sequential rules.
func Check(init int, history []Op) Result {
	return search(init, history, realTimeCandidates)
}

// CheckSequential reports whether history is sequentially consistent
// (Lamport 1979): some total order exists that respects each client's
// program order, but not real time across clients.
func CheckSequential(init int, history []Op) Result {
	return search(init, history, programOrderCandidates)
}

// realTimeCandidates: an op may go next if no other unlinearized,
// non-pending op returned before it was called.
func realTimeCandidates(ops []Op, done []bool) []int {
	minRet := int64(math.MaxInt64)
	for i, o := range ops {
		if !done[i] && !o.Pending && o.Return < minRet {
			minRet = o.Return
		}
	}
	var c []int
	for i, o := range ops {
		if !done[i] && o.Call <= minRet {
			c = append(c, i)
		}
	}
	return c
}

// programOrderCandidates: the earliest unlinearized op of every client.
func programOrderCandidates(ops []Op, done []bool) []int {
	first := map[int]int{}
	for i, o := range ops {
		if done[i] {
			continue
		}
		if j, ok := first[o.Client]; !ok || o.Call < ops[j].Call {
			first[o.Client] = i
		}
	}
	var c []int
	for i := range ops {
		if j, ok := first[ops[i].Client]; ok && j == i {
			c = append(c, i)
		}
	}
	return c
}

func search(init int, ops []Op, next candidateFn) Result {
	done := make([]bool, len(ops))
	seen := map[string]bool{}
	var order, longest []int

	required := 0
	for _, o := range ops {
		if !o.Pending {
			required++
		}
	}

	var dfs func(state, linearized int) bool
	dfs = func(state, linearized int) bool {
		if linearized == required {
			return true // pending ops may be left out: they never happened
		}
		key := memoKey(done, state)
		if seen[key] {
			return false
		}
		seen[key] = true
		for _, i := range next(ops, done) {
			ns, legal := step(state, ops[i])
			if !legal {
				continue
			}
			done[i] = true
			order = append(order, i)
			if len(order) > len(longest) {
				longest = append(longest[:0], order...)
			}
			add := 1
			if ops[i].Pending {
				add = 0
			}
			if dfs(ns, linearized+add) {
				return true
			}
			order = order[:len(order)-1]
			done[i] = false
		}
		return false
	}

	if dfs(init, 0) {
		return Result{OK: true, Order: append([]int(nil), order...)}
	}
	return Result{OK: false, Longest: longest}
}

func memoKey(done []bool, state int) string {
	var b strings.Builder
	for _, d := range done {
		if d {
			b.WriteByte('1')
		} else {
			b.WriteByte('0')
		}
	}
	fmt.Fprintf(&b, "|%d", state)
	return b.String()
}

// Describe renders an order of op indices for logs and the lab.
func Describe(history []Op, order []int) string {
	parts := make([]string, len(order))
	for k, i := range order {
		parts[k] = history[i].String()
	}
	return strings.Join(parts, " -> ")
}
go
package linearizability

import "testing"

func TestSequentialWriteThenReadIsLinearizable(t *testing.T) {
	h := []Op{
		{Client: 1, Kind: Write, Arg: 1, Call: 0, Return: 10},
		{Client: 2, Kind: Read, Out: 1, Call: 20, Return: 30},
	}
	if r := Check(0, h); !r.OK {
		t.Fatalf("want linearizable, longest prefix %v", r.Longest)
	}
}

// The classic stale read: the write returned before the read was called,
// yet the read saw the old value. A lagging replica produces exactly this.
func TestStaleReadAfterCompletedWriteIsNotLinearizable(t *testing.T) {
	h := []Op{
		{Client: 1, Kind: Write, Arg: 1, Call: 0, Return: 10},
		{Client: 2, Kind: Read, Out: 0, Call: 20, Return: 30},
	}
	if Check(0, h).OK {
		t.Fatal("stale read accepted as linearizable")
	}
	// Sequential consistency has no real-time rule: client 2's read may be
	// ordered before client 1's write.
	if !CheckSequential(0, h).OK {
		t.Fatal("history should be sequentially consistent")
	}
}

// During a slow write, two reads that do not overlap each other must not go
// "back in time": once one read saw 1, a later read may not see 0.
func TestNewThenOldDuringConcurrentWriteIsNotLinearizable(t *testing.T) {
	h := []Op{
		{Client: 1, Kind: Write, Arg: 1, Call: 0, Return: 100},
		{Client: 2, Kind: Read, Out: 1, Call: 10, Return: 20},
		{Client: 3, Kind: Read, Out: 0, Call: 30, Return: 40},
	}
	if Check(0, h).OK {
		t.Fatal("new-then-old accepted")
	}
}

func TestOldThenNewDuringConcurrentWriteIsLinearizable(t *testing.T) {
	h := []Op{
		{Client: 1, Kind: Write, Arg: 1, Call: 0, Return: 100},
		{Client: 2, Kind: Read, Out: 0, Call: 10, Return: 20},
		{Client: 3, Kind: Read, Out: 1, Call: 30, Return: 40},
	}
	r := Check(0, h)
	if !r.OK {
		t.Fatal("old-then-new rejected")
	}
	if got := Describe(h, r.Order); got != "c2 read()=0 -> c1 write(1) -> c3 read()=1" {
		t.Fatalf("unexpected witness %q", got)
	}
}

// Two concurrent compare-and-set calls from 0 to their own id cannot both win.
func TestTwoWinningCASIsNotLinearizable(t *testing.T) {
	h := []Op{
		{Client: 1, Kind: CAS, Arg: 0, Arg2: 1, OK: true, Call: 0, Return: 50},
		{Client: 2, Kind: CAS, Arg: 0, Arg2: 2, OK: true, Call: 10, Return: 60},
	}
	if Check(0, h).OK {
		t.Fatal("two CAS winners accepted")
	}
	h[1].OK = false
	h = append(h, Op{Client: 3, Kind: Read, Out: 1, Call: 70, Return: 80})
	if !Check(0, h).OK {
		t.Fatal("one winner plus a consistent read rejected")
	}
}

// A write that timed out may or may not have happened; both outcomes are legal.
func TestPendingWriteMayOrMayNotTakeEffect(t *testing.T) {
	for _, seen := range []int{0, 1} {
		h := []Op{
			{Client: 1, Kind: Write, Arg: 1, Call: 0, Pending: true},
			{Client: 2, Kind: Read, Out: seen, Call: 20, Return: 30},
		}
		if !Check(0, h).OK {
			t.Fatalf("pending write, read %d rejected", seen)
		}
	}
	// But once a later read saw it, an even later read cannot un-see it.
	h := []Op{
		{Client: 1, Kind: Write, Arg: 1, Call: 0, Pending: true},
		{Client: 2, Kind: Read, Out: 1, Call: 20, Return: 30},
		{Client: 2, Kind: Read, Out: 0, Call: 40, Return: 50},
	}
	if Check(0, h).OK {
		t.Fatal("pending write seen then unseen accepted")
	}
}

// Sequential consistency still forbids a client seeing its own writes undone.
func TestSequentialConsistencyKeepsProgramOrder(t *testing.T) {
	h := []Op{
		{Client: 1, Kind: Write, Arg: 1, Call: 0, Return: 10},
		{Client: 1, Kind: Read, Out: 0, Call: 20, Return: 30},
	}
	if CheckSequential(0, h).OK {
		t.Fatal("client read its own write undone")
	}
}

func BenchmarkCheck20Ops(b *testing.B) {
	var h []Op
	for i := 0; i < 10; i++ {
		t := int64(i * 10)
		h = append(h,
			Op{Client: 1, Kind: Write, Arg: i + 1, Call: t, Return: t + 15},
			Op{Client: 2, Kind: Read, Out: i, Call: t + 1, Return: t + 9},
		)
	}
	for b.Loop() {
		if !Check(0, h).OK {
			b.Fatal("expected linearizable")
		}
	}
}

Example: hybrid logical clock ​

go
// Package hlc is a hybrid logical clock (Kulkarni, Demirbas et al. 2014), the
// timestamp scheme CockroachDB uses. A timestamp is the largest
// physical time seen so far plus a logical counter that breaks ties. It stays
// close to wall-clock time, never goes backwards, and preserves Lamport's
// happened-before: if a sends a message that b receives, ts(a) < ts(b).
package hlc

import (
	"fmt"
	"sync"
	"time"
)

// Timestamp orders by Wall, then Logical.
type Timestamp struct {
	Wall    int64 // nanoseconds since the Unix epoch
	Logical uint32
}

// Less reports whether t is before u.
func (t Timestamp) Less(u Timestamp) bool {
	return t.Wall < u.Wall || (t.Wall == u.Wall && t.Logical < u.Logical)
}

func (t Timestamp) String() string { return fmt.Sprintf("%d.%d", t.Wall, t.Logical) }

// Clock is safe for concurrent use.
type Clock struct {
	mu        sync.Mutex
	physical  func() int64
	last      Timestamp
	maxOffset time.Duration
}

// ErrClockOffset reports a remote timestamp too far ahead of local physical
// time. CockroachDB treats the analogous condition (--max-offset, default
// 500ms) as fatal for the node, because past that bound its uncertainty
// interval no longer protects reads.
type ErrClockOffset struct{ Remote, Local int64 }

func (e ErrClockOffset) Error() string {
	return fmt.Sprintf("hlc: remote clock %v ahead of local", time.Duration(e.Remote-e.Local))
}

// New returns a clock reading physical time from now (nil = time.Now) that
// rejects remote timestamps more than maxOffset ahead (0 = no check).
func New(now func() int64, maxOffset time.Duration) *Clock {
	if now == nil {
		now = func() int64 { return time.Now().UnixNano() }
	}
	return &Clock{physical: now, maxOffset: maxOffset}
}

// Now returns a timestamp for a local or send event.
func (c *Clock) Now() Timestamp {
	c.mu.Lock()
	defer c.mu.Unlock()
	pt := c.physical()
	if pt > c.last.Wall {
		c.last = Timestamp{Wall: pt}
	} else {
		c.last.Logical++ // physical clock stalled or went backwards
	}
	return c.last
}

// Update merges a timestamp received from another node and returns the
// timestamp of the receive event, which is after both.
func (c *Clock) Update(remote Timestamp) (Timestamp, error) {
	c.mu.Lock()
	defer c.mu.Unlock()
	pt := c.physical()
	if c.maxOffset > 0 && remote.Wall-pt > int64(c.maxOffset) {
		return c.last, ErrClockOffset{Remote: remote.Wall, Local: pt}
	}
	switch {
	case pt > c.last.Wall && pt > remote.Wall:
		c.last = Timestamp{Wall: pt}
	case remote.Wall > c.last.Wall:
		c.last = Timestamp{Wall: remote.Wall, Logical: remote.Logical + 1}
	case c.last.Wall > remote.Wall:
		c.last.Logical++
	default: // equal walls
		c.last.Logical = max(c.last.Logical, remote.Logical) + 1
	}
	return c.last, nil
}

The Go angle ​

  • Porcupine (github.com/anishathalye/porcupine) is the production-grade version of the checker above: "Porcupine is a fast linearizability checker used in both academia and industry", taking "a sequential specification as executable Go code, along with a concurrent history". It implements P-compositionality (check each key separately) and renders an HTML visualisation of linearization points; its README notes that "etcd uses Porcupine's linearizability checker and visualizer in its robustness tests".
  • Recording histories: take Call and Return from time.Now() (monotonic clock reading inside Go's time.Time) on the test runner, never from the servers' clocks.
  • go.etcd.io/etcd/client/v3: reads are linearizable by default; clientv3.WithSerializable() makes them local and possibly stale. CAS is Txn(ctx).If(clientv3.Compare(clientv3.ModRevision(k), "=", rev)).Then(...).
  • go.mongodb.org/mongo-driver/v2: options.Session().SetCausalConsistency(true) with readconcern.Majority() and writeconcern.Majority(); pass sess.OperationTime() between processes with AdvanceOperationTime.
  • database/sql + pgx: two *sql.DB pools (primary, replicas) plus the token check SELECT pg_last_wal_replay_lsn() >= $1::pg_lsn is all the session client needs on PostgreSQL.
  • Go's own memory model is a consistency model too: the Go memory model calls its guarantee "DRF-SC: data-race-free programs execute in a sequentially consistent manner", and specifies sync/atomic with "the same semantics as C++’s sequentially consistent atomics".

Laravel ​

Before ​

Read/write split, and the redirect after a write reads from a replica.

php
<?php

namespace App\Http\Controllers;

use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\View\View;

/**
 * Before: read/write split without any session guarantee.
 *
 * The update goes to the primary. The redirect is a NEW request, so the
 * per-request 'sticky' flag is gone and show() reads from a replica that may
 * not have replayed the update yet: the user sees the old name.
 */
class ProfileController
{
    public function update(Request $request, int $id): RedirectResponse
    {
        DB::table('profiles')->where('id', $id)->update([
            'display_name' => (string) $request->input('display_name'),
            'updated_at' => now(),
        ]);

        return redirect()->route('profiles.show', $id);
    }

    public function show(int $id): View
    {
        $profile = DB::table('profiles')->where('id', $id)->first(); // any replica

        return view('profiles.show', ['profile' => $profile]);
    }
}

After ​

1. The connection. Laravel 13 lets one connection have read and write hosts; sticky sends reads to the write connection after a write in the same request:

php
<?php

// config/database.php (excerpt): one logical PostgreSQL connection with a
// write host (primary) and read hosts (streaming-replication standbys).
// Laravel picks one read host at random per request.

return [
    'default' => env('DB_CONNECTION', 'pgsql'),

    'connections' => [
        'pgsql' => [
            'driver' => 'pgsql',
            'read' => [
                'host' => explode(',', env('DB_READ_HOSTS', '127.0.0.1')),
            ],
            'write' => [
                'host' => [env('DB_WRITE_HOST', '127.0.0.1')],
            ],
            // After a write in THIS request, later reads in this request use
            // the write connection. It does nothing for the next request.
            'sticky' => true,

            'port' => env('DB_PORT', '5432'),
            'database' => env('DB_DATABASE', 'app'),
            'username' => env('DB_USERNAME', 'app'),
            'password' => env('DB_PASSWORD', ''),
            'charset' => 'utf8',
            'prefix' => '',
            'search_path' => 'public',
            'sslmode' => 'prefer',
        ],
    ],
];

The Laravel docs are explicit about its scope: "If the sticky option is enabled and a "write" operation has been performed against the database during the current request cycle, any further "read" operations will use the "write" connection." The redirect is a new request.

2. Across requests, by time window (built in). Illuminate\Foundation\Http\Middleware\PreventStaleDatabaseReads stores the time of the last write in the session; "By default, requests within two seconds of a write will use the write connection for reads on that connection." PreventStaleDatabaseReads::for(5) widens the window. It is simple, but it is a guess: wrong if lag exceeds the window, wasteful if replicas are 5 ms behind.

php
<?php

use App\Http\Middleware\ReadYourWritesLsn;
use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
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 {
        // Option A (built in, time window): for 5 s after this session wrote,
        // read from the write connection. Simple; wrong if lag exceeds 5 s,
        // wasteful if replicas catch up in 5 ms.
        $middleware->web(append: [
            PreventStaleDatabaseReads::for(5),
        ]);

        // Option B (version token): compare the session's last commit LSN with
        // what the chosen replica has replayed. Use A or B, not both.
        // $middleware->web(append: [ReadYourWritesLsn::class]);
    })
    ->withExceptions(function (Exceptions $exceptions): void {
        //
    })->create();

3. Across requests, by version token (exact). Store the primary's LSN after a write; on the next request, ask the replica Laravel chose for this request (one random read host per request) whether it has replayed that LSN; if not, call useWriteConnectionWhenReading() for the rest of the request. The middleware uses hasModifiedRecords(), the same flag the built-in middleware reads.

php
<?php

namespace App\Http\Middleware;

use App\Consistency\ReplicaLsn;
use Closure;
use Illuminate\Database\DatabaseManager;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

/**
 * Read-your-writes and monotonic reads across requests with a version token.
 *
 * After a request that wrote, store the primary's WAL position (LSN) in the
 * session. On the next request, ask the replica Laravel chose for this
 * request whether it has replayed that position; if not, send this request's
 * reads to the primary. Unlike a fixed time window, this is exact: it costs
 * one tiny query and never reads stale, however large the lag is.
 *
 * Must run after StartSession (append it to the 'web' group).
 */
class ReadYourWritesLsn
{
    public function __construct(
        private DatabaseManager $db,
        private ReplicaLsn $lsn,
    ) {}

    public function handle(Request $request, Closure $next, string $connection = 'pgsql'): Response
    {
        $conn = $this->db->connection($connection);
        $token = $request->session()->get(ReplicaLsn::SESSION_KEY);

        if (is_string($token) && ! $this->lsn->replicaHasReplayed($conn, $token)) {
            $conn->useWriteConnectionWhenReading();
        }

        $response = $next($request);

        if ($conn->hasModifiedRecords()) {
            $request->session()->put(ReplicaLsn::SESSION_KEY, $this->lsn->primaryPosition($conn));
        }

        return $response;
    }
}
php
<?php

namespace App\Consistency;

use Illuminate\Database\Connection;

/**
 * PostgreSQL WAL positions as session version tokens.
 */
class ReplicaLsn
{
    public const SESSION_KEY = '_pg_write_lsn';

    /** The primary's current WAL write position, e.g. "0/3000148". */
    public function primaryPosition(Connection $conn): string
    {
        $row = $conn->selectFromWriteConnection('select pg_current_wal_lsn()::text as lsn');

        return $row[0]->lsn;
    }

    /**
     * True if the read connection for this request has replayed $lsn.
     * pg_last_wal_replay_lsn() is NULL on a primary, which has everything.
     */
    public function replicaHasReplayed(Connection $conn, string $lsn): bool
    {
        $row = $conn->selectOne(
            'select coalesce(pg_last_wal_replay_lsn() >= ?::pg_lsn, true) as ok',
            [$lsn],
        );

        return (bool) $row->ok;
    }
}

4. MongoDB causal consistency. With mongodb/laravel-mongodb, DB::connection('mongodb')->getClient() returns the MongoDB\Client; startSession(['causalConsistency' => true]) plus majority read and write concern give all four session guarantees even when reading secondaries. Across requests, carry operationTime and call advanceOperationTime().

php
<?php

namespace App\Mongo;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use MongoDB\BSON\Timestamp;
use MongoDB\Collection;
use MongoDB\Driver\ReadConcern;
use MongoDB\Driver\ReadPreference;
use MongoDB\Driver\Session;
use MongoDB\Driver\WriteConcern;

/**
 * MongoDB causal consistency from Laravel (mongodb/laravel-mongodb).
 *
 * Inside one causally consistent session, with "majority" read and write
 * concern, MongoDB guarantees read-your-writes, monotonic reads, monotonic
 * writes and writes-follow-reads, even when reads go to secondaries.
 * Across HTTP requests the session object is gone, so we carry its
 * operationTime in the Laravel session and advance the next session to it.
 */
class CausalProfileStore
{
    private const OP_TIME = '_mongo_operation_time';

    public function rename(Request $request, string $id, string $name): ?array
    {
        $session = $this->session($request);
        $profiles = $this->profiles();

        $profiles->updateOne(['_id' => $id], ['$set' => ['name' => $name]], ['session' => $session]);
        // Reads from a secondary, yet is guaranteed to see the update above.
        $doc = $profiles->findOne(['_id' => $id], ['session' => $session]);

        $this->remember($request, $session);
        $session->endSession();

        return $doc;
    }

    public function find(Request $request, string $id): ?array
    {
        $session = $this->session($request);
        $doc = $this->profiles()->findOne(['_id' => $id], ['session' => $session]);
        $this->remember($request, $session);
        $session->endSession();

        return $doc;
    }

    private function session(Request $request): Session
    {
        $client = DB::connection('mongodb')->getClient();
        $session = $client->startSession(['causalConsistency' => true]);

        $saved = $request->session()->get(self::OP_TIME);
        if (is_array($saved)) {
            // Timestamp(increment, timestamp). On a sharded cluster, also copy
            // the cluster time with $session->advanceClusterTime().
            $session->advanceOperationTime(new Timestamp($saved[1], $saved[0]));
        }

        return $session;
    }

    private function remember(Request $request, Session $session): void
    {
        $t = $session->getOperationTime();
        if ($t instanceof Timestamp) {
            $request->session()->put(self::OP_TIME, [$t->getTimestamp(), $t->getIncrement()]);
        }
    }

    private function profiles(): Collection
    {
        $client = DB::connection('mongodb')->getClient();

        return $client->selectCollection(config('database.connections.mongodb.database'), 'profiles', [
            'readConcern' => new ReadConcern(ReadConcern::MAJORITY),
            'writeConcern' => new WriteConcern(WriteConcern::MAJORITY),
            'readPreference' => new ReadPreference(ReadPreference::SECONDARY_PREFERRED),
            'typeMap' => ['root' => 'array', 'document' => 'array', 'array' => 'array'],
        ]);
    }
}

The Laravel angle ​

  • DB::withoutAffectingStickiness(fn () => ...) performs a write that does not switch the request's reads to the primary (job heartbeats, audit timestamps), documented in the 13.x database page.
  • ->useWritePdo() on a query builder forces one query to the primary; DB::connection()->useWriteConnectionWhenReading() does it for the rest of the request; reads inside DB::transaction() always use the write PDO.
  • Queued jobs dispatched after a write may run on a worker that reads a replica; dispatch with ->afterCommit() and pass the token (or the model ID plus useWritePdo()) so the job does not read the pre-write state.
  • Cache is a replica too: Cache::remember() after an update serves the old value until TTL unless you Cache::forget() inside the same flow (Caching).
  • Octane workers keep the application in memory across requests; keep any token you add in the request or session, never in a static property.

Solving the classic problems ​

"I saved my profile and the old one came back" ​

SolutionHowAdvantageCost / limitation
Read your own data from the primaryRoute /me/* reads to the primaryTrivialPrimary load grows with active users
Time windowLaravel PreventStaleDatabaseReads::for(n)Built in, one lineGuess; breaks when lag exceeds n
Version tokenLSN/GTID/operationTime in session; replica checkExact; replicas still serve most readsOne extra tiny query; token plumbing
Synchronous applyPostgreSQL remote_applyNo app changesEvery commit waits for replay
Optimistic UIShow the submitted value client-sideInstant UXNot a data guarantee; other tabs still stale

"Two people booked the last seat" ​

Linearizable CAS on one key. SQL with a unique constraint on the primary, Cassandra LWT, or DynamoDB conditional write:

sql
-- PostgreSQL (primary): the unique index is the CAS
CREATE UNIQUE INDEX seats_one_holder ON seat_holds (event_id, seat);
INSERT INTO seat_holds (event_id, seat, user_id) VALUES (1, 'A12', 7)
ON CONFLICT DO NOTHING RETURNING user_id;   -- no row returned = someone else won

For DynamoDB the same is PutItem with ConditionExpression: attribute_not_exists(pk); for Cassandra, INSERT ... IF NOT EXISTS and read [applied]. Never check on a replica and write on the primary.

"A reply appeared before the message it answers" ​

Causal consistency: MongoDB causally consistent sessions, or carry the parent's version with the reply and have the reader hold back (or fetch) the parent until it is visible. In event pipelines, key by conversation ID so one partition preserves order.

"A comment appears, then disappears on refresh" ​

Monotonic reads: pin the session to one replica (consistent hashing on user ID), or keep token.Read and refuse replicas behind it. This is the second guarantee the Go client enforces.

"Clock skew reordered our writes" ​

SolutionHowAdvantageCost
HLC timestampsMerge remote timestamps on receiveCausal order with near-physical timeStill needs a skew bound for real-time claims
Version vectorsDetect concurrency, keep siblingsNo lost updateApplication merge
Server-assigned orderOne leader or log assigns orderSimpleLeader on the write path
Bounded skew + crashCockroachDB --max-offset behaviourSafety preservedNodes stop under bad NTP

"Our 'strongly consistent' read was stale after failover" ​

Use the product's linearizable read path (etcd default, MongoDB linearizable, ReadIndex), majority writes, and fencing tokens for anything that acts on the result (Distributed Locking).

Testing consistency ​

ToolChecksInputNotes
JepsenWhole systems under partitions, clock skew, crashesReal cluster + nemesisProduces histories; uses Knossos or Elle to judge them
KnossosLinearizability of single-object historiesinvoke/ok/fail/info events"attempts to show that the history is not linearizable" with respect to a model; exponential in concurrency
ElleTransactional isolation (G0, G1a/b/c, G2, write skew, lost update)List-append or register transactions"Elle is a transactional consistency checker for black-box databases"; "~linear in history length"
PorcupineLinearizability, Go specsGo Operation or Event slicesFaster than Knossos on Jepsen test data; visualiser
This page's checkerLinearizable vs sequential, register with CASGo Op slicesTeaching tool; tests show each anomaly

Knossos's event types are the vocabulary of every history: an operation has an invoke and a completion that is "either ok if the operation took place, fail if the operation did not take place, or info if you're not sure what happened, e.g. the operation timed out." Treat info as Pending (it may have happened at any time after invocation), which is why a timed-out write can explain a later read.

Choosing ​

Feature / workloadModel neededHow to get itWhat the user sees if weaker
Username or email claimLinearizable CASUnique index on primary, LWT, conditional writeTwo accounts with the same name
Last-seat booking, flash-sale stockLinearizable CAS or serializable txnON CONFLICT, IF, ConditionExpression, SERIALIZABLE + retryOversell
Money transfer + confirmation pageStrict serializable on that pathPrimary / Spanner / leaseholder read after commit"Transfer done" and old balance
Leader election, locksLinearizable + fencingetcd, DynamoDB conditional writesTwo leaders
Profile, settings, own postsRead-your-writes + monotonic readsVersion token, Laravel middleware, MongoDB sessionEdits "revert"
Comments, chat threadsCausalCausal sessions, per-conversation partitionReply before question
Feeds, timelines of othersEventual + monotonic readsReplicas, caches, pinned replicaItems flicker
Counters, likes, viewsEventual / strong eventualCRDT counters, sharded countersNumbers off by a few for seconds
Search, recommendationsEventualAsync indexingNew item missing for seconds
Analytics, reportsSnapshot at a timestampAS OF SYSTEM TIME, replicas, warehouseSlightly old totals (label them)
Multi-region active-active writesCausal+ or CRDT, or strict via Spanner/MRSCPick per entityConflicts or high write latency

UX implication rule: every weaker model needs a sentence in the UI spec: "after saving, the page reads from the primary", "counts may be a few seconds old", "pending" states for async work. If you cannot write the sentence, you need the stronger model.

In architecture: from a single process to a distributed system ​

Monolith: one process, one database ​

One PostgreSQL primary, no replicas: every read is linearizable and every transaction strict serializable at SERIALIZABLE (one clock, one WAL). Consistency problems here are isolation problems (Isolation Levels). Example: a Laravel shop with one database; the only consistency choice is the isolation level of checkout.

Modular monolith: boundaries without the network ​

Modules own their tables but share the database, so cross-module reads are still consistent if they run in one transaction. The first weakening arrives with a cache or a search index per module: each one is an eventually consistent replica. Example: the catalogue module writes products; the search module reads an Elasticsearch index fed by an outbox, and the product page reads the database while the listing reads search, so define which page may be stale.

Microservices: consistency stops at the service boundary ​

Each service has its own database; between services there is no shared transaction, so cross-service state is eventually consistent by construction (sagas, outbox, events: see Saga and Outbox). What you can still give users is session guarantees and causality through tokens:

text
     Browser             Orders service            Payments service           Order page (BFF)
1    POST /orders ->     commit order (LSN o1)
2                        emit OrderPlaced via outbox
3                                                  charge, commit (LSN p7)
4    <- 201 + token {orders: o1}
5    GET /orders/1 ->                                                         reads Orders replica: replayed >= o1 ? else primary
6                                                                             payment status may be "pending": UI says so

Distributed data: replicas, caches, sharded and multi-region ​

Read replicas give eventual consistency plus whatever session layer you add; caches are replicas with TTL; sharded SQL (Citus, Vitess) is linearizable per shard but cross-shard reads need a distributed snapshot; distributed SQL (CockroachDB, Spanner) moves the consistency work into the database with consensus and clocks. Multi-region forces the PACELC choice per table: CockroachDB REGIONAL BY ROW and global tables, Spanner multi-region configurations, DynamoDB MREC vs MRSC. Replication wiring is in Replication Topologies.

Scaling path: 1x, 10x, 100x ​

LoadWhat changesExample
1xOne primary; everything strictLaravel + PostgreSQL, no replicas
10xRead replicas + session tokens; caches with explicit staleness; linearizable CAS stays on the primary2-4 standbys, ReadYourWritesLsn, Redis cache with TTL
100xPer-feature models: CRDT counters, causal sessions for social data, distributed SQL or Spanner for money, follower reads for analytics, multi-region with chosen trade-offs; Jepsen/Elle tests in CI for the claims you rely onCockroachDB multi-region + Kafka + Redis Enterprise Active-Active

Lab: check histories and measure stale reads ​

Single-process Go, no network, no containers. Runs in about a second.

go
// Command lab runs the two experiments of the consistency-models chapter in
// one process, with fixed seeds so the output is reproducible:
//
//  1. three register histories through the linearizability and
//     sequential-consistency checkers;
//  2. 1,000 "save profile, then show profile" sessions against a leader with
//     two lagging followers, read naively and through the session client.
package main

import (
	"context"
	"fmt"
	"math/rand/v2"

	"academy/consistency-models/before"
	lin "academy/consistency-models/linearizability"
	"academy/consistency-models/session"
)

func main() {
	histories()
	sessions()
}

func histories() {
	cases := []struct {
		name string
		h    []lin.Op
	}{
		{"stale read after completed write", []lin.Op{
			{Client: 1, Kind: lin.Write, Arg: 1, Call: 0, Return: 10},
			{Client: 2, Kind: lin.Read, Out: 0, Call: 20, Return: 30},
		}},
		{"new-then-old during a slow write", []lin.Op{
			{Client: 1, Kind: lin.Write, Arg: 1, Call: 0, Return: 100},
			{Client: 2, Kind: lin.Read, Out: 1, Call: 10, Return: 20},
			{Client: 3, Kind: lin.Read, Out: 0, Call: 30, Return: 40},
		}},
		{"old-then-new during a slow write", []lin.Op{
			{Client: 1, Kind: lin.Write, Arg: 1, Call: 0, Return: 100},
			{Client: 2, Kind: lin.Read, Out: 0, Call: 10, Return: 20},
			{Client: 3, Kind: lin.Read, Out: 1, Call: 30, Return: 40},
		}},
	}
	for _, c := range cases {
		l := lin.Check(0, c.h)
		s := lin.CheckSequential(0, c.h)
		fmt.Printf("%-34s linearizable=%-5v sequential=%v\n", c.name, l.OK, s.OK)
		if l.OK {
			fmt.Printf("  witness: %s\n", lin.Describe(c.h, l.Order))
		} else {
			fmt.Printf("  longest legal prefix: %s\n", lin.Describe(c.h, l.Longest))
		}
	}
}

func sessions() {
	const n = 1000
	ctx := context.Background()
	rng := rand.New(rand.NewPCG(7, 7))

	run := func(name string, put func(k, v string) error, get func(k string) (string, error), cl *session.Cluster) {
		stale := 0
		for i := 0; i < n; i++ {
			key := fmt.Sprintf("profile:%d", i%50)
			want := fmt.Sprintf("v%d", i)
			if err := put(key, want); err != nil {
				panic(err)
			}
			// Each follower applies the log up to a random point: lag of 0-3 writes.
			for r := 0; r < 2; r++ {
				head := cl.Head()
				lag := session.Version(rng.IntN(4))
				if lag > head {
					lag = head
				}
				cl.ApplyTo(r, head-lag)
			}
			got, err := get(key)
			if err != nil {
				panic(err)
			}
			if got != want {
				stale++
			}
		}
		fmt.Printf("%-28s stale reads %4d / %d\n", name, stale, n)
	}

	cl1 := session.NewCluster(2)
	naive := &before.Store{Leader: cl1.Leader(), Replicas: cl1.Replicas(), Rand: rand.New(rand.NewPCG(1, 1))}
	run("before: any replica", func(k, v string) error { return naive.Put(ctx, k, v) },
		func(k string) (string, error) { return naive.Get(ctx, k) }, cl1)

	cl2 := session.NewCluster(2)
	c := &session.Client{Leader: cl2.Leader(), Replicas: cl2.Replicas(), Guarantees: session.All}
	run("after: session token", func(k, v string) error { return c.Put(ctx, k, v) },
		func(k string) (string, error) { return c.Get(ctx, k) }, cl2)
	fmt.Printf("  served by replicas %d, by leader %d (fallback)\n", c.Stats.ReplicaReads, c.Stats.LeaderReads)
}
bash
cd docs/snippets/system-design/consistency-models/go
go vet ./... && go test ./...
go run ./cmd/lab

Output from an actual run on the author's machine (Go 1.27, seeds fixed in the program):

text
stale read after completed write   linearizable=false sequential=true
  longest legal prefix: c1 write(1)
new-then-old during a slow write   linearizable=false sequential=true
  longest legal prefix: c1 write(1) -> c2 read()=1
old-then-new during a slow write   linearizable=true  sequential=true
  witness: c2 read()=0 -> c1 write(1) -> c3 read()=1
before: any replica          stale reads  750 / 1000
after: session token         stale reads    0 / 1000
  served by replicas 450, by leader 550 (fallback)

Experiments.

  1. Read the three verdicts against the timeline diagram: the first two are sequentially consistent but not linearizable; only real time separates them.
  2. Change the lag in sessions() from rng.IntN(4) to rng.IntN(2): the naive store's stale reads drop to about half, and the session client's replica share rises; it stays at 0 stale.
  3. Set Guarantees: session.MonotonicReads only: stale reads reappear (read-your-writes is no longer enforced), but TestMonotonicReadsNeverGoBackwards still passes.
  4. Add a pending write to a history in checker_test.go and confirm that both "seen" and "not seen" are accepted, but "seen then unseen" is not.
  5. PostgreSQL version (expected, not run): start a primary and one streaming standby, SELECT pg_current_wal_lsn(); after an UPDATE on the primary, then on the standby SELECT pg_last_wal_replay_lsn() >= '<lsn>'::pg_lsn; returns t within milliseconds normally, and f after SELECT pg_wal_replay_pause(); until SELECT pg_wal_replay_resume();.

Common misconceptions ​

BeliefReality
"Strong consistency" is one levelIt may mean linearizable, read-from-leader, serializable or external consistency; ask which
Serializable implies linearizableNo real-time rule in serializability; strict serializability adds it
Linearizable keys give safe transactionsTwo linearizable keys still allow write skew; you need serializability for multi-key invariants
Quorum reads and writes (R + W > N) are linearizableNot with sloppy quorums, concurrent writes ordered by timestamps or no read repair before returning
Synchronous replication means replica reads are freshReceived is not applied; remote_apply (PostgreSQL) is the setting that waits for visibility
Sticky load-balancer sessions give read-your-writesThey pin the app server, not the replica
Laravel sticky fixes the redirect-after-save problemIt lasts one request; use PreventStaleDatabaseReads or a token
Eventually consistent means "within a second"No time bound in the model; measure lag and alert on it
etcd "serializable" reads are stronger than linearizable onesIn etcd, serializable means local and possibly stale
Redis WAIT makes Redis strongly consistentIts own docs say it does not; failover can still lose acknowledged writes
MongoDB sessions are causal with any concernOnly with majority read concern and majority write concern
NTP makes timestamps safe for orderingNTP gives no hard bound; use HLC, consensus or TrueTime-style intervals
A passing integration test proves linearizabilityOnly a checker over many concurrent histories under faults gives evidence

Cheat sheet ​

TopicRemember
Consistency modelA set of legal histories; a safety property
LinearizableSingle object, real time, behaves like one copy; composable; CAP's C
SequentialOne order, per-process order kept, no real time
CausalCause before effect everywhere; sticky available; causal+ adds convergence
PRAM= RYW + MR + MW; per-writer FIFO
Session guaranteesRYW, MR, MW, WFR (Terry 1994); implement with version tokens
Eventual / strong eventualConverge when writes stop / equal state for equal updates (CRDTs)
SerializableSome serial order of transactions; no real time
Strict serializableSerializable + linearizable = Spanner's external consistency
SI / RCSnapshot per transaction (write skew allowed) / committed data per statement
Linearizable readsReadIndex or log read; lease reads only with bounded clock skew
ClocksLamport (total order), vector (concurrency), HLC (causal + near physical), TrueTime (bounded interval)
CockroachDBSERIALIZABLE; single-key linearizable within --max-offset 500ms
DynamoDBEventual by default; ConsistentRead on table/LSI; MRSC for global tables
CassandraTunable CL; LWT (Paxos) per partition for CAS
TestingKnossos/Porcupine (linearizability), Elle (transactions), Jepsen (faults)

Self-check: questions & answers ​

Show:
  • Must-know asked in almost every interview
  • Important frequent; expected at senior level
  • Good to know extra depth that sets you apart

1 — Client A's write(x=1) returned OK at t=10. Client B's read(x) started at t=20 and returned 0. Which models does this violate: linearizable, sequential, read-your-writes? Must-know ​

Answer

Answer: It violates linearizability (real-time order). It is still sequentially consistent (B's read can be ordered before A's write), and read-your-writes does not apply because the read is by a different client. See Linearizability and the lab.

2 — Why is serializability not enough for "transfer done, now show the balance"? Important ​

Answer

Answer: Serializability lets the database order the later read before the transfer, for example by serving it from a stale snapshot or replica. You need strict serializability (external consistency) on that read path, or a token that forces a fresh read. See Transactional models.

3 — Name the four session guarantees and one user-visible anomaly each prevents. Important ​

Answer

Answer: Read-your-writes (own edit missing), monotonic reads (comment appears then disappears), monotonic writes (second edit applied before the first), writes-follow-reads (reply visible before the message). See Session guarantees.

4 — What does Laravel's sticky option guarantee, and what does PreventStaleDatabaseReads add? Important ​

Answer

Answer: sticky sends reads to the write connection after a write within the same request. PreventStaleDatabaseReads stores the last write time in the session and reads from the write connection for N seconds (default 2) on later requests. A version token replaces the time guess with an exact LSN check. See Laravel.

5 — Two concurrent cas(0 -> 1) and cas(0 -> 2) both return success. Is the history linearizable? Why does it matter? Important ​

Answer

Answer: No: in any total order the second CAS would see the first one's value and fail. This is the double booking or two leaders bug. TestTwoWinningCASIsNotLinearizable encodes it. See Go.

6 — How does a Raft leader serve a linearizable read without writing to the log, and why is a lease read riskier? Good to know ​

Answer

Answer: ReadIndex: it records the commit index, confirms leadership with a heartbeat round to a majority (after committing a no-op in its term), waits until it has applied that index, then reads. A lease read skips the heartbeat round and relies on time; the Raft paper notes it "assumes bounded clock skew". See Consensus reads.

7 — What does CockroachDB guarantee if a node's clock drifts beyond --max-offset, and what does it do about it? Good to know ​

Answer

Answer: Serializability is maintained, but single-key linearizability between causally dependent transactions can be violated. A node whose clock is off from at least half the cluster by 80% of the max offset crashes itself. See Clocks.

8 — Under which conditions does a MongoDB causally consistent session give all four session guarantees? Good to know ​

Answer

Answer: With "majority" read concern and "majority" write concern, and one thread at a time using the session. Across processes, pass operationTime (and cluster time) and advance the new session. See Causal.

9 — Your team uses Cassandra with QUORUM writes and QUORUM reads. Is the username table safe against duplicates? Important ​

Answer

Answer: No. Quorums overlap, so completed writes are visible, but two concurrent inserts are both accepted and ordered by timestamp. Use INSERT ... IF NOT EXISTS (LWT, Paxos) and check [applied]. See Products.

10 — Which tool would you use to check a history of multi-key transactions for write skew, and which for a single register? Good to know ​

Answer

Answer: Elle for transactions (it finds dependency cycles such as G2); Knossos or Porcupine (or this page's checker) for single-object linearizability. See Testing.

Glossary ​

TermMeaning
Consistency modelA set of histories a system may legally produce; a safety property
HistoryOperations with invocation time, response time and result
AnomalyA pattern in a history that a model forbids (stale read, write skew, lost update)
Real-time orderA precedes B if A returned before B was invoked
Single-copy semanticsThe system behaves as if there were one copy of each object
LinearizabilitySingle-object, real-time, atomic; Herlihy and Wing 1990
CAS registerRegister with read, write and compare-and-set; the standard linearizability test object
Sequential consistencyOne total order respecting each process's program order; Lamport 1979
Causal consistencyCausally related operations seen in the same order everywhere
Causal+Causal consistency with convergent conflict handling (COPS)
PRAM / FIFO consistencyEach process's writes seen in its order; = RYW + MR + MW
Eventual consistencyReplicas converge if writes stop; no ordering or time bound
Strong eventual consistencyReplicas with the same delivered updates have the same state (CRDTs)
ConvergenceReplicas reaching identical state via anti-entropy, read repair and merge
Session guaranteesClient-centric guarantees: RYW, MR, MW, WFR (Terry et al. 1994)
Read-your-writesA session's reads reflect its own earlier writes
Monotonic readsA session never reads an older state than it already read
Monotonic writesA session's writes are applied in issue order everywhere
Writes-follow-readsA write is ordered after the writes its session had read
SerializabilityTransactions equivalent to some serial order
Strict serializabilitySerializable in an order consistent with real time
External consistencySpanner's term for strict serializability
Snapshot isolationReads from a start snapshot; first committer wins; allows write skew
Read committedEach read sees only committed data
Lamport clockInteger counter consistent with happened-before
Vector clockOne counter per node; detects concurrency
Hybrid logical clockPhysical time plus logical counter, respects causality
TrueTimeSpanner's clock API returning a bounded interval
Clock skewDifference between two nodes' clocks
Uncertainty windowInterval after a read timestamp where a value's order is unknown (CockroachDB)
Commit waitSpanner waiting until the commit timestamp is certainly past
Lease readLeader read relying on a time-based leadership lease
ReadIndexRaft read that confirms leadership with a heartbeat round first
Quorum readRead from R replicas of N, newest wins
Stale readA read that misses a write that completed before it started
Replica lagHow far a replica's applied state is behind the leader
Sticky connectionReads use the write connection after a write (Laravel sticky)
Version tokenLog position (LSN, GTID, operationTime) carried by a session to bound staleness
LWTCassandra lightweight transaction: Paxos-based CAS per partition
Paxos / RaftConsensus protocols providing a replicated, linearizable log
JepsenFault-injection testing of distributed systems' consistency claims
KnossosJepsen's linearizability checker
ElleJepsen's transactional anomaly checker
PorcupineFast linearizability checker in Go
Linearizability checkerTool that searches for a legal real-time-respecting order of a history

References ​

Built by Morteza Negahi