ealeng

Episode 26 of 55 · Messaging

Idempotent consumers: 16,955 extra copies, and no card charged twice

Killing an order consumer every 5 seconds, 100 times, made Kafka deliver 16,955 extra copies of orders it had already sent. A table of processed event ids, written in the same transaction as the card charge, applied none of them twice; the group without one charged 14,768 extra copies. Why a kill repeats the work since the last commit, why a clean stop costs seconds and a kill costs 10 to 15, and why a consumer that is too slow gets treated as dead.

Lab 12 · Queues and Event Streams (Kafka)10 min read
Video transcript9:06

0:00Cold open

0:01

I ran two groups of order consumers side by side, and killed one consumer in each group every five seconds, a hundred times. Only one group had a small table.

0:13

Kafka sent sixteen thousand nine hundred fifty-five extra copies of orders it had already delivered.

0:21

And not one card was charged twice. The group without the table made fourteen thousand seven hundred sixty-eight extra charges.

0:31

So why does a queue deliver the same order twice, and how do you make that harmless?

0:39Intro

0:40

Hands-on system design, part twenty-six.

0:44

Today: why a queue delivers some messages twice, and why a crash costs far more than a clean restart.

0:51Meet Lucía

0:53

I’m Lucía, a platform engineer.

0:56

Orders go into Kafka, on a topic split into six partitions. A group of three consumers shares them: each consumer owns two partitions, and charges the card for every order on them.

1:09

Each consumer keeps its place in a partition: done up to order twelve hundred, say. That place is called the offset. Every five seconds, the consumer sends its latest place to Kafka. That’s a commit.

1:23

Think of a kitchen. Each partition is a rail of order tickets. Each cook works one rail, and remembers how far they’ve got. Every five seconds, the cook writes it on the board: done up to ticket twelve hundred.

1:3901 · What you need

1:40

To run it yourself: Docker, for three Kafka brokers, Postgres, and the consumers, each its own process. One setup script starts everything.

1:51

The quick tests run in a couple of seconds, without Docker.

1:56

The card charge isn’t real: it’s a two-millisecond pause, and a row in Postgres. Everything else is real Kafka, on one laptop.

2:0702 · At least once

2:09

Here’s the consumer. For each order, it does the work first, then notes done, in memory. Every five seconds, the latest note goes to Kafka: that’s the commit.

2:20

Now kill it, with SIGKILL: the process is stopped at once, with no chance to clean up.

2:27

The notes since the last commit never reached Kafka. So the next consumer starts from the last commit, and gets those orders again.

2:36

That’s called at-least-once delivery. Nothing is lost, but some orders arrive twice. In the kitchen: a cook collapses, the next cook starts from the board, and cooks the last few tickets again.

2:5103 · A hundred kills

2:53

The test: three hundred orders a second for five hundred and five seconds. That’s a hundred and fifty-one thousand five hundred. The table group and the no-table group read the same orders, and every five seconds one consumer in each group is killed, and replaced at once.

3:10

The table group got sixteen thousand nine hundred fifty-five extra copies, the other fourteen thousand seven hundred sixty-eight: about a hundred and fifty to a hundred and seventy per kill. At a hundred orders a second, that’s roughly one and a half seconds of work nobody had committed yet. Less than the five-second interval suggests. My guess: some kills hit a replacement that hadn’t started yet. And the table group got fifteen percent more; my guess is that’s just where each kill landed. The table doesn’t change what Kafka sends.

3:45

One order arrived five times. My guess: it was sent again, and the consumer that got it was killed again before it could commit.

3:54

And not one order was lost, in either group.

4:0004 · One table

4:01

The fix is called idempotency: doing the same order twice has the effect of doing it once. The table group has one extra table: the ids of orders already charged. When it records a charge, the consumer also inserts the order’s id. If the id is already there, the insert does nothing.

4:22

So only the first copy of an order is charged. Every later copy finds its id taken, and its charge isn’t applied.

4:31

And the insert and the charge record are one transaction. So a crash can’t save one without the other.

4:4005 · Zero

4:41

The table group: sixteen thousand nine hundred fifty-five extra copies, and zero charged twice.

4:50

