ealeng

Episode 25 of 55 · Messaging

Queues and the outbox: a crash between two writes lost 143 events, and the outbox lost none

An order service that saved each order and then published its event to Kafka lost 143 events when it crashed on purpose between the two steps 107 times: orders saved, cards never charged. With the outbox pattern, 108 crashes lost none. How a queue cut the request's median from 55 ms to 3 ms and moved the card charge later, why a slow card service built a backlog of 1,226 that arithmetic predicted, what the outbox costs instead (events sent twice when its relay dies), and why consumers must be idempotent.

Lab 12 · Queues and Event Streams (Kafka)10 min read
Video transcript8:52

0:00Cold open

0:01

My order service saves each order to the database, then sends an event, a short message saying “this order was placed”, to Kafka, so other services can charge the card. Then I made it crash right between those two steps, a hundred and seven times.

0:18

A hundred and forty-three orders were saved with no event. No consumer ever heard of those orders, so nothing would ever charge those cards.

0:29

Then I changed one thing, called the outbox. A hundred and eight crashes. Zero events lost, out of two thousand four hundred and twenty-eight orders.

0:40

So why did one lose events, and what did the other cost instead?

0:46Intro

0:48

Hands-on system design, part twenty-five.

0:51

Today: taking work out of the request with a queue, and not losing it on the way.

0:58Meet Lucía

0:59

I’m Lucía, a platform engineer. Each order needs three things: an email, a stats update, and a card charge. Fifty milliseconds of work in all, simulated here.

1:10

Inline: do all three in the request, then answer. The caller waits for everything.

1:16

Dual write: save the order, send an event to Kafka, and answer. Kafka is a queue, a log of events. Consumers, separate processes, read each event later and do the work.

1:29

And the outbox: save the order and its event as one database transaction, a group of writes the database keeps all-or-nothing. A small relay sends the event to Kafka afterwards.

1:42

Think of a restaurant. Inline, each customer waits at the counter while their meal cooks. With a queue, the waiter pins a ticket on the rail, and cooks take tickets off it. Dual write: the waiter writes the order in the book, then walks to the rail; faint on the way, and the kitchen never hears. And with the outbox, the page in the book is enough: a runner copies it to the rail.

2:0601 · What you need

2:08

To run it yourself: Docker for three Kafka brokers, Postgres, the order service and the consumers. The quick tests run in a couple of seconds, without Docker.

2:19

No cloud, and nothing to pay for.

2:2402 · What the caller waits for

2:25

Fifty orders a second, for forty seconds, two rounds. Inline, a request took about fifty-five milliseconds: the work, plus a little.

2:36

Dual write: eleven. The fifty milliseconds left the request. Most likely, what’s left is waiting for Kafka to confirm it stored the event, in three copies.

2:47

The outbox: three milliseconds. Just one database transaction.

2:53

But the work didn’t go away. It moved. Inline, the card was charged fifty-two milliseconds after the order. With the outbox, seventy-three: later, not sooner.

3:06

And the slowest charge in every hundred, with or without the relay, came just over two hundred milliseconds after the order. Typically, dual write’s card was charged sixty-three milliseconds after the order, the outbox’s seventy-three. The relay looks for new rows every twenty milliseconds, so an event most likely waits about ten.

3:2803 · A slow card

3:30

Now the card service slows down, so each order’s work takes three hundred milliseconds instead of fifty. Six consumers can now charge at most six divided by point three: twenty orders a second. Fifty arrive.

3:45

Inline, the caller waits for the slow card: over three hundred milliseconds. With the outbox, the request didn’t notice: under ten milliseconds at the slowest one in a hundred.

3:58

But the charges fell behind. Typically thirty-one seconds after the order. The slowest one in a hundred: seventy-five seconds.

4:08

When the load stopped, twelve hundred and twenty-six orders were waiting: a backlog. The arithmetic predicted it: fifty arriving, twenty done, thirty more every second, for forty seconds: twelve hundred.

4:22

