Database Consistency Models
What you will learn
- Why "consistency" has more than one meaning
- Strong (linearizable) consistency and eventual consistency
- Two useful middle guarantees: read your own writes and monotonic reads
- How a quorum (N, W, R) works
- Why
W + R > Ngives fresh reads, and what it does not guarantee
All code in this lesson is a simulation that imitates an idea. It is not a real database. You can run each block on its own.
1. Two meanings of "consistent"
The word is used for two different things:
- In ACID (lesson 6.3), consistency means a transaction moves the database from one valid state to another, so that your rules (keys, constraints) always hold.
- In distributed systems, consistency is about copies: when the same data lives on several machines, do all readers see the same, latest value?
This lesson is about the second meaning. Because copies are updated over a network (lesson 14.2), there is a window in which they differ. A consistency model is a promise about what readers may see during and after that window.
2. The main models
| Model | The promise | Cost |
|---|---|---|
| Strong (linearizable) | Every read returns the latest completed write, as if there were a single copy | slower: machines must coordinate; may refuse requests during a network failure (lesson 14.5) |
| Eventual | If writes stop, all copies eventually become the same. Until then, reads may be stale | fastest and most available; the application must cope with stale or conflicting data |
| Read your own writes | After you write, you always see your write (others may still see old data) | needs routing: read from the primary or a replica known to be up to date |
| Monotonic reads | Once you have seen a value, you never see an older one later | needs sticky routing, for example the same replica for the same user |
The middle two are guarantees that applications often add on top of eventual consistency, because they match what users expect: "I saved my profile, so I should see it" and "the page should not go back in time".
The opposite of strong consistency is sometimes described as "weaker", but weaker models are not wrong. A like counter that is a few seconds behind harms nobody; a bank balance that is behind can.
3. Quorums: choosing how many copies to ask
Some systems keep N copies and let you choose, for each operation, how many copies must answer:
- W: how many copies must confirm a write before the write is acknowledged
- R: how many copies a read asks (the reader keeps the answer with the newest version)
The key rule: if W + R > N, every read set and every write set overlap in at least one copy, so a read always includes at least one copy that has the latest acknowledged write. Here is a simulation with N = 3, W = 2, R = 2. Randomness decides which copies answer, so the simulation fixes the seed (random.seed(7)) to make the output repeatable:
import random
random.seed(7)
class Replica:
def __init__(self, name):
self.name = name
self.value = None
self.version = 0
self.up = True
replicas = [Replica("r1"), Replica("r2"), Replica("r3")]
N, W, R = 3, 2, 2
def write(value, version, w):
"""Store on the first w available replicas (a random few answer in time)."""
acks = 0
order = replicas[:]
random.shuffle(order)
for r in order:
if r.up and acks < w:
r.value, r.version = value, version
acks += 1
return acks >= w, [r.name for r in order if r.version == version]
def read(r_count):
"""Ask r_count random replicas and keep the answer with the newest version."""
order = replicas[:]
random.shuffle(order)
answers = [(r.version, r.value, r.name) for r in order if r.up][:r_count]
return max(answers), [a[2] for a in answers]
ok, where = write("v1", 1, 3)
print("initial write to all:", ok)
ok, where = write("v2", 2, W)
print("write v2 with W=2 acknowledged:", ok, "stored on", sorted(where))
for i in range(5):
best, asked = read(R)
print(f" read with R=2 asked {sorted(asked)} -> {best[1]}")
print("W + R > N ?", W + R > N)
print()
print("Reading with R=1 five times:")
for i in range(5):
best, asked = read(1)
print(" asked", asked, "->", best[1])
initial write to all: True
write v2 with W=2 acknowledged: True stored on ['r1', 'r3']
read with R=2 asked ['r2', 'r3'] -> v2
read with R=2 asked ['r1', 'r3'] -> v2
read with R=2 asked ['r1', 'r2'] -> v2
read with R=2 asked ['r2', 'r3'] -> v2
read with R=2 asked ['r1', 'r3'] -> v2
W + R > N ? True
Reading with R=1 five times:
asked ['r2'] -> v1
asked ['r3'] -> v2
asked ['r2'] -> v1
asked ['r2'] -> v1
asked ['r1'] -> v2
Read the output:
- The first write reached all three copies. The second write (
v2) was acknowledged after only two copies,r1andr3, stored it;r2still holds the oldv1. - Every read with R = 2 returned
v2, even when it askedr2(stale) together with another copy. Two copies out of three always include at least one that hasv2, because2 + 2 > 3. - With R = 1, a read sometimes asks
r2alone and returns the stalev1. This is eventual consistency in action: fast, but not always fresh.
(The output is repeatable only because of random.seed(7); other seeds pick other copies.)
Every possible read set in SQL. This lesson runs on the sample database you chose in lesson 4.1 (use the Example data picker at the top). Instead of random choices, a query can list all ways of asking R copies and show what each read returns. The copies table is a small one of its own (the write of v2 reached r1 and r3, but not r2); Reset data removes it.
CREATE TABLE copies (name TEXT PRIMARY KEY, value TEXT, version INTEGER);
INSERT INTO copies VALUES ('r1', 'v2', 2), ('r2', 'v1', 1), ('r3', 'v2', 2);
(3 rows changed)
With R = 2 there are three ways to choose the copies to ask. Each read keeps the newest version it sees:
SELECT a.name || ' + ' || b.name AS asked,
CASE WHEN a.version >= b.version THEN a.value ELSE b.value END AS read_returns
FROM copies a JOIN copies b ON a.name < b.name
ORDER BY asked;
asked read_returns
------- ------------
r1 + r2 v2
r1 + r3 v2
r2 + r3 v2
(3 rows)
With R = 1 each copy is read alone:
SELECT name AS asked, value AS read_returns FROM copies ORDER BY name;
asked read_returns
----- ------------
r1 v2
r2 v1
r3 v2
(3 rows)
CREATE TABLE copies (name TEXT PRIMARY KEY, value TEXT, version INTEGER);
INSERT INTO copies VALUES ('r1', 'v2', 2), ('r2', 'v1', 1), ('r3', 'v2', 2);
(3 rows changed)
With R = 2 there are three ways to choose the copies to ask. Each read keeps the newest version it sees:
SELECT a.name || ' + ' || b.name AS asked,
CASE WHEN a.version >= b.version THEN a.value ELSE b.value END AS read_returns
FROM copies a JOIN copies b ON a.name < b.name
ORDER BY asked;
asked read_returns
------- ------------
r1 + r2 v2
r1 + r3 v2
r2 + r3 v2
(3 rows)
With R = 1 each copy is read alone:
SELECT name AS asked, value AS read_returns FROM copies ORDER BY name;
asked read_returns
----- ------------
r1 v2
r2 v1
r3 v2
(3 rows)
CREATE TABLE copies (name TEXT PRIMARY KEY, value TEXT, version INTEGER);
INSERT INTO copies VALUES ('r1', 'v2', 2), ('r2', 'v1', 1), ('r3', 'v2', 2);
(3 rows changed)
With R = 2 there are three ways to choose the copies to ask. Each read keeps the newest version it sees:
SELECT a.name || ' + ' || b.name AS asked,
CASE WHEN a.version >= b.version THEN a.value ELSE b.value END AS read_returns
FROM copies a JOIN copies b ON a.name < b.name
ORDER BY asked;
asked read_returns
------- ------------
r1 + r2 v2
r1 + r3 v2
r2 + r3 v2
(3 rows)
With R = 1 each copy is read alone:
SELECT name AS asked, value AS read_returns FROM copies ORDER BY name;
asked read_returns
----- ------------
r1 v2
r2 v1
r3 v2
(3 rows)
Every pair includes at least one copy that holds v2, so every R = 2 read returns v2. With R = 1, the read of r2 returns the stale v1. That is the rule W + R > N in numbers: the write set {r1, r3} overlaps every read set of size 2.
Choosing the numbers is a trade:
| Setting | Writes | Reads | Freshness |
|---|---|---|---|
| W = N, R = 1 | slow, fail if any copy is down | fast | fresh |
| W = 1, R = N | fast | slow | fresh |
| W = 2, R = 2 (N = 3) | medium | medium | fresh, and tolerates one copy being down |
| W = 1, R = 1 | fastest | fastest | may be stale |
Quick check: with N = 5, is W = 3 and R = 3 enough for fresh reads?
Yes: 3 + 3 = 6, which is more than 5, so any 3 copies that confirmed the write overlap with any 3 copies that are read.
4. What a quorum does not promise
W + R > N is a useful rule, but it is not the same as strong consistency in every case. Real systems must handle situations that this simulation ignores, such as writes that succeeded on fewer than W copies and were then reported as failed, copies that come back with old data after a failure, and two clients writing at the same moment. Always read the documentation of a specific product to see exactly what it promises under each setting; this lesson does not claim any product's behaviour.
5. Adding the missing guarantees
If a system is eventually consistent but users expect to see their own changes, the application can add a guarantee:
# Simulation: "read your own writes" by remembering the version a user has written.
primary = {"name": "Rina", "version": 1}
replica = {"name": "Rina", "version": 1} # a lagging copy
def save_name(session, new_name):
primary["version"] += 1
primary["name"] = new_name
session["min_version"] = primary["version"] # remember what this user wrote
def read_name(session):
# use the replica only if it is new enough for this user, otherwise ask the primary
if replica["version"] >= session.get("min_version", 0):
return replica["name"], "replica"
return primary["name"], "primary"
session = {}
print("before saving:", read_name(session))
save_name(session, "Rina Akter")
print("right after saving (replica is behind):", read_name(session))
replica.update(primary) # the replica catches up
print("after the replica catches up:", read_name(session))
before saving: ('Rina', 'replica')
right after saving (replica is behind): ('Rina Akter', 'primary')
after the replica catches up: ('Rina Akter', 'replica')
The user always sees their own save: while the replica lags, the read is sent to the primary; once the replica has caught up, reads return to the cheaper replica.
Worked example: choosing a model for each feature
A made-up social app decides what each feature needs:
| Feature | Model | Why |
|---|---|---|
| Number of likes on a post | eventual | a count a few seconds behind harms nobody |
| Profile edit page | read your own writes | the user must see the change they just saved |
| Message list scrolling | monotonic reads | messages must not disappear and reappear |
| Account balance for paid features | strong | stale data could grant or deny paid access wrongly |
Mixing models inside one application is normal. The cost of strong consistency is paid only where it is needed.
Common mistakes
- Mixing up ACID consistency and distributed consistency. One is about valid states, the other about copies agreeing.
- Assuming "eventual" means "soon" or "wrong". It promises convergence, with no fixed time, and many features are fine with it.
- Setting W = 1 and R = 1 for data that must be fresh.
- Believing
W + R > Nfixes everything. Failures and concurrent writes need more rules.
Key takeaways
- Distributed consistency asks whether all readers see the latest value of copied data.
- Strong consistency is the simplest to reason about but costs speed and availability; eventual consistency is fast but can return stale data.
- Read your own writes and monotonic reads are practical guarantees added to weaker systems.
- With N copies,
W + R > Nmakes every read overlap the latest acknowledged write. - Choose the model per feature, according to what a stale answer would cost.
Practice
1. What is the difference between consistency in ACID and consistency in distributed systems?
Show answer
In ACID it means a transaction leaves the database in a valid state that obeys all rules. In distributed systems it is about whether the copies of the data agree and readers see the latest value.
2. A user posts a comment and, after reloading, does not see it for a few seconds. Which guarantee was missing?
Show answer
Read your own writes: the read was served by a copy that had not yet received the comment.
3. With N = 3 and W = 2, what is the smallest R that guarantees a fresh read?
Show answer
R = 2, because W + R must be more than N: 2 + 2 = 4 > 3. (R = 1 gives 2 + 1 = 3, which is not more than 3.)
4. In the simulation, why could a read with R = 1 return v1 after v2 was acknowledged?
Show answer
It asked only r2, which had not received v2. A single copy chosen at random may be one that missed the write.
5. Give one feature where eventual consistency is acceptable and one where it is not.
Show answer
Acceptable: a view counter or like count. Not acceptable: for example a payment balance or stock count where a stale value could cause a wrong decision.
6. Why does the lesson say not to rely on W + R > N alone for a real product?
Show answer
Because real systems also face failed or partial writes, copies returning with old data and concurrent writers. What a product actually guarantees must be read from its own documentation.