Data integrity and uptime
medium 30 minWhen copies of your data cannot talk to each other you must choose: refuse some requests and stay correct, or answer and repair differences later.
Video lesson · Chapter 1 of 6
Who must hear a write?
CAP without the triangle
1:25Reel coming soon
Theory
Read or listen first. About 2 min.
What it is
Data integrity means the data is correct, complete and not lost: an account never shows money that is not there, and an order that was confirmed still exists. Uptime means the system answers.
As long as there is one copy on one machine, the two do not fight. Availability needs copies, and copies need to be told about every change. When the message cannot get through, you can wait for it, which costs uptime, or carry on without it, which costs agreement between the copies.
Why it exists
Machines die and networks break, so this is not a rare question. It decides whether a shop may sell its last item twice, whether a chat shows an old message, and whether a bank machine gives out cash while the line is down.
There is no single right answer for a company, only for an operation. A like counter that is wrong for a second is fine. A payment that is taken twice is not. Good designs mix both and say where.
A short history
1983
Härder and Reuter coin ACID: the promises of a transaction, with consistency and durability among them.
2000
Eric Brewer presents the CAP principle as a conjecture at the PODC conference.
2002
Seth Gilbert and Nancy Lynch publish a formal proof of it.
2007
Amazon publishes the Dynamo paper: a store where a shopping cart can always be written to, and differences are merged later.
2010
Daniel Abadi describes PACELC: also without a partition you trade latency against consistency.
2012
Brewer writes "CAP Twelve Years Later" and warns that "two of three" is misleading.
Words to know
- Consistency (CAP)
- Every read sees the latest completed write, as if there were one copy (linearizable).
- Availability (CAP)
- Every working node answers every request, without an error.
- Partition
- Nodes are alive but cannot reach each other.
- Quorum
- How many copies must agree, often a majority: N/2 + 1 rounded down first.
- Stale
- An older value than the latest.
- Conflict
- Two different changes to the same thing, neither knowing of the other.
- RPO
- Recovery point objective: how much recent data you may lose, as time.
- RTO
- Recovery time objective: how long you may be down.
How it works
Step through the idea, or press Play.
Name the operation. Pay, reserve, like, read a feed: each is its own decision
Understand it
Start here
The classroom
Imagine a teacher who asks the class a question. There are two ways to answer. In the same answer way the pupils talk first and all say the same thing: it takes longer, but they agree. In the fast answer way everybody speaks at once: quick, but the answers may differ.
The last two pictures are the whole CAP theorem. The wall is not your choice. What the lonely pupil does is.
Integrity first
- "I would rather refuse than tell you something wrong"
- Payments, stock, medical records
- Costs waiting, and errors during a partition
Uptime first
- "I will always answer, perhaps with old data"
- Feeds, counters, analytics
- Costs stale reads, conflicts and repair work
The theorem
What CAP really says
C: consistency
Reads see the latest completed write, as if there were one copy.
A: availability
Every working node answers every request.
P: partition tolerance
The system keeps its promise although messages between nodes are lost.
PACELC, the fuller version
Three common misunderstandings
| Claim | Better |
|---|---|
| "Pick two of three" | You do not pick P. And outside a partition you may have C and A together |
| "CA systems exist" | One machine has no partition inside, so CAP says nothing about it. It is simply down when it is down |
| "Product X is CP" | It depends on settings and on the operation: majority writes and single-copy reads are different choices |
Partition
What happens when the link breaks
West has two copies, East has one
| Consistency first (CP) | Availability first (AP) | |
|---|---|---|
| West (2 of 3) | Works: it has a majority | Works |
| East (1 of 3) | Refuses writes and consistent reads | Accepts both |
| Stale data | None | Possible |
| After the link heals | East catches up | Differences must be merged |
| Users in the east see | An error, or a read-only page | A normal page, perhaps old |
The same write in both worlds
Models
From strongest to weakest
Consistency models
| Model | Promise | Example |
|---|---|---|
| Linearizable | Every operation takes effect at one moment, in real-time order | Locks, leader election, a balance you may not overdraw |
| Sequential | Everybody sees one order, but it may lag behind the clock | A replicated log read by followers |
| Causal | A reply is never seen before the message it answers | Comment threads |
| Session (read your writes) | You see your own changes | Editing your profile |
| Bounded staleness | Never older than a limit, such as 5 seconds | A dashboard |
| Eventual | If writes stop, all copies become equal | Like counters |
Strong against eventual
| Strong | Eventual | |
|---|---|---|
| A write is confirmed | When enough copies have it (a majority, or the required standby) | After the first copy; the others follow |
| A read | Latest value | May be stale |
| Good | Easy to reason about | Fast, stays available |
| Bad | Waits, and may refuse during a partition | Conflicts need rules |
Replication
When is a write safe?
| Mode | Confirm after | If the primary dies | Write cost |
|---|---|---|---|
| Asynchronous | The primary | The last moments may be lost | Lowest |
| Semi-synchronous | The primary and one replica has received it | Safe as long as that replica survives | One round trip |
| Synchronous / majority | The primary and the required copies have stored it | Nothing confirmed is lost, if a copy survives | Slowest of the required copies |
How much can be lost?
Asynchronous failover, step by step
Quorum
The middle: ask a majority
Overlap
Uptime of each choice (three copies, each up 99%)
Common settings for N = 3
| W | R | Overlap? | Survives for writes | Survives for reads | Use |
|---|---|---|---|---|---|
| 3 | 1 | Yes | 0 lost copies | 2 lost copies | Rare writes, many reads |
| 2 | 2 | Yes | 1 | 1 | The balanced default |
| 1 | 3 | Yes | 2 | 0 | Many writes, rare reads |
| 1 | 1 | No | 2 | 2 | Counters, logs, feeds |
Trade-offs
Side by side
| Integrity first | Uptime first | |
|---|---|---|
| Write latency | At least a round trip to the required copies | Local |
| Between zones (assumed 1 to 2 ms) | Small cost | No cost |
| Between continents (assumed 80 ms) | 80 ms on every write | No cost |
| Read freshness | Latest | May be stale |
| During a partition | May refuse | Answers |
| Confirmed data lost | None while a required copy survives | Possible |
| Conflicts | Prevented | Must be resolved |
| Good for | Money, stock, records, leader election, configuration | Feeds, analytics, carts with merging, sessions, caches |
Which one for this operation?
Strategies
You do not have to pick one side
| Strategy | How | Gain |
|---|---|---|
| Quorum reads and writes | W + R > N, for example 2 and 2 of 3 | Fresh reads, survives one loss |
| Read your writes | Send a user's reads to the primary, or to a copy that has reached the version of their last write | Your own edit never disappears |
| Conflict resolution | Last write wins, merge both, or the application decides | Writes are possible everywhere |
| Tunable consistency | Per query: payments QUORUM, analytics ONE | Pay for strength only where needed |
| Degraded mode | Read-only, or limited amounts, during a partition | Useful and still correct |
A shop uses all of them
| Operation | Choice | Why |
|---|---|---|
| Payment, stock deduction, order confirmation | Strong (transaction) | A mistake costs money and trust |
| Profile, preferences | Quorum, or primary with read your writes | Fresh for the owner, short waits are fine |
| Shopping cart | Available, merged; checked strongly at checkout | Always be able to add an item |
| Product views, review counts, recommendations | Eventual | Old numbers hurt nobody |
Real systems
It depends on the setting
| System | Default or usual | Can be turned |
|---|---|---|
| PostgreSQL | One primary, ACID, asynchronous replicas | Synchronous standbys; replicas may be stale |
| MongoDB | One primary per replica set, majority writes by default | Read and write concerns per operation |
| etcd | Raft, linearizable reads by default | Serializable reads: faster, may be stale |
| ZooKeeper | Zab, ordered writes by majority | Reads are local and may lag; sync first for the latest |
| Redis Cluster | Asynchronous, can lose confirmed writes | WAIT reduces the risk but does not make it strong |
| Cassandra | Consistency level per query | ONE, QUORUM, ALL and others |
| DynamoDB | Eventually consistent reads by default | Strongly consistent reads of tables on request |
| CouchDB | Several writers, conflicts kept as revisions | The application resolves |
| Riak, Voldemort | Dynamo style, versions and repair | N, R and W per request |
More than copies
Other ways integrity is lost
- 1
A bug or a wrong delete
Replication copies the mistake within a second. Only backups and point-in-time recovery help.
- 2
Half an operation
Money taken, order not stored. Use one transaction, or steps that can be repeated and undone.
- 3
The same request twice
A retry after a timeout. Use an idempotency key.
- 4
Silent corruption
A bad disk or cable. Use checksums, and read backups back.
- 5
Bad values
Constraints in the database: not null, unique, foreign key,
stock >= 0.
Summary
The whole topic in one minute.
Copies give uptime, and keeping copies in agreement costs uptime when the network breaks. CAP says only this: during a partition, an operation either refuses or risks being out of date. The rest of the time the trade is latency.
Wait for a majority when a wrong answer is expensive. Answer from any copy, and merge later, when no answer is worse than an old one. Choose per operation, write down RPO and RTO, and protect integrity with transactions, constraints, checksums and tested backups too.
- During a partition an operation either refuses or risks being out of date. That is all CAP says.
- Without a partition the trade is latency against consistency.
- Strong needs a majority, not all copies: 97.03% against 99.97% with three copies of 99%.
- W + R > N gives overlap. It does not order concurrent writes.
- Choose per operation, and state RPO and RTO.