Philosophy & Ethics

A thousand transfers, a 2% fault rate, and two copies of every balance. If the app writes both copies itself, 35 transfers end up wrong. A log keeps the copies equal but still applies 35 transfers twice. A request ID carried end to end leaves 0 wrong, for about 21 ms more lag.

Pick a design and raise the fault rate. Then we build each part: one log for every copy, replay, the unbundled database, end-to-end checks and audits. Then we turn to the people inside the data: biased predictions, feedback loops and privacy.

You need a little Python and what a database and a retry are. We build the rest from zero.

Move a thousand transfers

2%

Illustrative and seeded: 1,000 transfers. Each transfer meets three faults with the chance you set: a lost request, a lost reply and an app crash halfway. A client always retries once. Lag is the time until both copies show a transfer. Dual writes take two writes of 2 to 5 ms. A log takes one append of 2 to 5 ms, then a poll every 50 ms.

Chapter 0

Five Copies of One Fact

Write one price to two stores at once and watch the copies disagree

A shop sells a lamp for 40. The price lives in the orders database. It also lives in the search index, a cache, the warehouse and the features of a recommendation model. One fact, five copies. Every copy is derived data: data the shop could rebuild from the system of record, the one store that holds the truth.

The easy way to keep copies in step is a dual write: the app writes the database, then writes the index. Two people change the price at almost the same moment. Each write takes a different time on the network. The database may keep one price and the index the other.

Race two price changes

Client A sets 40, client B sets 45. Each writes the database, then the index; each write takes 0 to 40 ms. The lanes show one trial. Move the gap, then switch to one log.

0 ms

Illustrative and seeded: 1,000 trials per setting. Each store keeps the write that arrives last. Through a log, both stores apply the two changes in the one order the log gave them.

With no gap, the copies disagree in 260 of 1,000 trials. Nothing crashed. The fix is to stop writing twice. Write each change once, to a log, and let every copy read the log in the same order. This lesson builds on that idea. Then it asks what the data does to the people it describes.