The no-table group: every one of its fourteen thousand seven hundred sixty-eight extra copies was charged again, spread across twelve thousand three hundred fifty-five orders. In a real shop, that’s cards charged twice.

5:0606 · When the group changes

5:08

Kills aren’t the only time partitions change hands. When a consumer joins or leaves, the group hands partitions out again. That’s a rebalance. In the kitchen: rails handed to other cooks.

5:21

There are three ways to do it. Eager: every consumer gives back everything, then it’s all handed out again. Cooperative-sticky: only the partitions that move are taken away. And KIP-848, Kafka’s newest protocol, named after its proposal number: the broker, not the consumers, works out who gets which partition, and moves only those.

5:44

A new test: twelve partitions, three consumers, three trials each. A pause is how long some partition went with nothing processed. A consumer joining, or one leaving cleanly: at most three and a half seconds, and no extra copies.

6:01

The longest was cooperative-sticky’s join: three and a half seconds, against eager’s half a second. My guess: cooperative-sticky takes two rounds, take away, then hand out, and the moved partitions wait for the second.

6:17

Now a consumer is killed. Which protocol paused least?

6:23

None of them did much better. Ten to fifteen seconds of pause, and about two hundred to three hundred fifty extra copies, under every protocol.

6:3507 · Why a kill costs more

6:36

Why? Every three seconds, each consumer sends a small heartbeat: still here. A killed consumer just goes quiet. The group only notices after the session timeout with no heartbeat: ten seconds here. Kafka’s default is forty-five. Until then, its partitions sit idle. And here even the survivors’ partitions stalled for a moment.

6:59

A clean stop is different. SIGTERM asks the process to finish up. The consumer commits its place, and tells the group it’s leaving. Nobody waits for a timeout, and nothing is redone.

7:12

So deploy with a clean stop, SIGTERM, not SIGKILL. Here, that mattered more than which protocol you pick.

7:2208 · Too slow counts as dead

7:23

One more way to leave a group: be too slow. A consumer that doesn’t ask Kafka for more within the poll limit is declared stuck, and its partitions are taken away. Ten seconds here; Kafka’s default is five minutes. I sent one order that takes fifteen seconds.

7:41

It was worked on eight times before the test ended. The first consumer was removed after ten seconds, the order went to the next one, which got stuck too, and back.

7:53

The table charged it only once. But each copy still spent its fifteen seconds.

8:00

And everyone else paid: the group handed out partitions forty-two times. By the end, seven thousand seven hundred seventy-four of nine thousand orders were done.

8:13Back to Lucía

8:14

So, three lessons.

8:17

Expect any message more than once. A table, in the same transaction as the charge, made sixteen thousand nine hundred fifty-five extra copies harmless.

8:29

Shut consumers down cleanly. A clean stop paused three and a half seconds at most. A kill, ten to fifteen, under every protocol.

8:39

And keep every message under the poll limit, or it can bounce between consumers, and stall everyone else.

8:47

Next time: falling behind. Lag, order, and one poison message.

8:53

For today: twice is normal.Lucía: Twice is normal.

8:57Summary

8:58

Make processing idempotent, stop consumers cleanly, and stay under the poll limit.

Key takeaways

  • ✓Kafka delivers at least once: a consumer records its place every 5 seconds, so a kill repeats everything it processed since its last record, which in the lab was 148 to 170 extra copies per kill at 100 orders a second per consumer.
  • ✓An idempotency table, a list of processed event ids written in the same transaction as the charge, turned 16,955 extra copies into 0 repeated charges; the group without the table applied all 14,768 of its extra copies, across 12,355 orders.
  • ✓Nothing was lost in either group across 100 kills each, so the price of at-least-once delivery was duplicates alone, and the table was what made them harmless.
  • ✓A clean stop costs little: a consumer joining or leaving with SIGTERM paused a partition for at most 3.49 s and repeated no events in any of its 18 trials, while a kill, SIGKILL, paused for 9.79 to 14.78 s and repeated 192 to 351 events under every protocol.
  • ✓The shutdown mattered more than the protocol: cooperative-sticky's join paused 3.41 to 3.49 s against eager's 0.40 to 0.53 s, but a kill cost 9.79 to 14.78 s under all three protocols, so the lab's advice is to stop consumers cleanly on every deploy.
  • ✓A consumer that goes longer than the poll limit, 10 seconds in this test, is removed as stuck: a 15-second message was processed 8 times, the group made 42 partition assignments, and 7,774 of 9,000 orders finished.

