Consistency models in practice
Linearizable, sequential, causal, read-your-writes, snapshot: what each one promises, what it costs, and how to catch your database breaking it
The shop runs Postgres 17 with one asynchronous hot standby. A client's UPDATE on the primary returns COMMIT. Two milliseconds later the same client reads that row from the standby. What can it see?
The word “consistent” means three different things in this course. In ACID it means the database moves from one state that satisfies your constraints to another. In CAP it means linearizability, one specific and expensive guarantee. In everyday engineering it means “my read returns what I expect”, which is a promise nobody made. This chapter is about the second and third meanings: the consistency models that say which values a read is allowed to return when data lives in more than one place, how they relate to the isolation levels you met in isolation anomalies, and how to test which one your system actually gives you.
Two families, one map
Consistency models come from two research communities that met late.
The distributed-systems side talks about single objects: a register, a key, a row. Its models say how operations on that object by different clients may be ordered. Linearizable, sequential, causal, PRAM, and the session guarantees (read-your-writes, monotonic reads, monotonic writes, writes-follow-reads) live here.
The database side talks about transactions over many objects. Its models say which interleavings of multi-object transactions are allowed. Serializable, snapshot isolation, repeatable read, read committed live here; the anomalies catalogue in module two is their test suite.
The two meet at the top. Strict serializability is serializable plus real-time order, which is linearizability for transactions. Spanner calls it external consistency. Everything else is a trade along one axis or the other.
Jepsen’s consistency map draws all of these as a hierarchy, where an arrow from A to B means every history allowed by A is allowed by B. It also colours each model by what it costs in availability, which is the most useful thing on the page:
| model | what it promises | availability under partition | where you meet it |
|---|---|---|---|
| strict serializable | transactions run in one order consistent with real time | not available | Spanner, FoundationDB |
| serializable | transactions run in some single order | not available | Postgres SERIALIZABLE, CockroachDB default |
| snapshot isolation | each transaction reads one consistent snapshot; write-write conflicts abort | not available | Postgres REPEATABLE READ, Oracle “serializable”, MongoDB snapshot reads |
| linearizable | single object behaves like one copy; real time respected | not available | etcd reads, MongoDB readConcern: "linearizable", Cassandra lightweight transactions |
| sequential | single total order, each client’s order preserved, real time ignored | not available | ZooKeeper reads without sync() |
| causal | if A could have influenced B, everyone sees A before B | sticky available | MongoDB causally consistent sessions |
| read-your-writes | you see your own acknowledged writes | sticky available | sticky sessions, LSN tokens |
| monotonic reads | your reads never go back in time | totally available | pinning a client to one replica |
| read committed | you never see uncommitted or aborted data | totally available | Postgres default; any async replica |
“Totally available” means every node that is up can answer every request, even when cut off from the rest. “Sticky available” means a client can keep working only if it keeps talking to the same server. “Not available” means some requests must wait or fail during a partition. That last column is a theorem, not a vendor choice: Bailis and colleagues proved in the Highly Available Transactions paper which models a system can offer with high availability, and the line falls between read committed (yes) and snapshot isolation (no), and between causal (sticky) and sequential (no).
The practical reading of the map is this. Anything in the “not available” group costs you a coordination round trip on every operation that needs it, and stalls during a partition. Anything below it can be served locally, and is therefore what you get by default from any system that reads from replicas.
Linearizability: one copy, real time
A history is linearizable if every operation appears to take effect at a single instant between its invocation and its response, and those instants are consistent with what every read returned. Herlihy and Wing defined it in 1990 for concurrent objects; it is the property you assume when you write x = 1; assert x == 1 against a single machine.
The rule that bites in production is the real-time one. Draw each operation as an interval from invocation to completion:
Client B’s read overlaps the write, so the write may take effect before or after it: 41 and 42 are both linearizable. Client C’s read starts after the write was acknowledged, so linearizability requires 42. A replica that has not applied the write returns 41, and that history has no valid linearization. This is the stale read, and it is the anomaly the lab hunts.
Linearizability costs a round trip. A leader that wants to serve a linearizable read must know it is still the leader, so it either confirms with a majority (etcd’s ReadIndex, one network round trip) or holds a time-based lease and trusts the clocks. A quorum system must read from a majority whose set overlaps the last write’s majority. Either way the read latency is bounded below by the distance to a majority, which is the “else latency” half of PACELC. The simulation below makes the cost concrete: watch the read latency in the linearizable scenario, then the stale value in the eventual one.
PACELC (Abadi, 2012):
if Partitioned: trade Availability against Consistency (CAP)
Else: trade Latency against Consistency
Where the latency goes, for a write to 3 replicas that apply it after 0 / d / 2d:
linearizable ack after a majority applies write latency = d
read asks a majority read latency = round trip to
the 2nd-nearest replica
every read sees every acknowledged write
eventual ack after the local apply write latency = local
read asks one replica read latency = local
a read may return a value older than one you were told was written
in between read-your-writes / session: route reads to a replica that has
your write, or carry its version and wait for it. Cheap, but
only for your own writes, only while the session holds. Keep the schedule: write at t=0, acknowledged at t=2, read from R2 at t=27. Drag REPLICA DELAY to the lowest value at which that read comes back stale.
GOAL: the read at t=27 is stale at this delay and fresh one notch lower
What the tune exercise shows is that the stale window is replica delay minus the time the client takes to come back. Your application servers are fast. They come back in under a millisecond. So any replica delay at all produces stale reads for clients that write and then read, which is every checkout flow.
Sequential and causal: giving up real time
Sequential consistency keeps a single total order that all clients agree on, and keeps each client’s own operations in program order, but drops the real-time rule. Client C in the diagram may read 41 after the write was acknowledged, as long as it never then reads 42 followed by 41, and as long as everyone agrees on the same order. ZooKeeper is the classic example: writes go through the leader and are totally ordered, but a read is served by whichever server the client is connected to, which may be behind. ZooKeeper offers sync() to force the server to catch up before a read when you need real time.
Causal consistency drops the single total order too. It promises only that if operation A could have influenced operation B (the same client did A then B, or B read a value A wrote, transitively), then every client sees A before B. Concurrent operations, the ones with no causal path between them, may be seen in different orders by different clients. Tracking “could have influenced” is what vector clocks do. Causal consistency is the strongest model that stays sticky available under partition, which is why it is popular in geo-replicated designs: a reply to a comment never appears before the comment, and nobody waits for another continent.
Causal is weaker than it sounds for invariants. Two clients can each read “one seat left”, each book it, and both bookings are causally fine because neither saw the other. Uniqueness, balances that must not go negative, and any check-then-act across clients need a total order, so they need a model from the unavailable group.
Session guarantees: what users actually notice
Terry and colleagues named four guarantees in 1994 for the Bayou system. They are scoped to one client session and they are what users complain about:
- Read-your-writes: after you write, your reads reflect it. Violated in the Why: the payment page wrote, the order page read a replica.
- Monotonic reads: once you have seen a value, you never see an older one. Violated when a load balancer sends consecutive reads to two replicas with different lag; the comment count goes 12, 14, 13.
- Monotonic writes: your writes are applied in the order you made them everywhere.
- Writes-follow-reads: a write you make after reading something is ordered after the thing you read.
All four together, plus a few conditions, give causal consistency. Each one on its own is cheap, because it constrains only what a session sees, not what the whole system agrees on. Read-your-writes needs either stickiness (read from the node that took your write) or a token (the position of your last write, which a replica must reach before serving you). Monotonic reads needs the same token idea, advanced on every read rather than every write. Both cost nothing for clients that are not writing.
Transactions on replicas: snapshot isolation of the past
The transactional models were covered from the inside in module two. What changes with replicas is the point in time the snapshot is taken from.
A Postgres hot standby replays WAL in order and applies a transaction’s commit record atomically. A query on the standby takes a snapshot of the standby’s current replay position, so it sees a consistent prefix of the primary’s history: every transaction committed up to some LSN, none after. Within one standby, a REPEATABLE READ transaction is snapshot isolation of a moment in the past. Reads are never torn and never show uncommitted data. They are only late. That is read committed, monotonic reads (per standby), and consistent prefix, and nothing on the left of the map.
The gap between “then” and “now” has no upper bound you configured. It grows when:
- the standby’s replay is slower than the primary’s write rate, typically during bulk loads, index builds and
VACUUMof large tables; - a query on the standby conflicts with replay (it needs row versions the primary has vacuumed away) and replay pauses for up to
max_standby_streaming_delay, 30 s by default, before cancelling the query; - the network or the standby’s disk stalls.
pg_stat_replication.replay_lag on the primary and now() - pg_last_xact_replay_timestamp() on the standby measure it. Both are averages over recent activity, so a reading of 2 ms says nothing about the read that hit a 900 ms pause.
What Postgres replication actually promises
synchronous_commit decides when the primary acknowledges a commit, and therefore what a replica reader may see afterwards:
synchronous_commit (with a sync standby named) |
primary waits for | after COMMIT returns, a standby read |
|---|---|---|
off |
nothing; WAL flushed within wal_writer_delay × 3 |
may miss it; the primary may also lose it on crash |
local |
local WAL flush | may miss it |
remote_write |
standby has written WAL to its OS | may miss it |
on (default) |
standby has flushed WAL to disk | may miss it: flushed is not applied |
remote_apply |
standby has replayed the commit | sees it |
Only remote_apply gives read-your-writes, and a linearizable single-key read, from the standby. It costs a round trip plus replay time on every commit, and it turns standby slowness into primary slowness: a standby paused on a query conflict pauses every committing transaction on the primary.
Three traps sit in this table.
The silent no-op. All of the remote settings depend on synchronous_standby_names. If it is empty, the documentation says on, remote_apply, remote_write and local all give the same local behaviour. Setting remote_apply and forgetting the standby name gives you exactly what you had, with no warning.
The cancelled wait. If a client cancels a commit that is waiting for a synchronous standby, or the backend is terminated, Postgres returns a warning: the transaction has already committed locally but might not have been replicated. The write is visible on the primary and missing on the standby. Failover in that window loses an acknowledged write, which is why the failover chapter cares about it.
New then old. On the primary, a committing transaction stays invisible to other sessions until its synchronous-replication wait ends; on the standby it becomes visible as soon as replay applies it. In the gap, a client can read the new value on the standby and then the old value on the primary. That is a linearizability violation even with remote_apply. The window is short, and a checker that mixes primary and standby reads will eventually find it.
The serializable story has its own caveat. Postgres’ SSI tracks read-write dependencies inside one server, and standby queries cannot take part in that tracking. So a hot standby refuses the level outright: SET TRANSACTION ISOLATION LEVEL SERIALIZABLE on a standby fails with cannot use serializable mode in a hot standby, and the hint suggests REPEATABLE READ. Serializable reads go to the primary.
How Jepsen finds these, and why you can too
Jepsen tests work the same way at every scale. Clients run operations against the system while a nemesis injects faults: partitions, clock skew, process pauses, crashes. Every operation is recorded twice, once at invocation and once at completion, as :ok, :fail (definitely did not happen) or :info (unknown: it timed out and may or may not have taken effect). A checker then asks whether any order of the operations, consistent with the chosen model, explains every value read.
Checking linearizability of an arbitrary history is NP-complete in general, which is why Jepsen’s Knossos checker can run out of memory on long histories. Elle, the newer checker, avoids the search by designing the workload: operations append unique values to lists, so every read reveals the full order of writes it saw, and the checker can build a dependency graph and look for cycles in linear time.
You can borrow that trick. If every write produces a unique, strictly increasing value for its key, then a read that returns value v is stale exactly when some write of a value greater than v had already completed before the read was invoked. No search. Incrementing a counter on the primary does this for free: row locks serialise the increments, so the values come out in commit order. The lab uses inventory.on_hand as the counter.
Two honesty rules from Jepsen apply to any checker you write. First, a timed-out write is indeterminate: it may have committed. Count it as “may have happened” or you will report false anomalies. Second, use one clock for all timestamps. The lab runs every client in one process with time.monotonic_ns(), so invoke and complete times are comparable; a checker that compares timestamps from two machines is measuring clock skew.
Reading a vendor’s consistency claim
Every database has a page called “Consistency” and most of them are true under conditions that are in a footnote. Ask these, in order:
- Single object or transaction? “Strongly consistent reads” in DynamoDB means a read reflects all writes acknowledged before it, for one item, on the base table or a local secondary index; global secondary indexes are eventually consistent whatever you ask for.
- Which replica serves the read, and can I choose? MongoDB’s default
readConcernis"local": a read can return data that is later rolled back after a failover."majority"cannot be rolled back but can be stale."linearizable"is not stale but costs a majority round trip. - What happens to an acknowledged write when the leader dies? That is the write concern,
synchronous_commit, or the replication factor and consistency level; the failover chapter in this module is about this question. - Under which faults was this tested? Look for a Jepsen analysis. Read its list of anomalies found and the versions that fixed them.
- Is the guarantee per session, per key, per partition, or global? Cassandra’s lightweight transactions are linearizable per partition. CockroachDB guarantees serializable transactions and no stale reads for single keys, which is not the same as strict serializability across keys.
The habit that matters is to write the answer down next to each read path in your service: “order page: primary, linearizable”; “product listing: any replica, up to 30 s stale, monotonic per session”. The bug in the Why was a read path nobody had written that line for.
You will start one asynchronous hot standby of the shop, write a 130-line checker that records a history of increments and reads, and use it to find stale reads, read-your-writes violations and monotonic-read violations. Then you will fix them two ways and measure what each fix costs. Work in labs/databases/. The standby is replica1 from replication.yaml, the override the replication chapter created; the lab adds one new file, d3-consistency/checker.py.
1. Start the shop with the replication override.
replication.yaml restarts db with wal_level = logical and a pg_hba.conf that accepts replication connections, and defines replica1 on host port 5442. Start only the primary and that one standby:
cd labs/databases
export COMPOSE_FILE=compose.yaml:replication.yaml
docker compose up -d db
docker compose exec -T db psql -U atlas -d shop -v scale=0.1 -f /shop/load.sql # skip if already loaded
docker compose exec db psql -U atlas -d shop -c "show wal_level" -c "select slot_name from pg_replication_slots"db is recreated because its command changed, and comes back with the same data. wal_level is logical, a superset of the replica level a standby needs. The slot list is empty: the replication chapter dropped its slots at the end. If it shows replica1 or replica2, drop them now with select pg_drop_replication_slot(slot_name) from pg_replication_slots, and run docker volume rm databases_replica1-data if that volume is left over, so that the standby clones afresh.2. Add the hot standby.
docker compose up -d replica1
sleep 10
docker compose logs replica1 | tail -3
docker compose exec db psql -U atlas -d shop -c \
"select application_name, state, sync_state, replay_lag from pg_stat_replication"
psql postgres://atlas:atlas@localhost:5442/shop -c "select pg_is_in_recovery(), count(*) from inventory"(No psql on your host? Use docker compose exec replica1 psql -U atlas -d shop -c "..." instead.)
replica.sh clones the primary with pg_basebackup -R -C -S replica1, so the log shows cloning the primary, then database system is ready to accept read-only connections. pg_stat_replication shows one row: replica1 | streaming | async, with replay_lag empty or a few hundred microseconds. On the standby, pg_is_in_recovery is t and the count is 5000 at scale 0.1. The base backup of a 100 MB database takes a few seconds.3. Write the checker.
mkdir -p d3-consistency && cd d3-consistency
python3 -m venv .venv
.venv/bin/pip install "psycopg[binary]==3.3.6"Create d3-consistency/checker.py:
"""A small Jepsen-style checker for the shop's replicated Postgres.
Workers increment inventory.on_hand on the primary (each increment produces a
unique, larger value) and read it back from wherever --reads says. Every
operation is recorded with the time it was invoked and the time it completed.
After the run, the history is checked for three anomalies.
"""
import argparse, bisect, random, statistics, threading, time
from collections import defaultdict
import psycopg
PRIMARY = "postgresql://atlas:atlas@localhost:5432/shop"
REPLICA = "postgresql://atlas:atlas@localhost:5442/shop"
KEYS = [1, 2, 3, 4, 5] # product_ids whose stock is the register
history, hlock = [], threading.Lock()
def record(**op):
with hlock:
history.append(op)
def route(mode, rng, p, r, token):
if mode == "primary":
return "primary", p
if mode == "replica":
return "replica", r
if mode == "mixed": # a load balancer over both nodes
return rng.choice([("primary", p), ("replica", r)])
# mode == "lsn": use the replica only once it has replayed this worker's last write
(ok,) = r.execute("SELECT pg_last_wal_replay_lsn() >= %s::pg_lsn", (token,)).fetchone()
return ("replica", r) if ok else ("primary", p)
def worker(pid, args, stop):
p = psycopg.connect(PRIMARY, autocommit=True)
r = psycopg.connect(REPLICA, autocommit=True)
if args.sync:
p.execute("SET synchronous_commit = remote_apply")
rng, token = random.Random(pid), "0/0"
while not stop.is_set():
k = rng.choice(KEYS)
t0 = time.monotonic_ns()
if rng.random() < args.write_ratio:
(v,) = p.execute(
"UPDATE inventory SET on_hand = on_hand + 1, updated_at = now() "
"WHERE product_id = %s RETURNING on_hand", (k,)).fetchone()
t1 = time.monotonic_ns()
token = p.execute("SELECT pg_current_wal_lsn()::text").fetchone()[0]
record(pid=pid, f="write", key=k, value=v, t0=t0, t1=t1, node="primary")
else:
node, conn = route(args.reads, rng, p, r, token)
(v,) = conn.execute(
"SELECT on_hand FROM inventory WHERE product_id = %s", (k,)).fetchone()
t1 = time.monotonic_ns()
record(pid=pid, f="read", key=k, value=v, t0=t0, t1=t1, node=node)
def check(h, start):
writes = [o for o in h if o["f"] == "write"]
reads = [o for o in h if o["f"] == "read"]
# For each key: the earliest time at which ANY value >= v had been acknowledged.
done = defaultdict(dict)
for w in writes:
done[w["key"]][w["value"]] = w["t1"]
values, first_ack = {}, {}
for k, by_value in done.items():
vs = sorted(by_value)
acks = [by_value[v] for v in vs]
for i in range(len(acks) - 2, -1, -1): # suffix minimum
acks[i] = min(acks[i], acks[i + 1])
values[k], first_ack[k] = vs, acks
# 1. Stale read: a write of a newer value had completed before the read began.
stale = []
for rd in reads:
vs = values.get(rd["key"], [])
i = bisect.bisect_right(vs, rd["value"]) # first value newer than the read
if i < len(vs) and first_ack[rd["key"]][i] < rd["t0"]:
stale.append((rd, vs[i], (rd["t0"] - first_ack[rd["key"]][i]) / 1e6))
# 2. Read-your-writes and 3. monotonic reads, per worker and key.
ryw, mono = [], []
last_write, last_read = {}, {}
for o in sorted(h, key=lambda o: o["t0"]):
kk = (o["pid"], o["key"])
if o["f"] == "write":
last_write[kk] = o["value"]
continue
if o["value"] < last_write.get(kk, -1):
ryw.append(o)
if o["value"] < last_read.get(kk, -1):
mono.append(o)
last_read[kk] = max(o["value"], last_read.get(kk, -1))
print(f"ops {len(h)}: {len(writes)} writes, {len(reads)} reads")
nodes = defaultdict(int)
for rd in reads:
nodes[rd["node"]] += 1
print("reads served by", dict(nodes))
if writes:
lat = sorted((w["t1"] - w["t0"]) / 1e6 for w in writes)
print(f"write latency ms: p50 {lat[len(lat) // 2]:.2f} p99 {lat[int(len(lat) * 0.99)]:.2f}")
pct = 100 * len(stale) / max(len(reads), 1)
print(f"stale reads: {len(stale)} ({pct:.2f}% of reads)")
if stale:
ages = [a for _, _, a in stale]
print(f" how late: median {statistics.median(ages):.2f} ms, max {max(ages):.2f} ms")
rd, v, age = stale[0]
print(f" e.g. worker {rd['pid']} read product {rd['key']} = {rd['value']} on the "
f"{rd['node']} at t={(rd['t0'] - start) / 1e9:.3f}s, but {v} or newer had "
f"been acknowledged {age:.2f} ms before that read began")
print(f"read-your-writes violations: {len(ryw)}")
print(f"monotonic-read violations: {len(mono)}")
if __name__ == "__main__":
ap = argparse.ArgumentParser()
ap.add_argument("--reads", choices=["primary", "replica", "mixed", "lsn"], default="replica")
ap.add_argument("--workers", type=int, default=8)
ap.add_argument("--seconds", type=float, default=10)
ap.add_argument("--write-ratio", type=float, default=0.2)
ap.add_argument("--sync", action="store_true", help="writers use synchronous_commit = remote_apply")
args = ap.parse_args()
stop, start = threading.Event(), time.monotonic_ns()
ts = [threading.Thread(target=worker, args=(i, args, stop)) for i in range(args.workers)]
for t in ts:
t.start()
time.sleep(args.seconds)
stop.set()
for t in ts:
t.join()
check(history, start)The stale-read check is the counter trick from the body: for each key it precomputes, for every value, the earliest moment that value or a newer one had been acknowledged, then flags any read that started after that moment and returned something older. It is a sound linearizability check for these reads because nothing else writes inventory.on_hand for products 1 to 5 while it runs.
4. Establish the baseline, then read from the standby.
.venv/bin/python checker.py --reads primary
.venv/bin/python checker.py --reads replica
.venv/bin/python checker.py --reads mixed--reads primary all three counts are 0: a single Postgres primary gives linearizable reads of a row. Expect 10 000 to 40 000 operations in 10 s, depending on Docker’s port forwarding. With --reads replica you should see a non-zero count of stale reads and read-your-writes violations and zero monotonic-read violations: one standby replays in order, so it only ever moves forward. The stale count on an idle laptop is small, often well under 1% of reads, and the median “how late” is a fraction of a millisecond, because replay keeps up within a network hop. With --reads mixed all three are non-zero: alternating between two nodes at different points in time sends a session backwards. If replica mode shows 0 stale reads, run it with --workers 32; contention widens the window.5. Make the standby behave like a busy one.
A standby under load, or one replaying a large UPDATE, applies commits late. recovery_min_apply_delay simulates that deterministically. It is a reloadable setting and ALTER SYSTEM is allowed on a standby:
psql postgres://atlas:atlas@localhost:5442/shop -c "alter system set recovery_min_apply_delay = '50ms'"
psql postgres://atlas:atlas@localhost:5442/shop -c "select pg_reload_conf()"
.venv/bin/python checker.py --reads replica
.venv/bin/python checker.py --reads lsnlsn mode the read-your-writes count drops to 0, because each worker reads the standby only once it has replayed that worker’s own last write, and falls back to the primary otherwise; the reads served by line shows the split. Stale reads do not go to zero: the token covers your own writes, not other workers’. You may also see monotonic-read violations, because a worker that fell back to the primary and then returns to the standby can go back in time. Read-your-writes is a session guarantee; linearizability is not.6. Pay for linearizable standby reads with remote_apply.
Name the standby as synchronous on the primary, then run the writers with synchronous_commit = remote_apply:
docker compose exec db psql -U atlas -d shop -c "alter system set synchronous_standby_names = '*'"
docker compose exec db psql -U atlas -d shop -c "select pg_reload_conf()"
docker compose exec db psql -U atlas -d shop -c "select application_name, sync_state from pg_stat_replication"
.venv/bin/python checker.py --reads replica --sync
psql postgres://atlas:atlas@localhost:5442/shop -c "alter system reset recovery_min_apply_delay"
psql postgres://atlas:atlas@localhost:5442/shop -c "select pg_reload_conf()"
.venv/bin/python checker.py --reads replica --sync
.venv/bin/python checker.py --reads replicasync_state is now sync. With the 50 ms delay still on, the first --sync run shows 0 stale reads and 0 read-your-writes violations, and a write p50 of about 50 ms: every commit waits for the standby to apply it, delay included, so total operations fall by an order of magnitude or more. With the delay removed, --sync still shows 0 stale reads and the write p50 rises by roughly one replay round trip over plain async, typically from a few tenths of a millisecond to around a millisecond on a laptop. The last run, without --sync, is back to a few stale reads: the setting is per session, so every client that needs the guarantee must ask for it. In production the round trip is to another zone, 1 to 2 ms, or another region, 30 to 150 ms.synchronous_standby_names = '*' still set, stop the standby: docker compose stop replica1. Open docker compose exec db psql -U atlas -d shop, run set synchronous_commit = remote_apply; then update inventory set on_hand = on_hand + 1 where product_id = 1;. It hangs: the primary will not acknowledge a commit that no synchronous standby has applied, so one dead standby has stopped all writes that asked for the guarantee. (The default synchronous_commit = on also waits, for a flush rather than an apply; plain checker.py runs now hang too.) Press Ctrl-C. Postgres prints canceling wait for synchronous replication due to user request and a detail line saying the transaction has already committed locally but might not have been replicated to the standby. Run select on_hand from inventory where product_id = 1 and the increment is there. You were told “cancelled” and the write happened: an indeterminate operation, the :info case Jepsen refuses to ignore. Clean up with alter system reset synchronous_standby_names; select pg_reload_conf(); on the primary. Then remove the standby and its slot, which would otherwise keep WAL on the shop’s disk: docker compose rm -sf replica1, docker compose exec db psql -U atlas -d shop -c "select pg_drop_replication_slot('replica1')", docker volume rm databases_replica1-data, then unset COMPOSE_FILE and docker compose up -d to put db back on its default command.The shop's order page reads from two async Postgres standbys behind a load balancer to keep load off the primary. After a payment, about 1 in 400 customers sees 'awaiting payment' and some pay twice. The primary runs at 55% CPU; the order page is 30% of all reads. Standby replay_lag averages 3 ms with spikes past a second during nightly batch jobs. What do you change?
- DOC Consistency Models Kyle Kingsbury (Jepsen)
The map this chapter is built on, with one page per model giving a definition and its availability class. Read the overview and the pages for linearizable, causal, read-your-writes and snapshot isolation; skip the formal definitions of the weaker models on first pass.
- PAPER Highly Available Transactions: Virtues and Limitations Bailis, Davidson, Fekete, Ghodsi, Hellerstein, Stoica, 2014
Proves which isolation and session guarantees can be offered with high availability and which cannot. The source of the availability colours on the Jepsen map. Read: sections 4 and 5, and the summary table in section 5.3; skip the proofs in the appendix.
- BOOK Designing Data-Intensive Applications Martin Kleppmann, 2017
The clearest prose treatment of read-your-writes, monotonic reads and consistent prefix reads, followed by linearizability and its cost. Read chapter 5's section if this chapter's session guarantees felt brisk. Read: chapter 5, 'Problems with Replication Lag', then chapter 9 up to 'Distributed Transactions and Consensus'.
- PAPER Linearizability: A Correctness Condition for Concurrent Objects Maurice Herlihy and Jeannette Wing, 1990
The original definition, with the queue examples that make the real-time rule obvious. Short and readable; everything later cites it. Read: sections 1 to 3; skip the proof techniques in section 4 onwards.
- PAPER Elle: Inferring Isolation Anomalies from Experimental Observations Kyle Kingsbury and Peter Alvaro, 2020
How Jepsen checks transactional histories in linear time by designing the workload. The lab's counter trick is the single-object version of this idea. Read: sections 1 to 4: the list-append workload and how cycles map to anomalies.
- POST Jepsen: PostgreSQL 12.3 Kyle Kingsbury, 2020
A complete Jepsen analysis of the database this course uses: the G2-item bug in SERIALIZABLE, and the argument that REPEATABLE READ is snapshot isolation. Read it for the method as much as the result.
- DOC PostgreSQL 17: Replication settings
The authoritative description of synchronous_commit's interaction with synchronous_standby_names, recovery_min_apply_delay and max_standby_streaming_delay. Read the entries used in the lab; skip logical replication settings.
- POST Please stop calling databases CP or AP Martin Kleppmann, 2015
Why the CAP labels on vendor pages tell you almost nothing, and which precise questions to ask instead. A good companion to the vendor checklist in this chapter.
All companies and people in these examples are fictional. Any resemblance to a real business or person is unintended.