This lesson follows Designing Data-Intensive Applications, 2nd edition, by Martin Kleppmann and Chris Riccomini (O'Reilly, 2026). Its Chapter 13 is "A Philosophy of Streaming Systems" and its Chapter 14 is "Doing the Right Thing". In the first edition these ideas closed the book as Chapter 12, "The Future of Data Systems". We explain them in our own words, with our own examples and simulations.

Failure. Symptom: search shows the lamp at 45 and the product page says 40, for days. Measure: compare a sample of prices between the database and the index every night. Cause: dual writes that raced. Fix: write each change once to a log and derive the index from it (Chapter 1).

  1. Log: one ordered log feeds every copy, and lag says how far behind each is.
  2. Replay: build a new view by replaying history, then switch.
  3. Unbundle: indexes and caches as separate services, and where the work goes.
  4. End to end: a request ID from the client stops duplicate payments.
  5. Integrity: late can wait, wrong cannot; audit from the log.
  6. Bias: a model that never sees the group still treats it differently.
  7. Loop: where you look decides what you find.
  8. Privacy: every record kept is a record a breach can expose.
  9. The showcase: run a fraud-review desk for a year.
  10. The field guide: numbers, checklist, code and links.
Two price changes reach the database and the index. Nothing crashes. Why can the two stores still end with different prices?

Chapter 1

One Log, Every View

Stop a consumer, watch it fall behind, and watch it catch up without losing a change

Put every change in one log: an append-only list where each entry gets the next number, its offset. The app appends once. Each derived store has a consumer that reads the log in order and applies each entry. Two consumers that read the same entries in the same order end in the same state.

A consumer remembers the offset it has reached. If it stops, the log keeps growing and the consumer falls behind. When it restarts, it reads from its offset and catches up. No change is lost, because the log is the record and the consumer's store is only a view of it.

Run three consumers

The purple strip is the log; the head moves right as changes arrive. Each row is one consumer and its offset. Switch one off for a while, then on again.

Illustrative: changes arrive at 1,000 a second; a running consumer can apply 5,000 a second, so a stopped one catches up. Time runs 100 times faster than real time.

How far behind is a consumer, in time? Call the newest offset in the log, the head, h. Call the consumer's offset o, and the rate at which changes arrive r. The lag in seconds is L.

Say it aloud

L equals h minus o, divided by r.

L
L the lag: how many seconds of changes the consumer has not applied yet.
h
h the head: the offset of the newest entry in the log.
o
o the consumer's offset: the last entry it has applied.
r
r the arrival rate: new entries per second.
In plain words

Subtract the consumer's offset o from the head h to count the entries it still owes. Divide by the arrival rate r to turn that count into seconds. That is how stale its view is.

With numbers

With made-up numbers: h = 120,000, o = 90,000, r = 1,000 a second. L = 30,000 / 1,000 = 30 s. The search index shows the world as it was half a minute ago.

A distributed transaction that writes every copy or none gives readers the newest value at once. But every write then waits for every store, and one slow store stalls them all. The log gives up instant freshness and keeps the order. Transactions and consensus cover the other side.

A log has limits. One order needs one leader, and one leader has a top speed. A partitioned log keeps order within each partition, not across them. Stream Processing covers partitions, offsets and lag in depth.

Failure. Symptom: new products take an hour to appear in search, and nobody knows why. Measure: lag per consumer, in seconds, on a dashboard with an alert. Cause: the search consumer crashed and nobody restarted it. Fix: alert on lag, restart from the stored offset, and let it catch up.

The head is at offset 2,400,000, the cache consumer is at 2,340,000, and changes arrive at 2,000 a second. How stale is the cache?

Chapter 2

Change a View by Replaying

Build a new view from the whole history while the old one serves, then switch

The product team wants search to rank by sales, not by name. The old index cannot answer that. With a log, you do not migrate the old index in place. You start a new consumer at offset 0 with the new code. It replays the whole history and builds the new index next to the old one.

While it replays, new changes keep arriving, so the new view chases a moving head. When it catches up, move readers over, a few at a time. Keep the old view until you trust the new one. If the new code has a bug, point readers back. Nothing in the record changed, so nothing needs undoing.

Replay to a new view

The purple line is the head of the log; the teal line is the new view. They meet when the replay catches up. Slow the replay to the arrival rate and they never meet.

50 M
20,000/s

Illustrative: changes arrive at 2,000 a second. History is the entries already in the log when the replay starts.

How long until the switch? Call the entries already in the log the backlog, B. Call the replay speed rre and the arrival rate rin. The catch-up time is T.

Say it aloud

T equals B, divided by r-re minus r-in.

T
T the catch-up time, in seconds, until the new view reaches the head.
B
B the backlog: entries in the log when the replay starts.
rre
r-re the replay speed: entries per second the new consumer applies.
rin
r-in the arrival rate: new entries per second.
In plain words

Each second the new view gains r-re entries, but r-in new ones arrive. So it closes the gap by r-re minus r-in a second. Divide the starting gap B by that.

With numbers

With made-up numbers: B = 50 million, r-re = 20,000, r-in = 2,000. T = 50,000,000 / 18,000 = 2,778 s, about 46 minutes. At r-re = 4,000, T is about 6.9 hours.

Two designs use this idea. The lambda architecture (Nathan Marz, 2011) runs a batch job over all history and a stream job for recent data, then merges them. You write the logic twice and must keep both in step. The kappa architecture (Jay Kreps, 2014) keeps only the stream job and replays the log when the logic changes. Batch and stream are then one dataflow at two speeds. Batch Processing builds the batch half.

Failure. Symptom: the team cannot rebuild the index because the log keeps only seven days. Measure: how far back the log reaches against the history a new view needs. Cause: retention set for consumers, not for replay. Fix: keep the full log in cheap storage, or a snapshot plus every entry since.

A replay applies 3,000 entries a second, new entries arrive at 3,000 a second, and the backlog is 10 million. When does the new view catch up?

Chapter 3

The Database, Unbundled

Move work between write time and read time, and find where each design wins

A database already keeps derived data inside itself. An index is a copy of a column in sorted order. A materialized view is a stored query result. A replica is a copy of everything. The database updates them for you, inside one transaction.

Unbundling runs these parts as separate systems: a store for records, a search engine, a cache, a warehouse. A log ties them together, as in Chapter 1. Kleppmann called this "turning the database inside out" in a 2014 talk. You choose the best tool for each job. The price: you own the glue a single database gave you.

Every derived view moves work. The write path is the work done when data arrives. The read path is the work done when someone asks. An index adds work on every write and saves it on every query. A cache of whole answers moves even more work to the write side.

Move the boundary

A million documents, a million writes a day. Each bar is one design's daily work: teal for work on write, blue for work on read. Raise the queries.

10 M

Illustrative counts of records touched. A scan reads all 106 documents per query. An index costs 20 touches per write and 100 per query. Kept answers add 200 touches per write; 90% of queries hit and cost 1, the rest use the index.

Compare the designs by daily work. Call the writes a day w and the queries a day q. Call the cost of one write cw and of one query cq. The daily work is C.

Say it aloud

C equals w times c-w, plus q times c-q.

C
C the work a day, in records touched.
w
w writes a day.
cw
c-w records touched per write: the write path.
q
q queries a day.
cq
c-q records touched per query: the read path.
In plain words

Charge each write its write-path cost c-w and each query its read-path cost c-q. Add the two totals. The design with the smaller C does less work.

With numbers

From the device: w = 1 million, q = 10 million. Index: 1,000,000 × 20 + 10,000,000 × 100 = 1.02 billion. Kept answers: 1,000,000 × 220 + 10,000,000 × 10.9 = 329 million. Below about 2.2 million queries a day, the plain index wins.

The read path can reach past the server. A browser or phone that subscribes to changes keeps its own derived view up to date. The log then runs all the way to the screen.

Failure. Symptom: writes slow down after the team caches answers for every saved search. Measure: records touched per write, before and after. Cause: answers kept for queries nobody runs. Fix: keep answers only for queries read far more often than their inputs change.

With a million writes a day, at what query rate does keeping answers start to beat a plain index in this device?

Chapter 4

Check the Whole Path

Retry 10,000 payments and see which duplicates each layer can stop

A customer taps Pay. The request reaches the server and the charge goes through. Then the network loses the reply. The phone shows an error, and the customer taps again.

The second request is a new message on a new connection. TCP removes duplicate packets within one connection. A transaction makes one request atomic. Neither knows the two requests are the same payment.

This is the end-to-end argument of Saltzer, Reed and Clark (1984). Checks in the layers between cannot replace a check that only the ends can do correctly. Lower layers can make the check cheaper. They cannot make it unnecessary.

Retry the payments

Two faults make duplicates. The processor crashes before it records its offset and gets the message again. Or a reply is lost and the client sends again. Pick where the check sits.

1%

Illustrative and seeded: 10,000 payments; each fault strikes a payment with the chance you set. "Exactly once inside" means the stream processor applies each log message once, as in Stream Processing.

The fix starts at the client. It makes a request ID, a random unique number, when the customer first taps Pay. Every retry carries the same ID. The ledger has a unique constraint on the ID, so the ledger refuses a second row with the same ID.

How many duplicates slip past the inside check? Call the payments N and the chance that a reply is lost after the charge f. The expected client duplicates are D.

Say it aloud

D equals N times f.

D
D the expected number of payments charged twice because the client retried.
N
N the number of payments.
f
f the chance a reply is lost after the charge went through.
In plain words

Each of the N payments has chance f of a lost reply, and each lost reply makes the client pay again. Multiply them. With a request ID, D drops to zero.

With numbers

With made-up numbers: N = 10,000, f = 1%. D = 100 expected. The seeded run got 97, plus 112 redeliveries that the inside check removes.

The same idea enforces a uniqueness constraint without a global lock. Send every claim for a username to the log partition chosen by a hash of the name. One consumer reads that partition in order, so the first claim wins and the consumer refuses the second. Consistency and Consensus shows why some constraints still need agreement first.

Failure. Symptom: on a bad-network day, about 1 in 100 customers pays twice. Measure: payments per request ID, and charges with the same amount and card within a minute. Cause: the client retries with no ID, and the server sees two payments. Fix: make the ID at the client and enforce it at the ledger. Idempotency shows the server side.

The stream processor is exactly once, but customers are still charged twice. Where must the fix go?

Chapter 5

Late Is Fixable, Wrong Is Not

Lose a few events in a pipeline whose lag looks fine, and catch them with an audit

"Consistency" mixes two different promises. Timeliness means readers see an up-to-date state. Integrity means the data loses nothing, applies nothing twice, and never contradicts itself. Break timeliness and the view is stale for a while; wait, and it is right. Break integrity and the view stays wrong until someone notices.

A log-based pipeline gives up some timeliness on purpose: a consumer is a little behind. It keeps integrity with ordered logs, request IDs and consumers that apply each entry once. Some rules can be loose. An airline that sells one seat too many apologises and rebooks. The money in an account cannot be loose.

Audit the balances

Each dot is an account. A bug drops some events, and red dots are now wrong. The audit recomputes the teal-ringed accounts from the log. Press the button to run another day.

1 in 10,000
1,000

Illustrative and seeded: 20,000 accounts, 10 events each, 200,000 events a day. Each dot is 20 accounts at phone width and 10 on wider screens. A dot turns red if any of its accounts is wrong.

The lag monitor stays green, because a lost event makes nothing late. Only a check that compares the view with the log can see it. That is an audit: recompute some accounts from the log and compare. How likely is it to find a problem? Call the share of wrong accounts f, the accounts checked k, and the chance of finding at least one wrong account P.

Say it aloud

P equals one minus, one minus f, to the power k.

P
P the chance the audit finds at least one wrong account.
f
f the share of accounts that are wrong.
k
to the power k k is the number of accounts checked at random; the power multiplies one chance per account.
In plain words

One checked account is fine with chance 1 minus f. All k are fine with that chance multiplied k times. Subtract from 1 to get the chance that at least one is wrong.

With numbers

With made-up numbers: f = 0.1%, k = 1,000. P = 1 − 0.9991000 = 63%. With k = 5,000, P = 99.3%. With k = 100, only 9.5%.

Auditing is cheap when the record is a log. The log holds every input, so you can recompute any view, compare it, and rebuild it if it is wrong. The first edition of the book called this attitude "trust, but verify".

Failure. Symptom: a customer reports a missing deposit; every dashboard is green. Measure: the share of audited accounts whose balance differs from a recompute. Cause: a consumer skipped events with a rare field, and no check compared results. Fix: run a daily audit from the log, and rebuild the view when it fails.

A consumer silently drops 1 event in 10,000. Its lag is 0.3 s. Which check catches the problem?

Chapter 6

Predictions About People

Remove the group from a lending model and see the gap survive through a postcode

Much of this data describes people. The pipeline that ranks search results can also rank loan applicants or defendants. A wrong price annoys someone. A wrong denial changes a life.

A model learns from history, and history records past decisions too. Suppose a lender's records show more defaults in one part of town because people there once got worse terms. The model never sees the group. It sees the postcode, which tracks the group. A feature that stands in for something you removed is a proxy.

Remove the group

10,000 applicants, two groups with the same spread of true ability. The model approves the top half.

Illustrative and seeded. 80% of group B and 20% of group A live in the south side. We made up the historical penalty on that postcode. Shopping data agrees with the postcode 80% of the time. Group is never a feature.

How do you measure the gap? Call the share of group A approved sA and of group B sB. Their ratio is ρ. US employment guidelines treat a ratio under four-fifths as evidence of adverse impact (29 CFR 1607.4(D)). It is a rule of thumb.

Say it aloud

Rho equals s-B divided by s-A.

ρ
rho the ratio of approval rates; 1 means equal, under 0.8 flags adverse impact.
sB
s-B the share of group B's applicants approved.
sA
s-A the share of group A's applicants approved; put the group with the higher rate here.
In plain words

Divide group B's approval rate s-B by group A's s-A. If rho is below 0.8, look hard at why.

With numbers

From the device, income plus postcode: s-A = 58.0%, s-B = 42.0%. Rho = 0.420 / 0.580 = 0.72, under the line. With income only, rho = 1.00.

Equal accuracy does not mean equal errors. ProPublica's 2016 analysis of the COMPAS risk score looked at defendants who did not reoffend. COMPAS labelled 44.9% of the Black defendants among them higher risk, against 23.5% of the white defendants.

Chouldechova (2017) showed a limit. Suppose two groups reoffend at different rates, and a "high risk" label comes true equally often in both. Then the groups cannot also have equal false positive and false negative rates. Choosing which error to equalise is a value judgement.

Someone must answer for each decision. In 2018 Reuters reported that Amazon dropped an experimental hiring model, trained on ten years of résumés, that penalised the word "women's". Amazon said recruiters never used it to rate candidates. The GDPR gives a right, with exceptions, not to face a decision made solely by automated processing that has legal or similar effects (Article 22).

Failure. Symptom: approvals in one neighbourhood fall after a "group-blind" model ships. Measure: approval and missed-repayer rates per group, every release. Cause: a proxy carries the old bias. Fix: test what each feature stands in for; block a release with a ratio under 0.8 until explained.

A model never sees the applicant's group, yet approves 42% of group B and 58% of group A. What is the most likely cause?

Chapter 7

The Loop Feeds Itself

Send reviews where the model says fraud is, and watch its belief move away from the truth

A lender's fraud team reviews 1,000 loan applications a week. North and south have the same true fraud rate: 2%. Last year's records hold 200 fraud cases, 60% from the south, because the old team looked there more. A model trained on them believes the south has 60% of the fraud.

The team sends most reviews where the model points. Reviews find fraud where they look, so the team finds more in the south. The finds go into the log, and the model learns from them. This is a feedback loop: the system's output decides its next input. The model is derived data whose own decisions shape its record.

Follow the model

The teal line is the model's belief that fraud is in the south; the dashed line is the truth, 50%. The warm bars are reviews sent south each week. Pick a policy and press Play.

60%
0%

Illustrative and seeded: 1,000 reviews a week and a true fraud rate of 2% in both places. Last year's 200 cases are the starting history. Exploration splits a share of reviews evenly before the policy runs.

Where does the belief settle? Call last year's cases F0, with a share s0 from the south. Each week the team finds n cases, and sends a share a of its reviews south. After t weeks the belief is bt.

Say it aloud

b-t equals F-zero times s-zero, plus t times n times a, all divided by F-zero plus t times n.

bt
b-t the model's belief after t weeks: the south's share of all fraud found.
F0
F-zero the fraud cases in last year's records: 200.
s0
s-zero the south's share of those cases: 0.6.
t
t the number of weeks since the model took over.
n
n cases found per week: 1,000 reviews times 2% = 20.
a
a the share of reviews sent south; with equal rates, also the share of finds.
In plain words

Start with last year's F-zero cases, s-zero of them southern. Each week add n finds, a share a of them southern. Divide southern finds by all finds. As t grows, b-t moves to a: the share you chose to look at.

With numbers

With the device's numbers: F-zero = 200, s-zero = 0.6, n = 20, a = 0.8. After 10 weeks: (120 + 160) / 400 = 0.70. After 52 weeks: 0.77. The seeded run reaches 0.74 at week 20.

The data now measures the team's habits, not the fraud. Ensign and colleagues (2018) showed this runaway effect in predictive policing. A related trap is selective labels (Lakkaraju and colleagues, 2017): a lender sees repayment only from people it approved. The fix is to learn rates, fraud per review, so where you looked cancels out.

Failure. Symptom: each retrain makes the model surer the south is riskier, and every honest southern applicant waits longer. Measure: finds per review in each place, next to finds per place. Cause: the model counts finds, and finds follow reviews. Fix: train on rates, keep a share of reviews random, and audit the two beliefs against each other.

Both postcodes have the same fraud rate. The team sends 80% of reviews south for a year. What share of the fraud found comes from the south, in the long run?

Chapter 8

Data Is a Liability

Choose how long to keep location data and see what one breach exposes

A ride app records each user's location every hour. The data helps today's trip. Kept for years, it is a diary of where a person sleeps, works and prays. Data that tracks people for one purpose is surveillance data once it can serve any other. Every record you keep is a record a breach, a subpoena or a future owner can read.

Removing names does not make location data anonymous. De Montjoye and colleagues (2013) found that four hourly location points were enough to single out 95% of 1.5 million phone users. Sweeney (2000) estimated that postcode, sex and date of birth were unique for up to 87% of the US population.

Shrink the blast radius

The purple area is the location records stored on each day of three years. The red line is a breach on the last day. Shorten the retention.

ever

Illustrative: 100,000 users, 24 location points per user per day, a service running 1,095 days. The privacy facts come from the cited studies; the app is made up for this page.

Call the users u and the points per user per day k. Call the days you keep raw points R and the days the service has run A. A breach exposes E records.

Say it aloud

E equals u times k times the minimum of R and A.

E
E the records a breach exposes.
u
u the number of users.
k
k location points stored per user per day.
min
the minimum of the smaller of the two numbers.
R
R the retention: days the app keeps raw points before it deletes them.
A
A the age of the service in days.
In plain words

Each user adds k points a day. You hold the last R days of them, or all A days if the service is younger than R. Multiply by the u users.

With numbers

With made-up numbers: u = 100,000, k = 24, A = 1,095. Kept for ever, E = 2.63 billion points. Kept 30 days, E = 72 million: 36.5 times fewer.

The GDPR writes this down. Personal data must be "limited to what is necessary" (Article 5(1)(c)). It may stay identifiable "for no longer than is necessary" (Article 5(1)(e)). Consent must be "freely given, specific, informed and unambiguous" (Article 4(11)). A company must report a breach that puts people at risk to the regulator within 72 hours where feasible (Article 33).

An append-only log seems to clash with erasure. Data, Law and People covers the two fixes. Send deletions through the log, or encrypt each person's fields with their own key and delete the key.

Failure. Symptom: a breach leaks three years of location history for every user. Measure: records stored per user, and the oldest record, by table. Cause: nobody set a retention period, because storage is cheap. Fix: delete raw points after the shortest period the product needs, and keep coarse counts if analysts need trends.

An app keeps 24 location points a day for 100,000 users. It has run for three years. Retention drops from "for ever" to 30 days. What happens to a breach's size?

Chapter 9

Run the Review Desk for a Year

Set the policy, the history, exploration, retention and an audit, and count who pays for each choice

Back to the fraud desk, now for 52 weeks and with every knob. The model is a view derived from the review log. The audit compares two views of that log, finds per place and finds per review, as in Chapter 5. Retention decides how many review records a breach can expose.

Run the desk

Teal solid: the belief the policy uses. Teal dashed: fraud per review. Grey dashed: the truth. Warm bars: reviews sent south. Switch the audit on with the riskiest-first policy.

60%
0%
52 weeks

Illustrative and seeded, the engine of Chapter 7 run for 52 weeks. The audit switches to rates when the two beliefs differ by more than 0.1. Records kept counts weekly review records; last year's summary is always kept.

At the defaults the belief climbs from 0.60 to 0.76. The desk reviews 40,780 honest southern applicants, against 26,657 under the rate policy: about 14,000 people held up for nothing. Switch the audit on: it fires in week 2, and the year ends at 0.52.

Set last year's share to 50%, with no bias at all. "80% to the riskier" still picks a side by chance and locks in: the belief ends at 0.25, now against the north. Exploration of 20% only slows the climb, to 0.71. Shorter retention shrinks the records a breach exposes, from 52,000 to 4,000, but does not fix the loop.

Failure. Symptom: a review policy that looks data-driven doubles the burden on one area in a year. Measure: finds per review per area, every week, next to the model's belief. Cause: the model learns from the reviews it chose. Fix: train on rates, run the audit as a release gate, and keep records only as long as the audit needs them.

Chapter 10

The Field Guide

Keep the numbers, the rules and the code for the next system you build about people

Write each change once, to a log, and derive every other copy from it. Replay the log to build new views. Unbundle the database when separate tools serve you better, and own the glue. Check correctness at the ends: request IDs from the client, audits recomputed from the log. Prefer late to wrong.

Then remember who the records describe. Measure outcomes per group, because proxies carry history. Watch for loops where your decisions make your data. Keep the least data for the shortest time.

Terms and numbers

IdeaRuleThis lesson's number
Dual writestwo writes raceno gap: 260 of 1,000 trials disagree; log: 0
LagL = (h − o) / r30,000 entries at 1,000/s: 30 s
ReplayT = B / (rre − rin)50 M at 20,000/s against 2,000/s: 46 min
Write or read pathC = w · cw + q · cqkept answers beat the index above 2.2 M queries a day
End to endD = N · f10,000 payments at 1%: 97 duplicates; with a request ID: 0
AuditP = 1 − (1 − f)k0.1% wrong, 1,000 checked: 63%
Adverse impactρ = sB / sA < 0.8postcode model: 0.72; income only: 1.00
Feedback loopbt → a80% of reviews south: belief 0.60 → 0.76 in a year
RetentionE = u · k · min(R, A)for ever: 2.63 billion points; 30 days: 72 million

Checklist

  1. Name the system of record. Derive every other copy from its log, never by a second write from the app.
  2. Alert on consumer lag in seconds; keep enough log, or snapshots, to rebuild any view.
  3. Make the request ID at the client, carry it through every hop, and enforce it where the effect lands.
  4. Run an audit that recomputes a sample from the log; size the sample for the error rate you fear.
  5. For any model that decides about people: report outcomes and errors per group at every release.
  6. Ask whether your decisions produce your training data. If so, learn from rates, explore, and audit.
  7. Set a retention period for every table of personal data, and let people see and contest automated decisions.

The core as code

pythonclass Ledger:                            # the end of the path enforces the ID
    def __init__(self):
        self.rows = {}
    def apply(self, request_id, account, amount):
        if request_id in self.rows:            # a retry: drop it
            return False
        self.rows[request_id] = (account, amount)
        return True

def lag_seconds(head, offset, rate):     return (head - offset) / rate
def catch_up(backlog, replay, arrive):   return backlog / (replay - arrive) if replay > arrive else float('inf')
def p_detect(f, k):                      return 1 - (1 - f) ** k
def belief_after(F0, s0, n, a, t):       return (F0 * s0 + t * n * a) / (F0 + t * n)
def rate_belief(found, reviewed):        # fraud per review, so where you looked cancels
    rs, rn = found[0] / reviewed[0], found[1] / reviewed[1]
    return rs / (rs + rn)

L = Ledger()
print(L.apply('r-7f3a', 'acct-42', 40), L.apply('r-7f3a', 'acct-42', 40))   # True False
print(lag_seconds(120_000, 90_000, 1_000), round(catch_up(50e6, 20_000, 2_000)))   # 30.0 2778
print(round(p_detect(0.001, 1000), 3), belief_after(200, 0.6, 20, 0.8, 10))   # 0.632 0.7
print(rate_belief([160, 40], [8000, 2000]))   # 0.5: 80% of finds, but the same rate

Keep going

The takeaway. Derive every copy from one log, and check correctness where the effect lands. Then treat the model as derived data too: measure who it fails, notice when it feeds itself, and keep less.

Now press Present or Teach and explain four things from memory. Why do dual writes disagree with no crash? Why does exactly-once processing not stop a double charge? Why does a model that never sees the group still treat it differently? Why does a review policy's belief drift to where it looks? Then go back to the hero and find the only design that stays at zero wrong as you raise the faults.

Philosophy & Ethics · following Designing Data-Intensive Applications, 2nd edition, Chapters 13 and 14
Previous: Stream Processing · Back to the start: Trade-offs · Back to Gleams