AlgoViz

Trade-offs in databases

medium 30 min

Every database trades freshness, speed, safety and uptime against each other.

Video lesson · Chapter 1 of 5

Five copies and one shared witness

0:00 / 3:54

R + W > N in 75 seconds

1:15Reel coming soon

Theory

Read or listen first. About 2 min.

What it is

A database can be fast, always up, always fresh and never lose anything, but not all of these to the full at once. Trade-offs are the settings where more of one means less of another.

The clearest example is a store with several copies of each item. If a write must be confirmed by every copy, reads can ask any one of them, but a single sick copy stops all writes. If a write is confirmed by one copy, writing is quick, and reads may miss it.

Why it exists

No setting is right for everything. A bank transfer and a like button have different costs of being wrong, so they deserve different settings, even inside one product and one database.

Products often hide the trade behind defaults. A team that does not know its defaults has still made the choice, without looking. Knowing the dials lets you say what you bought and what you paid.

A short history

  1. 1979

    David Gifford publishes weighted voting for replicated data: read and write quorums that must overlap.

  2. 2007

    The Dynamo paper describes a store where N, R and W are set by the application. The common choice there is (3, 2, 2).

  3. 2012

    Daniel Abadi's PACELC paper adds the everyday trade of latency against consistency to CAP.

  4. 2016

    The RUM conjecture: reads, updates and memory, and the best of two costs you the third.

  5. 2022

    Amazon publishes the DynamoDB paper at USENIX ATC: a leader for each partition, elected with Multi-Paxos.

Words to know

N
How many copies of each item exist.
W
How many copies must confirm before a write counts as done.
R
How many copies must answer before a read returns.
Overlap
A copy that is in both the read set and the write set. Guaranteed when R + W > N.
Durability
A confirmed write survives failures.
Tunable consistency
Choosing the level for each query.
Read repair
A read that finds an old copy brings it up to date.
Sloppy quorum
Counting stand-in nodes when the proper ones are unreachable. It breaks the overlap.

How it works

Step through the idea, or press Play.

Step 1 of 3

Say what being wrong costs. Lost, stale, slow or refused

Understand it

Start here

A boat for the lake

Picture a lake with a small harbour that rents out three boats. The rowing boat is cheap and simple. The speedboat is quick but holds little. The ferry carries everything safely and takes its time. Asking which boat is best makes no sense until you say what you want to bring across.

Which boat today?
simple

The lake does not change. What you carry decides.

The telephone game has the same three styles. Very careful: whisper to all five friends before anybody goes on, slow and right. Very fast: tell one and hope. In between: make sure that three of the five know, quick enough and right enough.

The dials

N, R and W

The overlap rule

R+W>N;⇒;every read set shares at least R+W−N copies with every write setR + W > N ;\Rightarrow; \text{every read set shares at least } R + W - N \text{ copies with every write set}
N = 5, R = 3, W = 3: 3 + 3 = 6 > 5, so at least one copy that answers has the latest confirmed write.

Four settings for N = 5

SettingRWReadsWritesOverlap
Balanced, majorities33MediumMedium1 copy
Read-heavy15Fast, any copySlow, stop if one copy is down1 copy
Write-heavy51Slow, stop if one copy is downFast, least durable1 copy
Eventual11Fast, may be staleFast, least durableNone
Balanced and strong are the same numbers here. A common name for W = N is write all, read one.

Where the sets meet

Five copies. A write is confirmed by copies 1, 2 and 3. A read asks copies 3, 4 and 5. Copy 3 is in both sets, so the read sees the write.
Even in the worst case, with the sets as far apart as possible, three plus three out of five leaves one copy in common.

A quorum read with repair

Bad days

What a missing copy does

Chance that enough copies are up

P(≥q of 3)=∑k=q3(3k)pk(1−p)3−kp=0.99:;q=1:;99.9999%,;q=2:;99.9702%,;q=3:;97.0299%P(\ge q \text{ of } 3) = \sum_{k=q}^{3} \binom{3}{k} p^k (1-p)^{3-k} \qquad p = 0.99:; q=1:; 99.9999\%,; q=2:; 99.9702\%,; q=3:; 97.0299\%
Assuming independent copies, each up 99% of the time. Waiting for all three is less available than a single machine.

N = 3 with one copy down

R, WReadsWrites
2, 2Work, with 2 of 2 leftWork, with 2 of 2 left
1, 3WorkStop
3, 1StopWork
1, 1Work, may be staleWork
With 2, 2 a second failure stops both. That is the price of staying right.
  • Consistency

    How fresh and in what order are answers?

  • Availability

    Does it answer with copies or links missing?

  • Latency

    How many copies, and how far away, do we wait for?

  • Durability

    How many disks, in how many places, have the write when we say yes?

Three corners

Moving towards one corner moves away from another. Durability is the fourth dial behind the picture.

Time

Latency against freshness

An estimate for one read

Kind of readAsksAboutFreshness
Nearest copyAny copy1 msMay be old
Bounded stalenessA copy that is fresh enough1 to 5 msAt most so old
SessionA copy at my version1 to 10 msMy own writes
Strong, one regionLeader or majority nearby2 to 5 msLatest
Strong, across regionsA majority far away50 ms and moreLatest
Illustrative. Distance is what counts: roughly 1 to 5 ms inside a region, 50 to 100 ms between regions, 200 to 300 ms between far continents, for a round trip.

