AlgoViz

Data integrity and uptime

medium 30 min

When 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?

0:00 / 4:30

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

  1. 1983

    Härder and Reuter coin ACID: the promises of a transaction, with consistency and durability among them.

  2. 2000

    Eric Brewer presents the CAP principle as a conjecture at the PODC conference.

  3. 2002

    Seth Gilbert and Nancy Lynch publish a formal proof of it.

  4. 2007

    Amazon publishes the Dynamo paper: a store where a shopping cart can always be written to, and differences are merged later.

  5. 2010

    Daniel Abadi describes PACELC: also without a partition you trade latency against consistency.

  6. 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.

Step 1 of 3

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.

One question, three pupils
How manybooks?The question

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

Partitions are rare. The lower branch is every other second of the year, so it matters more in daily life.

Three common misunderstandings

ClaimBetter
"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

Data center West holds replica 1 and replica 2. Data center East holds replica 3. Users in the west write to replica 1, which copies to replica 2. Users in the east reach replica 3. The link between the two data centers is broken.
All three machines are alive. The only question is what East may do.
Consistency first (CP)Availability first (AP)
West (2 of 3)Works: it has a majorityWorks
East (1 of 3)Refuses writes and consistent readsAccepts both
Stale dataNonePossible
After the link healsEast catches upDifferences must be merged
Users in the east seeAn error, or a read-only pageA normal page, perhaps old
A CP system is not all down: the majority side keeps working. An AP system is not all wrong: it repairs itself later.

The same write in both worlds

AP sold the last ticket twice. For a concert that is a refund. For a seat in an aeroplane it is a known, priced risk. For a medicine it is not acceptable.

Models

From strongest to weakest

Consistency models

ModelPromiseExample
LinearizableEvery operation takes effect at one moment, in real-time orderLocks, leader election, a balance you may not overdraw
SequentialEverybody sees one order, but it may lag behind the clockA replicated log read by followers
CausalA reply is never seen before the message it answersComment threads
Session (read your writes)You see your own changesEditing your profile
Bounded stalenessNever older than a limit, such as 5 secondsA dashboard
EventualIf writes stop, all copies become equalLike counters
Stronger is easier to program against and costs more waiting.

Strong against eventual

StrongEventual
A write is confirmedWhen enough copies have it (a majority, or the required standby)After the first copy; the others follow
A readLatest valueMay be stale
GoodEasy to reason aboutFast, stays available
BadWaits, and may refuse during a partitionConflicts need rules
Strong does not mean waiting for all copies. If all must confirm, one dead copy stops every write.

Replication

When is a write safe?

ModeConfirm afterIf the primary diesWrite cost
AsynchronousThe primaryThe last moments may be lostLowest
Semi-synchronousThe primary and one replica has received itSafe as long as that replica survivesOne round trip
Synchronous / majorityThe primary and the required copies have stored itNothing confirmed is lost, if a copy survivesSlowest of the required copies

How much can be lost?

lost writes≈lag×write rate2 s×500/s=1,000 writes\text{lost writes} \approx \text{lag} \times \text{write rate} \qquad 2\,\text{s} \times 500/\text{s} = 1{,}000\ \text{writes}
This is your RPO in practice. With an asynchronous replica 2 seconds behind (assumed), a failover loses 1,000 confirmed writes.

Asynchronous failover, step by step

The client was told yes. That is the painful part of losing a confirmed write.

Quorum

The middle: ask a majority

Overlap

W+R>NN=3, W=2, R=2:2+2>3W + R > N \qquad N = 3,\ W = 2,\ R = 2:\quad 2 + 2 > 3
WW copies confirm a write and RR copies answer a read. Then every read meets at least one copy with the newest write. Keep a version with each value, so that the reader can tell which is newest.

Uptime of each choice (three copies, each up 99%)

all 3:0.993=97.03%majority 2:0.993+3⋅0.992⋅0.01=99.97%any 1:1−0.013=99.9999%\begin{aligned} \text{all } 3:&\quad 0.99^3 = 97.03\% \\ \text{majority } 2:&\quad 0.99^3 + 3 \cdot 0.99^2 \cdot 0.01 = 99.97\% \\ \text{any } 1:&\quad 1 - 0.01^3 = 99.9999\% \end{aligned}
Waiting for all is worse than a single machine. A majority gives overlap and still survives one loss.

Common settings for N = 3

WROverlap?Survives for writesSurvives for readsUse
31Yes0 lost copies2 lost copiesRare writes, many reads
22Yes11The balanced default
13Yes20Many writes, rare reads
11No22Counters, logs, feeds

Trade-offs

Side by side

Integrity firstUptime first
Write latencyAt least a round trip to the required copiesLocal
Between zones (assumed 1 to 2 ms)Small costNo cost
Between continents (assumed 80 ms)80 ms on every writeNo cost
Read freshnessLatestMay be stale
During a partitionMay refuseAnswers
Confirmed data lostNone while a required copy survivesPossible
ConflictsPreventedMust be resolved
Good forMoney, stock, records, leader election, configurationFeeds, analytics, carts with merging, sessions, caches

Which one for this operation?

Strategies

You do not have to pick one side

StrategyHowGain
Quorum reads and writesW + R > N, for example 2 and 2 of 3Fresh reads, survives one loss
Read your writesSend a user's reads to the primary, or to a copy that has reached the version of their last writeYour own edit never disappears
Conflict resolutionLast write wins, merge both, or the application decidesWrites are possible everywhere
Tunable consistencyPer query: payments QUORUM, analytics ONEPay for strength only where needed
Degraded modeRead-only, or limited amounts, during a partitionUseful and still correct

A shop uses all of them

OperationChoiceWhy
Payment, stock deduction, order confirmationStrong (transaction)A mistake costs money and trust
Profile, preferencesQuorum, or primary with read your writesFresh for the owner, short waits are fine
Shopping cartAvailable, merged; checked strongly at checkoutAlways be able to add an item
Product views, review counts, recommendationsEventualOld numbers hurt nobody
The strong check at checkout is what makes a relaxed cart safe.

Real systems

It depends on the setting

SystemDefault or usualCan be turned
PostgreSQLOne primary, ACID, asynchronous replicasSynchronous standbys; replicas may be stale
MongoDBOne primary per replica set, majority writes by defaultRead and write concerns per operation
etcdRaft, linearizable reads by defaultSerializable reads: faster, may be stale
ZooKeeperZab, ordered writes by majorityReads are local and may lag; sync first for the latest
Redis ClusterAsynchronous, can lose confirmed writesWAIT reduces the risk but does not make it strong
CassandraConsistency level per queryONE, QUORUM, ALL and others
DynamoDBEventually consistent reads by defaultStrongly consistent reads of tables on request
CouchDBSeveral writers, conflicts kept as revisionsThe application resolves
Riak, VoldemortDynamo style, versions and repairN, R and W per request
Never answer with a product name alone. Say the product and the setting.

More than copies

Other ways integrity is lost

  1. 1

    A bug or a wrong delete

    Replication copies the mistake within a second. Only backups and point-in-time recovery help.

  2. 2

    Half an operation

    Money taken, order not stored. Use one transaction, or steps that can be repeated and undone.

  3. 3

    The same request twice

    A retry after a timeout. Use an idempotency key.

  4. 4

    Silent corruption

    A bad disk or cable. Use checksums, and read backups back.

  5. 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.

Sources