Sixteen thousand nine hundred fifty-five extra copies of orders reached the consumers in one group, and the card was charged for none of them twice. The other group, with the same events and the same kills, had no such table, and charged 14,768 extra copies. This chapter is about the difference, and about what a consumer's crash really costs.

The examples come from Lab 12 (Queues and Event Streams (Kafka)) of the system design labs: script 02_crashes.py, exercise 1 (consumers killed 100 times in each of two groups), and script 03_rebalance.py, exercise 1 (a consumer joining, leaving or dying under three group protocols). 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 consumers and the producers all in Docker. Each row is one recorded run, and the machine was busy (load averages of about 7 to 10), so read the shapes more than the last digit.

At-least-once: the work comes twice

A topic is split into six partitions, each an ordered slice of the topic. A consumer group of three consumers shares them, so each consumer owns two partitions. A consumer keeps its place in each partition, the offset (the position of the last message it has dealt with). Every five seconds it sends its latest place to Kafka. That send is a commit.

The consumer's order of steps is the whole story. For each order it does the work first, then notes "done" in memory. Every five seconds the latest note is committed. A process killed with SIGKILL (the operating system's hard stop, with no chance to clean up) loses every note that was not yet committed. The next consumer starts from the last commit and gets those orders again.

That is at-least-once delivery: nothing is lost, but some orders arrive more than once. The video's kitchen analogy fits: a cook collapses mid-rail, the next cook starts from the board's last note, and cooks the last few tickets again. The consumer does the work and records "done" as two separate steps, and the commit runs on a timer, so the gap between work and commit is where repeats come from.

Try it · Why a kill repeats workIllustration · one consumer, 100 events a second, commit every 5 s

Kill the consumer this long after its last commit

1.5 s after commit
0 s5 s10 slast commitFirstnot committed yetSIGKILL at 6.5 sNext150 repeatednew work
Repeated deliveries
150
Lab, extra copies per kill
148 to 170
Work at risk
1.5 s

The lab’s 100 kills gave 14,768 extra copies without the table (about 148 per kill) and 16,955 with it (about 170). Those are measured. The repeats above are the same arithmetic as the lab’s: work since the last commit times the rate. The slider is a what-if.

The idempotency table

An operation is idempotent when doing it twice has the same effect as doing it once. The lab's consumer makes its card charge idempotent with one extra table, called processed in the lab, which holds the id of each event already handled. Each order's effect and its processed row are written in one database transaction, so both are saved together or neither is.

The check, from the lab's service/consumer.py, reads in order:

INSERT INTO processed (grp, event_id) VALUES (...) ON CONFLICT DO NOTHING;  -- rowcount 1 = first time
INSERT INTO effects (...)  -- one row per delivery; applied = true only when the insert above was new

The first copy of an order inserts its id and is charged. Each later copy finds its id already there, the insert does nothing, and its row in effects is recorded as not applied. The transaction is the point. If the id and the charge were written separately, a crash between them would either charge twice (charged, id not saved) or never charge (id saved, charge lost). One transaction makes that impossible.

Two limits, noted in the lab's checklist. The table only covers effects in the same database: an email or a call to a card provider is not in that transaction, and needs the provider's own idempotency key. And the check here runs after the work, so a copy still spends its time before it is recognised.

What the lab ran

Exercise 1 sent 300 events a second for 505 seconds, which is 151,500 events. Both groups read the same events. Every five seconds one consumer in each group was killed with SIGKILL and replaced at once, 100 times. Only one group had the processed table.

The lab's delivery_metrics.py counts duplicates as deliveries minus distinct events. Results, from data/results/02_crashes.json:

  • With the table: 168,455 deliveries, 16,955 duplicates, spread across 11,049 orders. The most copies of one order was 5. Repeated charges: 0. Lost: 0.
  • Without the table: 166,268 deliveries, 14,768 duplicates, spread across 12,355 orders. The most copies of one order was 4. Repeated charges: 14,768. Lost: 0.