You wait for the q-th fastest

Tq=t(q){2,70,140} ms:T1=2,T2=70,T3=140T_q = t_{(q)} \qquad \{2, 70, 140\}\text{ ms}:\quad T_1 = 2,\quad T_2 = 70,\quad T_3 = 140
Sort the copies by their time. A quorum of q takes as long as the q-th. Putting a majority of copies in one region makes T2 small, at the price of losing both with the region.

Products

Tunable consistency in practice

Apache Cassandra: a level for each query

LevelCopies that must respond
ONE1
QUORUMA majority of all copies: n / 2 + 1, rounded down
LOCAL_QUORUMA majority in the coordinator's datacenter
ALLEvery copy
The driver sets the level for each statement; in cqlsh the command is CONSISTENCY QUORUM. It is not part of the SELECT text.

Amazon DynamoDB: a choice for each read

ReadFreshnessCost for an item up to 4 KB
Eventually consistent, the defaultMay be slightly oldHalf a read unit
Strongly consistentLatest confirmed write1 read unit, twice as much
TransactionalAll or nothing over several items2 read units
10,000 such reads a second: 5,000 units eventual or 10,000 strong. Global secondary indexes and streams are always eventually consistent.

MongoDB: write concern and read preference

SettingValueMeaning
Write concernw: 1The primary has it
Write concernw: "majority"A majority of the data-bearing voting members has it; the default
Write concernw: a numberThat many members have it
Read preferenceprimaryThe default
Read preferencesecondaryA secondary, may be old
Read preferencenearestLowest latency, may be old
Read preference says whom to ask. Read concern, a separate setting, says how safe the returned data must be.

PostgreSQL has the dial too. Streaming replication is asynchronous by default, so a failover may lose the last commits. synchronous_commit together with named standbys makes a commit wait for another machine.

Beyond copies

Other trades inside one machine

You wantYou pay withExample
Faster readsSlower writes and spaceOne more index
Faster writesSlower reads or later workA log-structured store that merges later
Less spaceProcessor timeCompression
Fewer joinsCopies to keep in stepDenormalised tables
Fewer anomaliesWaiting and retriesA higher isolation level
More machinesQueries across themSharding
The RUM conjecture names one version of this: read cost, update cost and memory. Improving any two makes the third worse.

Compare

Products and what they can be set to

DatabaseConsistency on offerUsual fit
PostgreSQLStrong on the primary; standbys may be behindMoney, orders, general use
CassandraTunable for each query, last write winsTime series, many writes
MongoDBTunable concerns, one primary for each setDocuments that change shape
DynamoDBEventual by default, strong on requestKey lookups at a steady fast pace
CockroachDBSerializable transactions over many machinesSQL across regions
One letter such as CP or AP hides the settings. See the CAP theorem and SQL or NoSQL.

Four businesses

BusinessNeedsA reasonable start
BankingStrong consistency and transactions; latency may be higherPostgreSQL, or CockroachDB across regions
Social feedLow latency and high availability; old is fineCassandra or DynamoDB
ShopStrong for orders and payments, eventual for catalogue and reviewsPostgreSQL with a cache, or MongoDB with majority writes
MetricsVery many writes, eventual is fine, time rangesCassandra or a time-series store such as InfluxDB
Starting points, not rules. Numbers and what the team can run decide.

One shop, three settings

A shop service uses a PostgreSQL primary with a synchronous standby for orders, Cassandra with level ONE for reviews, and a Redis cache for catalogue pages.
Orders wait for a second machine. Reviews are confirmed by one copy. Catalogue pages may be a minute old.

Decide

From cost of being wrong to numbers

Choosing R and W

R = 1 with W = N is rarely worth it: one failed copy stops all writes.

Durability

When yes must mean safe

A confirmed write should survive whatever you plan for: a disk, a machine, a zone. The number of separate places that have it before you say yes is W, and reading from more copies later cannot bring back what only one disk knew.

What can go wrong with W = 1

A confirmed write that lived on one disk only. The client did nothing wrong.

Choosing a setting in five steps

  1. 1

    Name the operation

    Place an order, show a review, count a view.

  2. 2

    Price the mistakes

    Stale, lost, refused, slow: what does each cost?

  3. 3

    Pick the setting

    Levels or numbers for this operation only.

  4. 4

    Remove one copy

    Does it still work? Remove a region.

  5. 5

    Write it down

    The setting, the reason and what would change it.

Summary

The whole topic in one minute.

Consistency, availability, latency and durability pull against each other, and replication makes the pull visible as N, R and W. When R + W > N every read set meets every write set. R = 1 makes reads quick and writes fragile, W = 1 the other way round, and majorities sit in the middle.

Choose for each operation from the cost of being wrong, not for the whole company. Read the defaults of your product, check what a failed copy does to each setting, and remember that overlap alone does not order concurrent writes.

  • Consistency, availability, latency and durability pull against each other.
  • R + W > N makes read and write sets meet.
  • R = 1, W = N reads fast but stops writing when one copy fails.
  • W = 1 is fast and least durable.
  • Read your product's defaults; they are choices too.
  • Choose for each operation from the cost of being wrong.

Sources