Draining them took seventy-nine seconds, not the sixty that twelve hundred divided by twenty predicts. The log is split into six slices called partitions, one per consumer. While orders poured in, they finished about twenty a second, the most six can do. After the load stopped, only about fifteen a second. Most likely, some slices emptied early, and their consumers sat idle while the busiest finished.

4:4804 · The gap

4:50

Now the risky part. Here’s how the service places an order.

4:55

Dual write: first the database transaction saves the order.

5:00

Then, as a separate step, it sends the event. To test the gap between them, I made the service exit right after the save, the commit, with a four percent chance per order.

5:13

The outbox writes the event as a row in a table, inside the same transaction as the order. Both are saved, or neither is.

5:2305 · Crash in the gap

5:25

A hundred and seven crashes in the gap, with dual write. How many events were lost: a hundred and seven?

5:33

A hundred and forty-three. Four point four percent of the orders saved.

5:39

A hundred and seven were the orders that crashed it. The other thirty-six were most likely other orders the same process was still sending: saved, not yet sent, when it exited. None of their callers had heard “created” either. A crash takes everything in flight, not just one request.

5:58

The outbox: a hundred and eight crashes, and zero lost. One more thing, in both ways: a hundred and fourteen to a hundred and forty-five orders were saved, but the caller never heard “created”: the connection just dropped. A caller that just retries orders twice, unless each order carries an idempotency key, a unique order number the caller picks, from part ten.

6:2306 · Random kills

6:25

That was the worst moment, on purpose. What about random crashes? A hundred orders a second, and thirty attempts to kill the service at random moments.

6:35

Dual write, waiting for Kafka’s confirmation before answering: sixteen events lost, about one order in three hundred and seventy. Not one of them had been told “created”: the connection dropped before Kafka confirmed.

6:51

Dual write without waiting, the common shortcut: seventeen lost, and every one after the caller got “created”. Most likely the events were still waiting in the service’s memory when it died.

7:04

The outbox, with the relay killed thirty times too: zero lost. But twelve extra copies were sent. That’s the cost I promised: not in the gap test, but when the relay itself dies.

7:1807 · The relay

7:20

Why extra copies? Here’s the relay. In the restaurant, it’s a runner copying new pages from the order book onto the rail, and crossing each one out only after it’s pinned. It takes up to five hundred of the oldest outbox rows.

7:36

It sends them to Kafka, and waits until Kafka has confirmed every one.

7:42

Only then does it delete the rows.

7:46

Killed after sending but before deleting, the rows are still there, and get sent again. The outbox turns “maybe lost” into “maybe twice”. And twice is fixable, if the consumers can tell they’ve seen an event before. That’s next time.

8:03Back to Lucía

8:04

So, three lessons.

8:07

Queue what the caller doesn’t need to wait for. Fifty-five milliseconds became three.

8:14

A queue moves work, it doesn’t remove it. When the work gets slower, the backlog grows, and simple arithmetic tells you how big.

8:23

And save the event in the same transaction as the order. Dual write loses events in the gap; the outbox sends some twice instead.

8:33

Next time: the duplicates crashes leave behind, and what a rebalance costs.

8:39

For today: write it down together.Lucía: Write it down together.

8:43Summary

8:45

Queue what can wait, expect the backlog, and save the event with the order.

Key takeaways

  • ✓A queue takes work out of the request: the median request fell from 55 ms inline to 3.1 ms with the outbox, because the 50 ms of email, stats and card-charge work now runs later, in consumers that read the events.
  • ✓A queue moves work, it doesn't remove it: the card was charged 73 ms after the order at the median with the outbox, against 52 ms inline. When the card service slowed to 300 ms per order, 50 orders a second arrived but only about 20 a second finished, and the backlog reached 1,226 against a predicted 1,200.
  • ✓Dual write, which saves the order and then publishes its event as a second step, lost 143 of 3,221 committed orders when the service exited between the two steps 107 times: 4.4%, with a 95% range of 3.8% to 5.2%. The 107 were the crashing orders; the other 36 were orders the same process had committed but not yet published.
  • ✓The outbox writes the event as a row in the same database transaction as the order, and lost 0 of 2,428 committed orders across 108 crashes in the same gap.
  • ✓Waiting for Kafka's acknowledgement did not close the gap: in 30 random kills at 100 orders a second, dual write that waited still lost 16 of 5,909 orders, and dual write that didn't wait lost 17 of 5,900, all 17 after their callers had been told "created" (HTTP 201).
  • ✓The outbox's price is duplicates, not loss: killing the relay 30 times sent 12 events twice, so consumers must skip an event they have already processed, which the lab's idempotency table did for all 16,955 duplicate deliveries in the consumer-kill test.