Each kill repeated about 150 to 170 orders (14,768 and 16,955 divided by 100), which is the work of one consumer, 100 orders a second, since its last commit. One order arrived five times, because a consumer that got it was itself killed before it could commit. The run does not explain why the group with the table saw about 15% more copies. The table does not change what Kafka sends, so it most likely reflects where the kills happened to land.

Try it · Same events, 100 consumer killsLab 12 · 02_crashes.py · exercise 1 · recorded run

Copies beyond the first, arriving at the consumers

With the idempotency table
16,955
Without the table
14,768
Events sent
151,500
Kills per group
100
Lost, with table
0
Lost, without
0

Deliveries: 168,455 with the table, 166,268 without. Duplicate deliveries are deliveries minus distinct events. Repeated side effects are the duplicates the consumer applied a second time.

When the group changes hands

Partitions move when a consumer joins, leaves or dies. That is a rebalance, and it stops processing on the partitions being moved. The lab compares three protocols:

  • Eager (range): every consumer gives up every partition, then gets its new share.
  • Cooperative-sticky: only the partitions that move are taken away.
  • KIP-848: Kafka's newer protocol, named after its proposal number, in which the broker, not the consumers, works out the assignment.

The test used 12 partitions, 3 consumers, 240 events a second, a session timeout of 10 seconds, and three trials of each event. The pause is the time a partition went with nothing processed. Longest pause on any partition, in seconds, per trial:

Event Eager Cooperative-sticky KIP-848
A consumer joins 0.53, 0.40, 0.42 3.41, 3.47, 3.49 0.44, 2.30, 3.02
One leaves cleanly (SIGTERM) 3.33, 1.98, 0.81 2.49, 1.40, 0.44 2.74, 1.43, 0.55
One is killed (SIGKILL) 14.78, 13.41, 12.24 12.06, 11.24, 13.26 12.51, 10.82, 9.79

Across the 18 joins and clean leaves, no event was processed again. Across the nine kills, 192 to 351 were processed again under every protocol. This test has no idempotency table, so each repeat was applied twice, as the lab's table labels it.

Try it · Rebalancing, three protocolsLab 12 · 03_rebalance.py · exercise 1 · recorded run

Longest pause on any partition, seconds, three trials. 12 partitions, 3 consumers, 240 events a second, session timeout 10 s. No idempotency table in this test, so every repeat was applied again.

Eager (range)processed again: 275 / 315 / 302
14.78 s · t1
13.41 s · t2
12.24 s · t3
Cooperative-stickyprocessed again: 192 / 331 / 351
12.06 s · t1
11.24 s · t2
13.26 s · t3
KIP-848processed again: 349 / 331 / 314
12.51 s · t1
10.82 s · t2
9.79 s · t3

Across the 9 kills, 192 to 351 events were processed again, under every protocol, and the longest pause was 9.79 to 14.78 s.

The protocol mattered less than the way the consumer left. Cooperative-sticky's join was the slowest join, which is the cost of its two rounds: take away, then hand out, so the moved partitions wait for the second. But that cost is a few seconds, while a kill cost 9.79 to 14.78 seconds in every protocol.

Why a kill costs more

A consumer sends a small heartbeat to the group while it is alive. A killed consumer simply goes quiet, and the group only notices after the session timeout with no heartbeat, which was 10 seconds in this test. Kafka's default is 45 seconds, so a real crash costs 45 seconds or more. Until then, its partitions sit idle. The lab also saw survivors' partitions stall: a survivor, one thread per consumer, suddenly inherited the dead consumer's backlog of 10 to 15 seconds and starved its own partitions while it caught up.

A clean stop is different. SIGTERM asks the process to finish up: it commits its place, and tells the group it is leaving. Nobody waits for a timeout, and the clean leaves above paused at most 3.33 seconds. The lab's advice is to deploy with a clean stop, and that mattered more than the protocol choice.

A consumer that is too slow

Leaving is not the only way out of a group. A consumer that does not ask Kafka for more messages within the poll limit (max.poll.interval.ms, which is 10 seconds in this test and five minutes by default) is declared stuck, and its partitions are taken away. Exercise 2 sent one order whose work took 15 seconds, at 100 orders a second for 90 seconds (9,000 orders).

