Trade-offs
Every design buys one thing by paying with another, because every machine has a limit. Before you sign, write a bill with two columns, what you get and what you pay. This book calls it a ledger.
A kitchen with one stove. The stove has four burners and never gets more: that is the Limit. Next to it is a shelf of jars of sauce made earlier: that is the Store. Orders arrive on paper tickets from the diner, the user on a phone or browser. The cook is the application: the program that takes each request and works out the answer.
The stove is where the real cooking happens. In a computer that is the database: the program that keeps the data and answers questions about it. Prepped sauce on the shelf is a cache. Plates leaving the pass per hour is the throughput. How long one diner waits for one plate is the latency. Money, time, memory, people, and attention all work like burners.
The shelf made a plate faster and created a problem. A jar made this morning, after the recipe changed at noon, is stale: that is staleness. The use-by date on the jar is the TTL, short for time to live. A short TTL means fresher food and more trips to the stove. A long TTL means faster plates and older sauce. One jar cannot give both.
The ledger
Before you argue for an option, answer three questions.
- What does it buy? A property you need, with a number.
- What does it pay? What gets worse, including the work of running it and new ways it can break.
- When is it wrong? The condition where the price beats the gain.
| Option in the kitchen | Buys | Pays | Wrong when |
|---|---|---|---|
| Sauce shelf (cache) | Faster plates, less stove time | Old jars, a use-by rule, a rush on an empty shelf | Every plate must use today's recipe |
| Cook many plates in one batch | More plates per hour | Each diner waits for the whole batch | One diner is waiting for a single dish |
| Write every order in the book before cooking | The order is in the book, not only the waiter's head: a durable record, so a crash loses none | A pause per order | Losing an order is cheap and speed is everything |
The axes
Name the axis you are moving along.
- Latency against throughput. Batching raises plates per hour and makes each diner wait longer.
- The same answer against an answer every time. Three pictures first:
- Same answer. Two cooks asked about the same jar give the same answer, and it is the latest: consistency.
- Always answering. Every working cook answers when called: availability.
- The wall. A wall goes up between two kitchens and nobody can pass notes: a partition.
- The choice, CAP. Each side of the wall must answer with what it knows (available, maybe old) or refuse until it can check (consistent, not available). Gilbert and Lynch proved it: CAP, from Consistency, Availability, Partition tolerance.
- Consistency against latency, even with no wall. Only for systems that keep copies in more than one place. This is PACELC: if there is a Partition, choose Availability or Consistency; Else, choose Latency or Consistency.
- Cost against complexity. Every new part is paid for forever, including the cook whose phone rings at night when the stove breaks, the on-call person.
- Waiting near the limit. In a steady state (long-run averages, not a sudden rush), orders in the kitchen, waiting or cooking, equal the arrival rate times the time each spends in the kitchen. That is Little's law, L = λW (L the orders in the kitchen, λ the arrival rate, W the time each spends there). It does not say how the wait grows. With one cook, wait grows roughly as one divided by (one minus the busy share): near always busy, one more order makes the line far longer.
- Which limit runs out first. The burner that is always full while the others sit idle is the binding limit. Spend effort there: more shelf space does nothing if the stove is the full one.
Entry
"A cache makes reads faster, but data can be out of date, so I use it where a little old data is fine."
Mid
"A cache buys read speed and pays with staleness and a rule for throwing jars out. I check how often the cook finds the jar on the shelf, the hit rate, before I trust it."
Senior
"I find the binding limit first, for example a stove already about 70 percent busy (a made-up figure for illustration) while the shelf is nowhere near full, then spend the trade-off there. I price the on-call cost too, and I pick the version I can reverse if my numbers are wrong."
Principal
"I write the trade-off on a one-page note pinned above the stove: what we chose, why, who owns it. I draw a red line on the whiteboard: cross it and we reopen the choice. That line is a reopen trigger, such as 'reopen when reads pass half the stove limit'. The price is paid knowingly, not discovered during an outage."
A good design does not remove the cost. It moves the cost to the place where it hurts least. If you cannot say where the cost went, you have not finished designing.
"Just add a cache, it makes everything faster."
The trap: you say cache, and the interviewer asks what is now worse.
The escape: say the cache buys read speed and pays with staleness, a rule for throwing jars out, and a new failure: when a hot jar expires, every cook runs to the same empty shelf and then the stove at once, a stampede. Then say which data may be old, and how old. Also wrong: moving the wrong axis (shaving milliseconds when correctness is the need) or building for scale you do not have.
Scenario: a profile page is slow. A teammate says add a cache.
- Clarify. Slow for whom, and since when? How wrong may a profile be? A minute of old data is fine, but a user must see their own edit at once.
- Primitives. Limit (the stove answers only so many reads), Store (the shelf holds copies).
- Numbers. Say about 200 reads per second (a read is a query: one question the cook asks the stove) hit a database that handles about 2000. The stove is not the limit yet: measure the slow part first.
- Options and ledger. One option per line, each with what it buys and pays:
- Add tabs to the recipe book. A tab on a recipe-book page, so the cook flips straight to it: an index. Buys faster lookups, pays extra work on every write.
- Fix one slow query. Cheap and reversible.
- Add a cache. Buys speed, pays staleness and a stampede risk.
- Add a read copy. A second copy of the recipe book for other cooks to read is a replica. It buys read capacity and pays: the second book is a few pages behind, a delay called lag.
- Failure. The hot profile expires and hundreds of reads hit the database at once. Fix: one request refills while the rest wait, and expiry times are spread.
- Decide. Fix the slow query first. Add a cache only if measured load needs it: short TTL, and a user's own edit bypasses it.
- Evolve. If reads outgrow the stove, the cache becomes part of capacity, and its failure must be planned for.
Quietly. The shelf hides a stove that is already near its limit; the day the shelf is cold or down, the whole load lands at once and the wait jumps.
- Which data may be old, and for how long?
- What is the cost of one wrong answer, in money or trust?
"Stove first: the load is inside its limit. A shelf only if reads become the limit, with a short TTL, and a user\'s own edit skips it. The price is a minute of old sauce."
Limit: every resource has a ceiling, so every gain is paid for somewhere. Store is its partner here: a cache keeps a copy near the stove, spending memory to save time. That is Store used as a Copy, where the Copy chapter picks up.
entry Do it now or do it later?
Question
Doing prep at the counter while the diner waits is inline. A second cook doing slow prep off to the side is a background worker.
Signup must send a welcome email. Send it inline, inside the signup request, or hand it to a background worker through a to-do list?
Weak answer
"Put it on the to-do list so signup is fast."
Strong answer
Inline is simplest, but the user waits on the mail server and signup fails if it is down. The to-do list (the Wait primitive, number five of ten) keeps signup fast and survives an outage, and pays with an email that may arrive late or twice. Use the list and make the send safe to repeat.
What is tested
Simplicity against waiting and failure handling, tied to what the user tolerates.
Hard mode
The message is a login code that expires in a minute. Does your answer change?
Escape: yes. Send it inline or on a fast lane with a resend button: a late code is worthless.
mid Batching and latency
Question
Signing the order book so the entry cannot be lost is a commit.
Database writes are too slow. A teammate wants many writes under one commit. What changes?
Weak answer
"Put them all under one commit, a few thousand rows at a time, that's strictly better, no downside."
Strong answer
Throughput rises: the expensive step, making the write durable, is paid once for many rows (rows: one order line each in the book). Each row waits for its group, and a crash mid-group can roll back (tear out) the whole group.
What is tested
Throughput against latency, and the durability price.
Hard mode
Each action must be acknowledged only after it is safe. Does batching still work?
Escape: yes, as group commit: collect actions in a short window, commit once, then acknowledge them all.
mid The cache hit rate is low
Question
You added a cache and database load barely dropped. What do you check?
Weak answer
"Make the cache bigger."
Strong answer
The hit rate first: if requests rarely repeat, no cache helps. Then the TTL (too short throws jars out before reuse) and whether the keys (the label on each jar) include something that changes every time. Size is the last guess.
What is tested
Diagnosis before a fix, and knowing when the ledger says the option is wrong.
Hard mode
Hit rate is high, but the few diners who wait longest, the tail latency, got worse. Why?
Escape: look at hits and misses separately. A few slow misses or a stampede hurt the slowest plates while the average looks fine.
senior Many requests miss together
Question
Each time one popular item expires, the database spikes. Explain and fix it.
Weak answer
"Set a longer TTL."
Strong answer
A stampede: many requests find the jar gone and all go to the stove. A longer TTL only delays it and adds staleness. Let one request refill while the others wait or get the old jar, and spread expiry times.
What is tested
A failure the optimization created, and its cause.
Hard mode
The cache itself goes down. What does the database see, and what do you do?
Escape: it sees every read at once. Turn some tickets away at the door so the kitchen can finish the rest: that is to shed load. Serving a plainer plate because the sauce is not ready is a degraded answer: serve one, or an old one. Refill the shelf slowly.
senior Pick the axis
Question
A profile page and a payment screen at the same company: do both get the same consistency choice?
Weak answer
"Yes, strongest consistency everywhere to be safe."
Strong answer
No. Strong checks cost latency and availability, so spend them where a wrong answer is expensive: a payment must be exact, even if slower; a profile can be a minute old. Different ledger per feature.
What is tested
Tying each choice to the cost of being wrong.
Hard mode
A user changes their name and reloads, and still sees the old one. Fix it and keep the cache.
Escape: after a user's own edit, write the new value into the cache, or let that user read from the source for a short while.
principal A cache tier or a bigger database?
Question
The stations that go dark when one breaker trips are that breaker's blast radius.
Read load keeps growing. One camp wants a company-wide cache tier with its own team; another wants a much bigger database. How do you decide?
Weak answer
"The cache is cheaper to run, so build the cache."
Strong answer
Price both with the full ledger. The bigger database buys a higher limit with few new failure modes, and pays money, a risky cutover (moving to the bigger stove while tickets keep arriving), and it is still one box. The cache tier buys cheaper reads and pays staleness, stampedes, a new thing to run, and a team to own it; every team shares it, so its blast radius is larger. If most reads repeat and the data tolerates age, the cache wins. If not, buy the database, set a measurable trigger to revisit, and keep it reversible.
What is tested
Full cost, running and failure included, and reversibility.
Hard mode
Budget covers only one, and a launch is in six weeks.
Escape: pick the smaller blast radius and easier undo, usually the bigger database, and write down the trigger that reopens the cache tier.
Run this on an idle machine and record the load average: the commands start with uptime and sysctl vm.swapusage, so keep that output next to your timings. The recording below was taken at load 5.17, not idle, so treat its timings as noisy.
Part one prices the commit: one commit per row, one for all rows, and one per row plus a full flush (fullfsync: the drive's notepad of recent writes is copied onto permanent paper). Part two shows stale reads, the stampede, and the fix: ten cooks need the same sauce, one makes it and all share. That is coalescing. Needs sqlite3 and Node.
Commands
uptime
sysctl vm.swapusage
cd "$(mktemp -d)"
cat > t.js <<'EOF'
const {execFileSync}=require('child_process');const fs=require('fs');
function run(label,sql){fs.rmSync('t.db',{force:true});fs.rmSync('t.db-journal',{force:true});
const t=process.hrtime.bigint();execFileSync('sqlite3',['t.db'],{input:sql});
return `${label}: ${(Number(process.hrtime.bigint()-t)/1e6).toFixed(0)} ms for 2000 rows`}
let one='PRAGMA synchronous=FULL;CREATE TABLE o(id INTEGER);';
for(let i=0;i<2000;i++)one+=`INSERT INTO o VALUES(${i});`;
let batch='PRAGMA synchronous=FULL;CREATE TABLE o(id INTEGER);BEGIN;';
for(let i=0;i<2000;i++)batch+=`INSERT INTO o VALUES(${i});`;batch+='COMMIT;';
console.log(run('commit per row',one));console.log(run('one commit for all rows',batch));
console.log(run('commit per row, fullfsync on','PRAGMA fullfsync=ON;'+one));
EOF
node t.js
cat > c.js <<'EOF'
const sleep=ms=>new Promise(r=>setTimeout(r,ms));
let truth='v1',dbCalls=0;const db=async()=>{dbCalls++;await sleep(20);return truth};
const cache=new Map(),TTL=200;
async function get(){const e=cache.get('k');if(e&&e.exp>Date.now())return e.v;const v=await db();cache.set('k',{v,exp:Date.now()+TTL});return v}
(async()=>{await get();truth='v2';
console.log('read right after update:',await get(),'(truth is',truth+')');
await sleep(100);console.log('read 100 ms later:',await get());
await sleep(250);console.log('read after TTL expired:',await get());
cache.clear();dbCalls=0;await Promise.all(Array.from({length:200},get));
console.log('200 simultaneous misses -> db calls:',dbCalls);
cache.clear();dbCalls=0;const inflight=new Map();
const co=()=>{if(!inflight.has('k'))inflight.set('k',get().finally(()=>inflight.delete('k')));return inflight.get('k')};
await Promise.all(Array.from({length:200},co));
console.log('same 200 with coalescing -> db calls:',dbCalls)})();
EOF
node c.js
Recorded output (run on this machine, 2026-11-21, SQLite 3.51.0, Node 22)
14:34 up 2 days, 6:16, 7 users, load averages: 5.17 5.78 8.25 vm.swapusage: total = 8192.00M used = 6515.81M free = 1676.19M (encrypted) commit per row: 763 ms for 2000 rows one commit for all rows: 9 ms for 2000 rows commit per row, fullfsync on: 2667 ms for 2000 rows read right after update: v1 (truth is v2) read 100 ms later: v1 read after TTL expired: v2 200 simultaneous misses -> db calls: 200 same 200 with coalescing -> db calls: 1
What you should see
One commit for all rows was roughly 85 to 170 times faster than one per row across runs at different loads: that is the throughput gain, and its price is that a row waits for its group. The fullfsync line was about 2 to 5 times slower than plain per-row commits, so plain commits underprice a true flush to stable storage on this Mac. The cache half (the last five lines) printed the same on every run: v1 right after the update is staleness bought by the TTL, and 200 simultaneous misses made 200 database calls without coalescing and 1 with it.
Predict, then set TTL to 50: v2 at 100 ms, because the shorter TTL threw the old jar out.
- Martin Kleppmann, Designing Data-Intensive Applications, O'Reilly. dataintensive.net.
- Daniel Abadi, "Consistency Tradeoffs in Modern Distributed Database System Design: CAP is Only Part of the Story", IEEE Computer volume 45, issue 2, February 2012, pages 37 to 42 (PACELC, confirmed in Crossref). PDF.
- Seth Gilbert and Nancy Lynch, "Brewer's Conjecture and the Feasibility of Consistent, Available, Partition-Tolerant Web Services", SIGACT News volume 33, issue 2, June 2002, pages 51 to 59 (confirmed in Crossref). PDF.
- John D. C. Little, "A Proof for the Queuing Formula: L = λW", Operations Research, 1961. Record.
- MIT OpenCourseWare 2.854, notes on the one-cook line: random arrivals and random service times at one cook:
M/M/1. Average time in the system is one divided by (service rate minus arrival rate). PDF. - SQLite, PRAGMA page:
synchronous(FULL is the default for a rollback journal) andfullfsync(off by default; only macOS supports it). - Mark Richards and Neal Ford, Fundamentals of Software Architecture: the first law is that everything in software architecture is a trade-off (page).