Two thousand four hundred and twenty-eight orders went through the outbox, and 108 crashes lost none of them. The same design with a dual write (saving the order and then publishing its event as a second step) lost 143 events in 107 crashes: orders were saved, no event was published, and no consumer ever charged those cards. This chapter takes the two designs apart, and then asks what the outbox costs instead.

The examples come from Lab 12 (Queues and Event Streams (Kafka)) of the system design labs, scripts 01_inline_vs_queued.py (what a queue does to the caller's wait, and to a slow card service) and 02_crashes.py (crashes between the two writes, and random kills). The setup is the earlier chapters' laptop, an Apple M4 Max with Docker Desktop and 16 virtual CPUs. Kafka 4.1.1 ran on three brokers (the servers that store the topic, the named stream of events), with Postgres, the order service and six consumers (the processes that do the work), all in Docker. Each configuration is one recorded run, and the README puts script 01 at about 7 minutes and script 02 at about 20. The machine was busy during the runs (load averages of about 7 to 12), so read the shapes more than the last digit.

Queues: take the work out of the request

Each order needs three things: an email, a stats update and a card charge, 50 ms of simulated work in all. There are three ways to handle it.

  • Inline: do all three in the request, then answer. The caller waits for everything.
  • Dual write: save the order to the database, publish an event to Kafka, then answer. Consumers read each event later and do the work.
  • Outbox: save the order and an outbox row (a record of the event, in a table called outbox) in one database transaction, a group of writes the database keeps all-or-nothing. A relay, a small separate process, publishes the outbox rows to Kafka afterwards and then deletes them.

Think of a restaurant. Inline, each customer waits at the counter while their meal cooks. With a queue, the waiter pins a ticket on the rail and the cooks take tickets off it. A dual write is a waiter who writes the order in the book, then walks to the rail, and may faint on the way, so the kitchen never hears. The outbox is a book whose page is the record: a runner copies the new pages to the rail, and the page is never lost.

What the caller waits for

Fifty orders a second for 40 seconds, in two rounds. Inline, a request took a median of 54.7 ms and 55.5 ms in the two rounds: the work plus a little. Dual write took 11.0 and 10.9 ms. What is left is the wait for Kafka to confirm the event is stored on three copies (the lab's acks=all setting, which waits for every in-sync copy). The outbox took 3.1 ms in both rounds, which is one database transaction.

The work did not go away, it moved. Measured from the order to the card charge, the median was 52 ms inline, 63 ms with dual write and 73 ms with the outbox. The slowest one charge in a hundred came 55 ms after the order inline, 214 to 225 ms with dual write and 226 to 234 ms with the outbox. The relay looks for new rows every 20 ms, so an event typically waits about ten ms longer.

Try it · What the caller waits forLab 12 · 01_inline_vs_queued.py · 50 orders a second, two rounds

what the caller waits

Inline
54.7 ms · r1
55.5 ms · r2
Dual write
11 ms · r1
10.9 ms · r2
Outbox
3.1 ms · r1
3.1 ms · r2

Slow card service: 300 ms of work, 50 orders a second in, 20 a second out

Request p50, inline
305.5 ms
Request p99, outbox
9.9 ms
Charged, median
31 s
Charged, slowest 1 in 100
75 s
Backlog when load stopped
1,226
Predicted backlog
1,200
Drain, measured
79 s
Drain, predicted
60 s

A slow card service

Now the card service slows down: each order's work takes 300 ms instead of 50. Six consumers can finish at most six divided by 0.3, which is 20 orders a second, and 50 arrive. Inline, the caller waited the whole time: a median of 305.5 ms per request. With the outbox, the request did not notice: 3.4 ms at the median and 9.9 ms at the slowest one in a hundred.

The charges fell behind. Measured from the order, the median card charge came 31 seconds later, the slowest one in a hundred 75 seconds, and the last one 79 seconds. When the load stopped, 1,226 orders were waiting. The arithmetic predicted it: 50 arriving minus 20 finished, for 30 more every second over 40 seconds, is 1,200.

Draining the backlog took 79 seconds, not the 60 that 1,200 divided by 20 predicts. The topic is split into six partitions, each an ordered slice of the topic, and each order goes to the partition for its user's id. Each partition has exactly one consumer, so the busiest partition sets the pace. Partition 1 got 20% of the orders instead of about 17%, and the other five consumers finished early and sat idle. While the load ran, about 20 orders a second got done ((2,011 − 1,226) ÷ 40); after it stopped, about 15 a second (1,226 ÷ 79).

The gap between two writes

Here is the risky part. Dual write saves the order in one transaction, and then, as a separate step, publishes the event. To test the gap between them, the lab's service exits right after the commit, before the publish, with a 4% chance per order. A hard exit like this stands in for a crash or a kill.

The outbox does the same write differently. The order and its outbox row go in one transaction, so both are saved or neither is. An exit after the commit leaves the row in the database, where the relay, a separate process, finds it and publishes it, even though the service that wrote it is gone.

Results from 02_crashes.py, exercise 2:

  • Dual write: 107 crashes in the gap. Of 3,221 committed orders, 3,078 events reached the topic, so 143 were lost, 4.4% (95% range 3.8% to 5.2%). The 107 were the crashing orders. The other 36 were orders the same process had committed but not yet published when it exited, so a crash takes everything in flight, not just the one request. For 145 orders, the caller never heard "created": the connection dropped.
  • Outbox: 108 crashes in the gap. Of 2,428 committed orders, all 2,428 events reached the topic: 0 lost. For 114 orders, the caller never heard "created," although the order was saved and its event was published.
Try it · Crash between the two writesLab 12 · 02_crashes.py · recorded runs
1. Save the order (database commit)
The process exits here (a hard kill, after the commit)
2. Publish the event to Kafka
Crashes injected
107
Orders committed
3,221
Orders with no event
143
Callers never told 'created'
145

143 lost = 107 orders that crashed in the gap, plus 36 other orders the same process had committed but not yet published.

Random kills and the relay

The gap is not one instruction wide. In exercise 3, the lab sent 100 orders a second and killed the service at 30 random moments, so the gap was every order in flight at that moment.

  • Dual write, waiting for Kafka's acknowledgement: 16 of 5,909 committed orders lost, about one in 370. None of them had been answered with a 201, because the connection dropped before Kafka confirmed.
  • Dual write, not waiting: 17 of 5,900 lost, and all 17 were answered with a 201 "created." The events were most likely still in the service's memory when it died.
  • Outbox, with the relay also killed 30 times: 0 of 5,923 lost. But 12 events reached the topic twice: 5,935 events for 5,923 orders.

The relay, and the copies it leaves

Why the extra copies? The relay takes up to 500 of the oldest outbox rows, sends them to Kafka, and waits until Kafka has confirmed every one. Only then does it delete the rows. A relay killed after sending but before deleting leaves the rows in place, and the next run sends them again. The outbox turns "maybe lost" into "maybe twice."

Twice is fixable, if the consumers can tell they have seen an event before. The lab's consumer test kills a consumer 100 times in each of two groups. With an idempotency table (a record of processed event ids, checked before each side effect), 16,955 duplicate deliveries led to zero repeated side effects. Without one, all 14,768 duplicate deliveries were processed again, which would mean the same card charged twice. An idempotency key does the same job at the other end, when a caller retries an order; Chapter 10 covers that.

A different way to get the same guarantee is change data capture (CDC), which reads the database's own change log instead of an outbox table. Chapter 20 used it to keep a search index in step. Tools such as Debezium do this for Kafka. The lab's README lists it as an exercise; this run did not measure it.

Caveats

  • One run per configuration. Exercise 1 ran two rounds, and the crash counts come from single runs, with the 95% range shown only for the gap loss rate. The random-kill counts are small (16 and 17 lost out of about 5,900), so treat them as the scale, not a precise rate.
  • Simulated work on a laptop. The 50 ms and 300 ms of work are sleeps, and the broker, database and service share one machine. The shapes will carry over; the exact milliseconds will not.
  • The 36 are an inference. The lab attributes them to orders in flight in the same process. The record shows the difference (143 lost, 107 crashing orders), and the explanation is the most likely one.
  • Inline "kept up" only because nothing limited it. The service had no cap on concurrent requests, so about 15 requests were in flight at once (50 a second for 0.3 s). With a thread pool or connection limit, inline would have queued in front of the caller.
  • Not covered: the lab's rebalances, poison messages, broker kills and throughput scripts, and Debezium. Those are the next chapters' material.

The checklist

  1. Queue what the caller doesn't need to wait for. The email and stats can be later; a charge the page shows as "charged" either stays inline or sits behind a status the page can read.
  2. Expect the backlog and do its arithmetic. Work arriving at 50 a second and finishing at 20 grows by 30 a second; for 40 seconds that is 1,200 orders.
  3. Never save state and publish the event as two steps. Write the event in the same transaction as the state change (the outbox), or read the database's change log.
  4. Waiting for the broker's acknowledgement does not close the gap. It fixed the 17 events lost after a 201 but not the 16 lost in the gap; only the outbox or CDC did.
  5. Expect duplicates from the relay, and make consumers idempotent. Killing the relay 30 times sent 12 events twice; a processed-events table absorbed every duplicate delivery.

Quiz

Try it · Check your understanding0 of 3 answered
  1. 1.A service saves an order, then publishes its event to Kafka as a second step. It crashes between the two. What can happen?

  2. 2.With the outbox, the request's median fell from 55 ms to 3 ms, but the card was charged 73 ms after the order at the median, not 52 ms. What explains that?

  3. 3.In the random-kill test the relay was killed 30 times, and 12 events reached Kafka twice. Why?

Check your understanding

Try each question before opening its answer.

Dual write lost 143 events from 107 crashes. Where do the other 36 come from, and why does a crash in the gap lose more than the one order?

The lab attributes them to other orders the same process had committed but not yet published when it exited. The service writes each order and publishes its event with no shared commit, so every order in flight at the moment of the exit is exposed. A crash takes everything in flight, not just the request that triggered it.

Why was the outbox's card charge later than inline's, and why does that not hurt the caller?

The charge still takes its 50 ms, but it runs in a consumer after the relay has published the event. The median charge came 73 ms after the order with the outbox against 52 ms inline, because the relay polls every 20 ms and publishes in batches. The caller's request never waited for the charge, so its median fell from 55 ms to 3 ms.

Dual write that waited for Kafka's acknowledgement still lost 16 events in the random kills. Why doesn't waiting fix it?

The wait happens after the database commit, so a kill in between still loses the event. The 16 were not answered "created", because the connection dropped before Kafka confirmed. Waiting only fixes the case where the service answers a caller before the event is safe. The gap is between the commit and the publish, and only the outbox or CDC closes it.

The relay sent 12 events twice. Did the consumers process them twice, and what stopped that?

Only if they lacked a record of processed events. The 12 duplicates come from a relay killed after publishing and before deleting its rows. In the lab's consumer test, an idempotency table absorbed all 16,955 duplicate deliveries, so zero were processed twice. Without it, all 14,768 duplicate deliveries were processed again.

The backlog reached 1,226 and the drain took 79 seconds, not 60. What did the arithmetic predict, and what did it miss?

It predicted a backlog of (50 − 20) × 40 = 1,200 and a drain of 1,200 ÷ 20 = 60 seconds, and the backlog was within 2%. The drain was slower because the topic's six partitions were uneven: partition 1 got 20% of the orders, its single consumer set the pace, and the other five sat idle once they finished. While loaded, about 20 orders a second got done; after the load stopped, about 15.

Learning something useful?

New labs, articles, and videos on evaluating and testing AI systems come out regularly. Follow along so you don't miss the next one.