The order was processed eight times, alternating between two test consumers, slow-1 and slow-2. Each was removed after 10 seconds, the order went to the other, which also got stuck. The table applied it only once, but each copy spent its 15 seconds first. Meanwhile the group made 42 partition assignments and 23 revocations, and 7,774 of the 9,000 orders were done by the end. The fix the lab suggests is to keep messages under the poll limit, or to move slow work off the poll loop.

Caveats

  • One run per configuration. The 148 to 170 per kill, the 15% difference and the rebalance pauses each come from one recorded run. The ranges across the trials are the spread the lab saw, not a confidence interval.
  • The card charge is simulated. It is a 2 ms pause and a row in Postgres, not a payment. The table shows the mechanism, not a real provider's behaviour.
  • Effects outside the database were not tested. An email or a call to a card provider cannot share the table's transaction, so it needs the provider's idempotency key, which the lab did not exercise.
  • Rebalance timeouts were short. The session timeout was 10 seconds, not Kafka's 45, and the trials were three per cell with three consumers, so a bigger group would show different pauses.
  • Not covered here: broker kills (lab script 06_broker_kill.py), lag and order (04_lag_order.py), poison messages (05_failures.py), throughput (07_throughput.py), and the outbox's relay duplicates from the previous chapter.

The checklist

  1. Assume every message can arrive twice. Plan for it before the first kill, not after the first double charge.
  2. Record the event id in the same transaction as the side effect, in the same database. Two separate writes can fail between them.
  3. Stop consumers with SIGTERM. A clean leave paused at most 3.49 seconds; a kill paused 9.79 to 14.78 seconds.
  4. Keep each message under the poll limit. A slow one was processed eight times and forced 42 rebalances.
  5. Use the provider's idempotency key for effects outside the database. The table covers only what is in its own transaction.

Quiz

Try it · Check your understanding0 of 3 answered
  1. 1.A consumer processes an order, then is killed before it records its place. What does the next consumer do?

  2. 2.Where must the check for an already-processed order live, so a crash cannot cause a second card charge?

  3. 3.In the rebalance test, which event caused the longest pauses and the most repeated events under every protocol?

Check your understanding

Try each question before opening its answer.

A consumer is killed after doing an order's work but before committing. Why does the replacement repeat the work, and why does one kill repeat 148 to 170 orders here?

The replacement starts from the last committed place, so every order processed since that commit is delivered again. The commit runs every 5 seconds, and at 100 orders a second per consumer, a kill just before a commit repeats about 500 orders, a kill just after one repeats none. The lab measured 148 to 170 per kill, below the 250 that an average kill would repeat if kills landed evenly in the interval. The video's guess is that some kills hit a replacement that had not started yet.

Why does the idempotency table have to be written in the same transaction as the charge, rather than before or after it?

If the id were saved first and the charge separately, a crash between them would leave the id recorded and the charge never made. If the charge came first and the id after, a crash between them would charge the card again on the next delivery. One transaction means the id and the charge are saved together or not at all.

A consumer leaves the group with SIGTERM and another is killed with SIGKILL. Why is the kill so much more expensive, when both remove a consumer?

The clean stop commits its place and tells the group it is leaving, so nothing waits. A killed consumer goes silent, and the group waits for the session timeout, 10 seconds in this test, before it reassigns partitions. The kill paused 9.79 to 14.78 seconds and repeated 192 to 351 events under every protocol; the clean leaves paused at most 3.33 seconds and repeated none.

The lab's table group saw about 15% more duplicate copies than the group without the table. Does the table cause the extra copies?

No. The table does not change what Kafka sends, so the extra copies come from the kills. The run does not explain the difference. The video's guess is that each kill landed at a different point, and with one run per group the lab's data cannot separate that from chance.

A message took 15 seconds, and the poll limit was 10 seconds. Why was it processed eight times, and what did the table do about it?

Each consumer that held the message was declared stuck after 10 seconds, and the message went to the other test consumer, which was also stuck. Each copy spent its full 15 seconds of work before the table recorded it, so the table applied the charge once but could not stop the copies from running. The group's remedy is to keep each message under the poll limit, or to move slow work off the poll loop.

Next up: Chapter 27, consumer lag and ordering. It covers the lab's lag and order script, how far consumers fall behind and what happens to order across partitions, and then one poison message, which the lab's failures script handles.

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.