"We need strong consistency" sounds like a requirement, but it tells you nothing.
Strong compared to what? Which specific thing does it prevent? Does it cover one object or several? Is it about transactions or about replicas? Those are four different questions, with four different answers and four different prices, and the sentence answers none of them.
Here's the idea that fixes it.
A consistency model is not a level of goodness. It is a list of specific bad things that the system promises cannot happen to you. That's all it is. Each bad thing is called an anomaly, such as two people booking the same room. Serializable isolation isn't "better" in the abstract. It forbids two particular anomalies that snapshot isolation, a slightly weaker level, permits. Linearizability, the promise that every read sees the latest write, isn't "the strong one" either. It forbids stale reads. It does nothing about the anomalies between transactions, and those are the ones more likely to take your system down.
So the useful question is never "how strong do we need this?" It's this: which specific bad thing am I trying to prevent, and what is the weakest guarantee that prevents it?
There's a second idea, and missing it is why these conversations so often get nowhere.
There are two independent families of consistency, they are configured in different places by different people, and neither one can fix the other's problems. Raising your isolation level will never fix a stale read from a replica. Reading from the leader, the one node that takes the writes, will never prevent write skew. If you can't say which family your problem is in, you'll buy the wrong fix. It won't help, and you'll decide you need something even stronger.
So this article covers the anomalies first. Once you know the eleven things that can go wrong, the model names stop mattering, because each name is just a label for a set of anomalies you already understand.
Why "how strong do you need it?" is the wrong question
There are three reasons, and each one leads to a different kind of wasted work.
Because "stronger" isn't one direction. There are two axes. Take a single PostgreSQL node running serializable transactions. It has the strongest isolation available. The moment you add a read replica and read from it, it also has the weakest replication consistency there is. The first fact does nothing to protect you from the second. Teams often spend a quarter tightening one axis while shipping bugs on the other.
Because the names lie, and that's meant literally. The isolation level called "repeatable read" means one thing in the SQL standard, a different thing in PostgreSQL, and something weaker again in MySQL. The details are documented, and they're worse than you'd guess.
Because the strong option is usually not the fix. If a stronger level makes a bug disappear, the real problem was a missing constraint. An invariant is a rule the data must never break, such as "at least one doctor is on call". A unique index costs nothing and states the invariant where everyone can see it. Serializable isolation costs you aborts forever: the database cancels some transactions, and every caller needs logic to retry them. It also hides the invariant in a configuration setting.
Here's the short version of when to care: consistency models matter exactly where an invariant spans more than one thing. That means more than one row, more than one object, more than one replica, or more than one request. If your operation touches one row on one node, almost none of this applies. Say so and move on.
The two families
Isolation: what concurrent transactions see of each other
This family comes from databases, and it's about transactions over several objects. A transaction is a group of reads and writes that commits or fails as one. The question is: while my transaction is running, what can I see of other transactions running at the same time?
From weakest to strongest, the levels are read uncommitted, read committed, snapshot isolation (often labelled repeatable read), and serializable. Under snapshot isolation, each transaction reads from a snapshot of the database taken when it started.
Serializable means the outcome is the same as if the transactions had run one at a time, in some order. That order doesn't have to be the order they arrived in, and this detail is what separates serializable from the next family.
Replication: when a write becomes visible, and in what order
This family comes from distributed systems, and it's about one object across several replicas. A replica is a copy of the data on another node, kept up to date by copying the writes across. The question is: once my write has completed, when do other people see it, and can different people see events in different orders?
Roughly from strongest to weakest, the levels are linearizable, causal, bounded staleness, session guarantees, consistent prefix and eventual. The order is rough because a few neighbours on this list each forbid something the other allows.
Linearizable means the system behaves as if there were only one copy of the data, with every operation ordered by real time. Once a write returns, nobody anywhere can read the old value again.
Two of these levels are rarely taught, and they're the practical ones.
Bounded staleness is the only model on the list that comes with a number. It promises that a read is at most k versions or t seconds behind the latest write, and you pick the bound. That's a different kind of promise from "eventual", because you can put a number in a product requirement, monitor it, and alert on it. No amount of lag breaks the "eventual" promise, so there's nothing to check.
Consistent prefix promises that whatever you see is a prefix of the real history: everything up to some point, with no gaps. You may be behind, but you'll never see event five without events one to four. It's weaker than causal consistency, and it removes a lot of the strange behaviour users notice, for very little cost.
They are orthogonal, and here is the grid
This grid organises the rest of the topic.
Strict serializability is the top-right corner: serializable transactions, ordered by real time as linearizability requires. It's the strongest guarantee on offer. Spanner provides it. CockroachDB comes close: it's serializable and promises no stale reads, but two transactions on unrelated keys can be ordered differently from real time.
The bottom-right corner is the interesting one, because it's very strong and very weak at the same time. A PostgreSQL primary, its leader, sits there if it runs serializable transactions and the application reads from an asynchronous replica to save load. An asynchronous replica gets the primary's writes after a delay, and the primary doesn't wait for it. Every transaction is perfectly isolated. Every read may be any amount out of date. Both statements are true, and neither one helps with the other.
Look at how those two properties get set. The isolation level is chosen in a transaction, usually by a backend engineer, and usually left at the default. The replication consistency depends on which connection string the read goes through, and that's usually chosen by whoever was speeding up a slow page. Two different people set them, in two different files, and nobody writes down the guarantee they produce together.
The eleven things that can go wrong
These eleven anomalies are what every consistency model is made of. Once you know them, the names are just labels.
Six anomalies in the isolation family
1. Dirty read. Another transaction writes ₹500 into an account but hasn't committed yet. You read the ₹500 and email a receipt. Then the other transaction rolls back, and your receipt describes money that never existed.
2. Dirty write. Two transactions each write the item and the buyer of the same order, before either commits. Their writes interleave, so the order ends up with the item from one and the buyer from the other. It belongs to nobody and matches no request anyone made.
3. Read skew, also called a non-repeatable read. You're producing a report, and accounts A and B hold ₹500 each. You read A and see ₹500. Then a transfer of ₹100 from A to B commits. You read B and see ₹600. Your report shows ₹1,100, but the bank holds ₹1,000. Nothing was corrupted. You read two different moments and added them together.
4. Lost update. Two clients read a counter at 42, both add one, and both write 43. One increment is gone. Nothing returned an error, and no log records a problem.
5. Write skew. This is the important one. Two transactions read the same set of rows. Each makes a decision based on what it read, and then each writes a different row. Row-level conflict detection only notices two transactions writing the same row, so it sees nothing here. The invariant covered both rows, and now it's broken.
6. Phantom. A write in one transaction changes the result of a search in another. Two transactions each count the bookings for a meeting room slot, each sees zero, and each inserts a booking. The key property is that you can't lock a row that doesn't exist yet. So phantoms need a different mechanism from row locks. Write skew usually happens through a phantom like this one.
Five anomalies in the replication family
7. Stale read. You read a replica that hasn't caught up, and you see an older value. This is the oldest and most ordinary of the five.
8. Non-monotonic read, or time running backwards. Your first read hits an up-to-date replica and shows a comment. Your second read hits one that's behind, and the comment is gone. To the user, it looks as if the comment was deleted, or as if they imagined it.
9. Read-your-writes violation. You change your display name, the page reloads from a replica that's behind, and the old name is back. This is the most reported bug in the family, and the cheapest to prevent.
10. Causal violation. You see a reply before the message it answers. A worse version: Alice removes her manager from her contacts, then posts that she's job hunting. The two writes reach different replicas in different orders, so one replica shows the post but hasn't yet applied the removal. That's a privacy failure caused only by ordering. Each write on its own was correct.
11. Writes-follow-reads violation. You read a post and reply to it. Someone else then sees your reply on a replica that doesn't have the original yet. Your reply seems to be answering nothing.
The reference grid
Using PostgreSQL as the reference implementation, since the
exact set differs by engine.
ISOLATION LEVEL forbids, of the 6 isolation anomalies
read uncommitted 2 runs as read committed here
read committed 2 dirty read, dirty write
repeatable read 4 + read skew, lost update
serializable 6 + write skew, phantom
and of the 5 replication anomalies, every one of them
forbids 0
─────────────────────────────────────────────────
The strongest isolation level money can buy addresses
zero of the five anomalies your users complain about.That last line is why this article separates the families before naming any levels. Almost every "we tried strong consistency and it didn't fix it" story is the same. Somebody bought protection against the six isolation anomalies, and the problem was one of the other five.
The four session guarantees, which are nearly free
Doug Terry and his colleagues named a set of four guarantees in 1994, while working on the Bayou project at Xerox PARC. Together they prevent four of the five replication anomalies. They're the best value in this article, and most engineers can't name them. They're called session guarantees because each one is a promise about what one session sees, and a session is one user's series of requests.
- Read your writes. You always see your own writes. Prevents anomaly 9.
- Monotonic reads. Later reads in a session never go backwards in time. Prevents anomaly 8.
- Monotonic writes. Your own writes are applied in the order you issued them, on every replica. This stops your second edit landing before your first. It also prevents anomaly 10 when both writes are yours, as with Alice.
- Writes follow reads. If you read something and then write in response, anyone who sees your write also sees what you were responding to. Prevents anomaly 11.
They're worth having because they cost almost nothing. None of them needs coordination, which means nodes exchanging messages and agreeing before they answer. So they keep working during a partition, when the network splits the nodes into groups that can't reach each other. They're built from two cheap mechanisms: sending a session's reads to one replica, or a version token. A version token is a write's position in the replication log, the ordered list of changes that the replicas apply. Here are the session guarantees against linearizability, the guarantee people reach for instead.
SESSION GUARANTEES
mechanism route a session's reads to one replica,
or carry a version token on each request
coordination between nodes none
extra latency ~0
behaviour during a partition keeps working
anomalies removed 4 of 5
LINEARIZABILITY
mechanism leader read with a lease, or a quorum read
coordination between nodes every operation
extra latency 1 round trip to mid-quorum
1 to 2 ms same region
60 to 200 ms across continents
behaviour during a partition minority side stops
anomalies removed 5 of 5
─────────────────────────────────────────────────
The fifth anomaly is the stale read. Everything else
is available for free.So the practical rule is short. Turn on session guarantees for everybody, always. Then ask, separately, whether any specific operation can't tolerate a stale read. Most teams do the opposite. They leave the cheap guarantees off, users report anomalies 8, 9 and 11, and the team reaches for linearizability. That's the expensive fix, and the only extra anomaly it removes is the stale read, which nobody was complaining about.
Every cache is a replica, so every TTL is a consistency decision
Teams think about consistency for the database, then put six layers of caching in front of it without thinking about consistency at all.
A cache is a replica with weaker guarantees and no replication protocol. A read replica at least knows it's behind, and it can tell you by how much. A cache has no idea. It holds a value it was given at some point, and it keeps serving that value until a timer runs out or somebody remembers to delete it.
Count the replicas in a fairly ordinary web application:
- the primary database
- a read replica
- a shared cache such as Redis
- an in-process cache inside each application instance
- a CDN (content delivery network)
- the browser's own HTTP cache
That's six tiers, and every one after the primary can serve old data. They're ordered by how hard each one is to invalidate, which means removing or replacing an entry when the data behind it changes. At least four different people set them, in at least four different files. Your user gets the guarantee of the weakest layer their request happens to hit, and that guarantee isn't written down anywhere.
Three things follow from this.
A TTL is a staleness bound, so it's a consistency decision. A TTL, or time to live, is how long an entry stays in the cache before it expires. If you set a 300 second TTL, you're stating that you accept data up to 5 minutes old. Most TTLs were chosen as a round number that felt safe. So most of your consistency policy was set by somebody typing 300 without thinking about the question. Take your twenty most-used cache keys and ask, for each one, "what is the oldest data this can safely show?" That review takes a few hours, and it's some of the most useful consistency work a team can do.
A cache breaks read-your-writes without any error, and it does it outside the database. You update a row, and the write commits. The very next read hits a cache that still holds the old value. You've broken the cheapest guarantee on the list, in a layer that no isolation setting and no replica-routing rule can reach. The fix has two parts. Invalidate or update the cache in the same code path as the write. Then, for a short window afterwards, send that user's reads past the cache.
After the browser's own cache, your CDN is your stalest replica and the hardest to invalidate, so it should hold the data whose freshness matters least. A CDN is a set of servers near your users that cache your responses. What ends up on the CDN is often an accident: things go there because they were slow, not because old copies of them are acceptable. Check that the two lists match: what's on the CDN, and what can safely be old.
So you don't have one consistency model. You have one per cache tier per key. That's hundreds of them, and almost all of them were set by default.
The method: name the anomaly, then find the weakest fix
1. Name the anomaly, not the level. Describe the bad outcome as a two-line story, with people in it. If you can't, you don't have a requirement yet.
2. Say who is harmed, and whether it can be undone. An outcome that can't be undone justifies expensive prevention. One that can be undone usually justifies a compensation instead: a later action that repairs the damage, such as a refund.
3. Decide which family it is in. Does the invariant span several objects inside one transaction, or one object across several replicas? People skip this step, and it decides whether your fix can work at all.
4. Find the weakest setting that forbids it, from the grid above.
5. Look for a cheaper fix before you change the level. A unique index, a check constraint, an atomic operation, a rule that only one writer ever updates a given key, or a session guarantee often removes the anomaly completely.
6. Price it, and write down what happens under contention. Contention means many transactions working on the same data at once. For isolation, write down the abort rate and who retries. For replication, write down the added latency and what happens during a partition.
Turn everything up to serializable and linearizable
It's the strongest setting, so it must be the safest. Set it globally and stop worrying.
Three things go wrong. First, you pay for coordination on every operation, including the large majority that never needed it, and that shows up as extra latency on every request, forever. Second, under contention serializable doesn't just slow down. It aborts transactions, so every caller now needs retry logic to be correct. Third, the invariant that started all this now lives in a configuration setting, not in the schema, so the next person who reads the code can't see it.
It may also not fix your bug at all. If the bug was a stale read from a replica, no isolation level can reach it.
Name the anomaly, place it, pick the weakest setting that forbids it
Work through the six steps. Name the anomaly as write skew. Note that it needs serializable, and that snapshot isolation won't do. Apply serializable only to the transactions that carry the invariant, and leave everything else where it was.
This is the right answer, and it's most of the value here. Say the two costs out loud. Serializable transactions abort under contention, so somebody has to retry them. And the retry has to be safe to run twice.
Move the invariant into the schema so no isolation level is needed
Ask why the database isn't enforcing the rule directly.
Most write skew hides a constraint. "At least one doctor on call" can become a row that both transactions must update. That turns a write skew nobody can detect into an ordinary write conflict on one row, which the database can detect. Kleppmann calls this materialising the conflict: you create a row for the transactions to compete over, so that cheap row-level detection can see the conflict. "No two bookings for the same room and slot" can become a unique index on the pair. The database then rejects the second insert at read committed, with no change to the isolation level and no retry logic.
Beyond the lower cost, this gives you two things. The invariant is now visible in the schema, where the next engineer will find it, instead of being implied by an isolation setting three layers away. And the database enforces it against every writer, including the migration script and the person on the console at 2 a.m. Neither of them will be running your carefully configured transaction.
What you give up: a unique index gives the caller an error rather than a place in a queue, so the caller has to handle a rejection. That's usually a better failure than an invariant broken without anyone noticing.
Four decisions, worked
1. Two doctors on call: write skew
The rule is that at least one doctor must be on call at all times. Alice and Bob are both on call. Both feel unwell, and both try to take themselves off call in the same second.
invariant: on_call count must be >= 1
starting state: Alice on call, Bob on call
T1 (Alice) T2 (Bob)
─────────────────────────────────────────────────
begin begin
count on_call → 2
count on_call → 2
2 >= 2, safe to leave
2 >= 2, safe to leave
update doctors
set on_call=false
where id='alice'
update doctors
set on_call=false
where id='bob'
commit commit
─────────────────────────────────────────────────
on_call count is now 0. Both transactions were
individually correct. Different rows were written,
so nothing conflicted.There are three ways out, from the one you should like least to the one you should like most.
Serializable isolation detects it and aborts one of the transactions. That's correct, and it costs you an abort plus retry logic in the caller.
An explicit lock on the shift, taken by both transactions with SELECT ... FOR UPDATE on the rows they read. Now they compete for real rows, and one waits for the other. This is correct and cheap, and it makes the contention visible in the code.
Materialise the conflict: give the shift its own row holding the on-call count, and make both transactions update it. The write skew becomes an ordinary write conflict on one row. Snapshot isolation detects that conflict. At read committed, the second update waits for the first, so it works if the update checks the count itself, as in where on_call > 1. This is the best of the three, because the invariant is now something the schema knows about.
2. Booking a meeting room: the phantom
This has the same shape as the doctors, with a different mechanism, and the difference matters.
Priya and Arjun both book room 4 for Tuesday at 10:00. Each transaction counts the existing bookings for that room and slot, sees zero, and inserts a booking. Both commit.
invariant: at most one booking per (room, slot)
starting state: no bookings for room 4 at 10:00
T1 (Priya) T2 (Arjun)
─────────────────────────────────────────────────
begin begin
count bookings where
room=4 and slot='10:00' → 0
same count → 0
0 == 0, the slot is free
0 == 0, it is free
insert (4, 10:00, priya)
insert (4, 10:00, arjun)
commit commit
─────────────────────────────────────────────────
Two bookings for one slot. There was no row for
either transaction to lock, because the thing being
protected was the absence of rows.
with a unique index on (room, slot):
T2's insert fails, at read committed,
with no retry logic and no isolation changeRow locks can't solve this, because there is no row. What you need to protect is the absence of any row that matches a condition, and a lock has to attach to something that exists. So serializable isolation needs a different mechanism. It can lock the condition itself, which is called a predicate lock. It can lock a range of an index, including the gap where the missing row would go. Or it can use serializable snapshot isolation, which tracks what each transaction read and aborts one of two transactions that each wrote something the other had read.
But before you reach for any of that, note that a unique index on (room, slot) solves this completely, at read committed, with no retries and no isolation change. The second insert fails on the constraint. The invariant becomes a line in the schema that everybody can see, and it holds against every writer, forever.
The general lesson: if you can state an invariant as "this combination must be unique", a unique index is almost always the right answer, and an isolation level is almost always the wrong one.
3. Unfriend, then post: causal consistency
Alice removes her manager from her contacts, then posts that she's looking for a new job. These are two writes, in that order, and the first causes the second: she posted because she had removed him.
If those writes are copied to the replicas independently, for example because contacts and posts are stored in different databases, some replica will have the post but not the removal. The manager reads that replica. Nothing was stale for long, no write was lost, and no constraint was broken.
This one is in the replication family, so no isolation level anywhere can help. You need causal consistency. The system has to know that the post depends on the removal, and a replica that hasn't applied the removal must not show the post. This is the monotonic writes guarantee from the session guarantees above, and it has to hold on the replica the manager reads, not only on the ones Alice uses. In practice that means tracking dependencies, usually with version vectors or a logical clock, which are counters that record which writes each write came after. A replica then holds a write back until the writes it depends on have arrived.
Full causal tracking is rare in production systems, so the cheaper approximation is useful to know. Route a session's writes and reads through one replica. The ordering is then local to that replica, and that user gets writes-follow-reads. It doesn't help a different user reading a different replica, and that's exactly the case here. For real privacy rules, check permissions at read time against an authoritative source, the one copy you trust to be current, and don't rely on replication order at all.
4. "My profile edit did not save"
This is the most common report in the family, and the cheapest to fix.
A user changes their display name. The write goes to the primary. The page reloads, the read goes to a replica that's 200 milliseconds behind, and the old name comes back. The user tries again. Now there are two writes, and they're still not sure it worked.
This is anomaly 9, and it needs read-your-writes. That's several levels below linearizability, and it costs almost nothing. For a few seconds after the write, send that user's reads to the primary, which took the write. Or return a version token with the write. The client sends the token with its next read, and a replica that hasn't reached that position waits or forwards the read.
This example shows the whole topic in miniature. The instinct is "we need strong consistency". The correct answer is one of the four cheapest guarantees available. It removes the anomaly completely, it needs no coordination, and it keeps working during a partition. Seeing the gap between the instinct and the real requirement is the whole skill.
Where this goes wrong
Here are eight failure modes, roughly in order of how much damage they do.
1. The level names do not mean the same thing anywhere
This isn't a matter of interpretation. The ANSI SQL standard defined its isolation levels with a lock-based implementation in mind. In 1995, Berenson, Bernstein, Gray, Melton and the two O'Neils showed that these definitions don't describe the isolation levels real databases implement. They had to define snapshot isolation as a new category, because the standard had no name for what shipping databases were doing.
Thirty years later the names are still inconsistent, and MySQL, one of the most widely deployed databases, is the worst example. Jepsen, an independent testing project, analysed MySQL 8.0.34. It found that MySQL's "repeatable read" doesn't provide repeatable read: it permits write skew. It doesn't provide snapshot isolation either, because it permits read skew and lost update. Read skew is the very anomaly the name "repeatable read" promises to prevent, and this is MySQL's default level. Counting the phantom, which repeatable read permits even in the standard, it lets through four of the six isolation anomalies.
The practical rule: never reason from the name. Look up what your specific engine at your specific version does, or test it.
2. Your default is weaker than you assume
PostgreSQL defaults to read committed, which forbids two of the six. MySQL defaults to repeatable read, which, as above, forbids fewer than its name suggests. Neither defaults to serializable.
So unless somebody on your team changed it on purpose, you're running a weak level. Any code written on the assumption of stronger guarantees is a bug that hasn't shown up yet. Check this today, not in an interview.
3. Snapshot isolation does not prevent write skew
Snapshot isolation prevents dirty reads, dirty writes and read skew, and lost update too in engines that detect it. It doesn't prevent write skew, and it doesn't prevent write skew through a phantom, as in the room booking.
The reason is in the design, not a weakness of any one implementation. Snapshot isolation only detects conflicts between transactions that wrote the same row. In write skew, the two transactions write different rows, so there's nothing to compare.
4. Serializable costs aborts, not latency
People expect stronger isolation to mean slower transactions, so this surprises them. Serializable snapshot isolation, the method PostgreSQL uses, is optimistic. It lets transactions run, and it aborts one, usually at commit, when it finds a conflict. So the cost shows up as a failure rate rather than as time, and the failure rate rises with contention.
Transaction takes 10 ms. Every abort is retried until it
succeeds. Expected attempts is 1 / (success rate).
abort rate attempts effective time
5% 1.05 10.5 ms
20% 1.25 12.5 ms
40% 1.67 16.7 ms
60% 2.50 25.0 ms
80% 5.00 50.0 ms
─────────────────────────────────────────────────
Contention raises the abort rate, which raises the
retry load, which raises contention. The curve bends
the wrong way, exactly like a queue near saturation.This has two consequences. First, every caller of a serializable transaction needs retry logic, and the retry has to be safe to run twice. So the transaction must be idempotent, meaning that running it twice has the same effect as running it once, or it must have no effects outside the database. Second, keep serializable transactions short and narrow. The longer a transaction holds its read set, the rows it has read, the more likely something conflicts with it.
5. A stronger level can hide a bug instead of fixing it
If turning on serializable makes a problem go away, you've learned that you had a write skew. You haven't learned where the invariant lives, or who else might break it.
The setting only protects the transactions that use it. Your migration scripts, your data-fix jobs, your analytics writer and anyone at a console run at the default level, so the setting doesn't stop them. A unique index or a check constraint applies to all of them, costs nothing per transaction, and is visible to the next person who reads the schema.
Treat "serializable fixed it" as a diagnosis rather than a solution.
6. Reading a replica downgrades your consistency silently
Nothing in your transaction changes when somebody points a read at a replica. The isolation level is the same. The SQL is the same. But the consistency you have has moved from the top row of the grid to the bottom.
This is the most common way a system ends up in the bottom-right corner of the grid. It has strict transactions on the primary, reads that can be any amount out of date, and no document that describes the two together.
Point reads at the replica because reads are cheap there
The primary is busy and the replica is idle, so move the reads. It's the obvious optimisation, and it works for most of the reads.
It's dangerous because the change is invisible where the read is made, at the call site. Somebody edits a connection string or a routing rule, and every read in the application moves from the top of the grid to the bottom. No type changed, no function signature changed, and no test failed. The reads that couldn't tolerate old data now get old data. You find out from a support ticket months later, with no way to tell which reads were affected.
Classify every read by whether it tolerates staleness, then route accordingly
Go through the read paths. A read goes to the primary if the user is about to act on it in a way that can't be undone, if the user just wrote it, or if another channel has already told them about it. Everything else, which is most reads, goes to a replica.
This is correct, and worth doing. Name its weakness yourself. The classification lives in somebody's head and in one code review. The next engineer who adds a read has no way to know the rule exists, so the classification goes out of date.
Make staleness tolerance part of the interface, so it cannot be chosen by accident
Stop treating staleness as a routing decision. Make it something the caller has to state explicitly.
In practice that means two separate methods, or a required parameter, instead of one method whose behaviour depends on configuration. getOrderForDisplay() and getOrderForCharging() are different operations with different guarantees. When the name says so, the choice is made at the call site, where the person writing the call can see what it means. A required staleness argument with no default does the same job.
This is the staff answer, not a matter of style, because it turns a decision that goes out of date into one nobody can make by accident. A new engineer adding a read has to answer the question, because the compiler or the code review won't let them past it. And when somebody later wants to move more reads to replicas, they search for one method name instead of digging through every query in the codebase.
What it costs: a slightly longer interface, and a one-time pass to classify the existing calls. You'd have to do that pass anyway. This way you only do it once.
7. Convergence is not correctness
Conflict-free replicated data types (CRDTs) are useful, and they're often oversold. A CRDT is a data type whose replicas each accept updates and later merge them without conflicts. It guarantees that replicas which have seen the same set of updates agree on the result. That's called convergence.
It does not guarantee that your invariant holds. A CRDT counter converges perfectly, and it still can't enforce "never below zero". If the counter is at 1 and two replicas each decrement it on their own, both replicas converge on minus one. Convergence tells you the replicas agree. It says nothing about whether the value they agree on is allowed.
So CRDTs work well for data that only needs to converge, such as counters nobody acts on, presence indicators that show who is online, or collaborative text. They don't replace a constraint.
8. Believing the documentation instead of testing it
The names are this unreliable, so the only way to know what your database does is to make it do it.
Fortunately, this is easy to check. Two database sessions and 5 minutes will reproduce write skew. Open two terminals and begin a transaction in each. Run the same read in both, then have each one write a different row, then commit both. If both commits succeed, your isolation level permits write skew, whatever its name claims. The same test for lost update is even shorter. If you run these against your actual engine, at your actual version, with your actual configuration, you'll know instead of assuming.
For the harder cases, good tools exist. Kyle Kingsbury's Jepsen project, and the Elle checker it uses to find transaction anomalies, exist because what vendors claim and what databases do differ often enough to need systematic testing. Jepsen's published analyses are also a good way to learn what these anomalies look like when they happen.
The habit to build is small: for any invariant you depend on, write a test that tries to break it. The test opens two concurrent connections, runs the operation you care about, and asserts that the invariant still holds. It's a normal integration test, it runs in your pipeline, and it catches the day somebody changes the isolation level or moves a read to a replica.
If you memorise nothing else
| A model is a list of forbidden anomalies | not a level of goodness |
| There are two families, and they are orthogonal | isolation, and replication |
| Isolation cannot fix a stale read | and reading the leader cannot fix write skew |
| Serializable forbids 6 anomalies of 11 | and cannot address the other 5 at any price |
| Snapshot isolation permits write skew | which is the one people assume it stops |
| Write skew writes different rows | so row-level conflict detection sees nothing |
| You cannot lock a row that does not exist | which is why phantoms need predicate locks |
| A unique index beats an isolation level | it is visible, free, and binds every writer |
| Serializable costs aborts, not latency | so every caller needs safe retry logic |
| MySQL's "repeatable read" permits write skew | per Jepsen; never reason from the name |
| Four session guarantees kill 4 of 5 replication anomalies | for no coordination at all |
| Most "strong consistency" needs are read-your-writes | the cheapest guarantee on the list |
| Convergence is not correctness | a CRDT counter will happily reach minus one |
| Every cache is a replica | so every TTL you set is a consistency decision |
| Bounded staleness is the only model with a number | "eventual" cannot be verified or violated |
| Two terminals reproduce write skew in 5 minutes | test it, do not read about it |
What is expected at each level
Mid-level
Know the anomalies by name and know there are two families.
You should be able to describe a dirty read, a lost update and a stale read. You should be able to say that isolation levels are about transactions, and replication consistency is about replicas. You should know that your database has a default isolation level, and want to know which one it is.
You aren't expected to tell write skew from a phantom without a prompt, or to know the session guarantees by name. You are expected not to say "we need strong consistency" as if it were a specification.
Senior
Name the anomaly, place it in the right family, pick the weakest fix.
Describe the bad outcome as a story before naming any level. An answer that starts with a level rather than an anomaly is the most common senior-level miss in this area.
Know that snapshot isolation permits write skew, and be able to say why: the two transactions write different rows, so there is no conflict to detect. This one fact separates people who have read about the levels from people who understand them.
Know that serializable fails rather than waits, so callers need retry logic and the transaction must be safe to run twice.
Reach for read-your-writes rather than linearizability for the many complaints that are really about a user not seeing their own change.
Staff+
The shift is from choosing a guarantee to removing the need for one.
Put the invariant in the schema. A unique index, a check constraint, or a materialised conflict row makes the rule visible, free, and binding on every writer, including the ones who aren't running your transaction. Reaching for this before an isolation level is the strongest move available here.
Notice which family the problem is in before proposing anything, and be willing to say that a proposed fix can't work because it's on the wrong axis.
Treat the combination as the guarantee. Serializable transactions with reads from an asynchronous replica is a real, common configuration, and usually nobody has written it down. Being the person who writes it down is worth more than tightening either half.
Turn on the cheap guarantees by default. Session guarantees remove four of the five replication anomalies with no coordination. Leaving them off and then buying linearizability is the most expensive way to solve the wrong problem.
Know what you would not do. You wouldn't set serializable globally, or choose an isolation level without naming an anomaly. You wouldn't use a CRDT where an invariant is required, or read from a replica without asking the caller whether it tolerates old data. And you wouldn't reason from the name of an isolation level in any database.
Sources
- Hal Berenson, Philip Bernstein, Jim Gray, Jim Melton, Elizabeth O'Neil and Patrick O'Neil, A Critique of ANSI SQL Isolation Levels, SIGMOD 1995, also available as Microsoft Research MSR-TR-95-51. Shows that the ANSI definitions don't describe the isolation levels real systems implement, and defines snapshot isolation as the category the standard was missing. Almost every naming problem in this area starts here.
- Doug Terry, Alan Demers, Karin Petersen, Mike Spreitzer, Marvin Theimer and Brent Welch, Session Guarantees for Weakly Consistent Replicated Data, PDIS 1994, pages 140 to 149. Where read-your-writes, monotonic reads, monotonic writes and writes-follow-reads were named, out of the Bayou project at Xerox PARC. Terry's later "Replicated data consistency explained through baseball" is the friendliest introduction to the same ideas.
- Kyle Kingsbury, Jepsen: MySQL 8.0.34. Testing that shows MySQL's "repeatable read" permits write skew, and also read skew and lost update, so it provides neither repeatable read nor snapshot isolation as normally defined. It's the clearest evidence that isolation level names can't be trusted.
- Microsoft, Consistency levels in Azure Cosmos DB. Five levels: strong, bounded staleness (bounded by k versions or t seconds), session, consistent prefix and eventual. The account sets a default, and a request can relax it. It shows clearly that consistency is chosen per operation rather than per database, and it's one of very few products that names session consistency as a level of its own.
- Martin Kleppmann, Please stop calling databases CP or AP, 2015. It makes the point that serializability and linearizability are separate properties, and that PostgreSQL's serializable snapshot isolation provides the first without the second. His book develops at length the idea of materialising conflicts to make write skew detectable.