ealeng

Episode 27 of 55 · Messaging

Consumers at half speed: lag is arithmetic, a random key broke order, and one poison message stopped 2,215 events

Four consumers slowed to under half the producer's speed for five minutes built a pile of 45,581 unprocessed events, which the arithmetic predicted to within 0.2%, and took 105 seconds to drain. Keyed by user id, no event arrived out of order; keyed by a random id, 7,135 of 12,000 did while the backlog drained. A poison message blocked two of six partitions and stranded 2,215 good events, while a dead-letter queue parked it after a fifth of a second, and retry topics kept a 30-second outage from losing anything.

Lab 12 · Queues and Event Streams (Kafka)10 min read
Video transcript10:13

0:00Cold open

0:01

My consumers read order events, and each user’s events have to be handled in order.

0:08

With a random key, while they kept up, two events in a thousand arrived out of order. Easy to miss.

0:16

Then they started forty seconds behind, and drained a twelve-thousand-event backlog. Sixty percent of the events came after a later event from the same user. Every user was affected.

0:29

So what happens when consumers fall behind: to the pile, to the order, and to one bad message?

0:38Intro

0:39

Hands-on system design, part twenty-seven.

0:43

Today: falling behind. Lag, order, and one poison message.

0:48Meet Lucía

0:50

I’m Lucía, a platform engineer.

0:53

A producer writes order events into Kafka, a log split into partitions, running in Docker on one laptop. Four consumers read them, two partitions each.

1:05

Three terms. Lag: events written but not yet processed, the pile, also called the backlog. An offset is an event’s position in its partition. And each consumer commits the offset it has reached, every five seconds here.

1:21

Think of a sorting office. Each partition is a conveyor belt of letters, each consumer a clerk. Lag is the pile waiting on the belts. And a commit is the clerk’s tally sheet.

1:3501 · What you need

1:36

To run it yourself: Docker, for three Kafka brokers, the consumers, and a database that records what they did. The quick tests run in a couple of seconds, without Docker.

1:48

No cloud, and nothing to pay for. The consumers’ work, and the outage later, are simulated. Kafka is real.

1:5802 · Half speed

1:59

First, lag. I measured the four consumers’ capacity, what they can really do: seven hundred twenty-five events a second with four milliseconds of work each, and a hundred forty-eight with twenty-five. You’d expect a hundred and sixty: forty a second each. But four thousand milliseconds divided by a hundred forty-eight is about twenty-seven milliseconds per event. Most likely, reading and recording each one add the other two.

2:26

The producer writes three hundred a second. Then, for five minutes, the consumers slow to the twenty-five milliseconds: half the producer’s speed.

2:36

The prediction takes two lines of arithmetic. The pile grows by three hundred minus a hundred forty-eight point four, a hundred fifty-one and a half a second, for three hundred seconds: forty-five thousand four hundred ninety-five. How close was the real peak?

2:54

Forty-five thousand five hundred eighty-one. Within two tenths of a percent: on the chart, the two lines overlap.

3:03

And the drain, the time to clear the pile once the consumers are fast again: forty-five and a half thousand, divided by the spare speed, seven twenty-five minus three hundred: a hundred and seven seconds predicted. A hundred and five measured. Then the pile stays at zero: it can’t go below.

3:2403 · The longest wait

3:25

Which event waited longest? I first guessed the last one before the consumers sped up. It has the whole pile, forty-five and a half thousand, ahead of it, but fast clerks: forty-five and a half thousand divided by seven twenty-five, about sixty-three seconds. Wrong by more than two times.

3:45

The longest wait was a hundred fifty-three seconds, predicted a hundred fifty-two. The model says it’s the event written halfway through the slowdown.

3:56

Here’s why. The pile grows a hundred fifty-one and a half a second, and the slow clerks clear a hundred forty-eight, almost the same. So an event waits about as long as the slowdown has run so far.

4:09

Written a hundred seconds in: about fifteen thousand two hundred ahead, so about a hundred seconds of wait. Written at the halfway mark, a hundred fifty seconds in: about a hundred fifty seconds, done just as the clerks speed up at three hundred. Later events get fast clerks for part of their wait.

4:29

One more number: the lag monitor, the number dashboards show. It reads committed offsets, and peaked at forty-six thousand eight hundred ninety-six, about thirteen hundred above the true forty-five thousand five hundred eighty-one.

4:44

The dashboard reads the tally sheet, which is updated only every five seconds. So it can miss up to five seconds of the clerks’ progress: at a hundred forty-eight a second, about seven hundred; right as they speed up to seven hundred twenty-five, a few thousand.

5:01

The pile peaked just as they sped up, so my guess is the dashboard’s peak caught one of those moments. The test doesn’t log exactly when.

5:1204 · Order

5:14

Now order. The partition key decides which partition, which belt, an event goes on. Kafka keeps order only within a partition. Two hundred users, twelve thousand events, and each event’s work varies at random: three milliseconds, give or take eighty percent. Out of order means an event processed after a later event from the same user.

5:37

Key by user id: not one event out of order. Not while keeping up, and not while draining a backlog. One user, one belt, one clerk, in order.

5:48

A random key, consumers keeping up: twenty-four of twelve thousand. Two in a thousand. Events of one user are rarely on two belts at the same moment.

5:59

A random key, draining a backlog, with all twelve thousand written before the consumers started: seven thousand one hundred thirty-five. Sixty percent, every user. Most likely, each belt drains at its own speed, so a user’s later event on a fast belt overtakes an earlier one on a slow belt. An ordering bug like this looks fine, until the first time consumers fall behind.

6:2605 · One poison message

6:27

Now failures. A poison message is one that fails every time, like a letter with an unreadable address. A smaller setup: six partitions, three clerks, a stream of two hundred events a second, and one poison message.

6:43

Policy one, block: retry it in place, forever. It stopped two of the six partitions, both belts of that clerk, because a clerk retrying one letter does nothing else. Two belts, about thirty-three a second each, for the last thirty-five seconds: about twenty-three hundred. Two thousand two hundred fifteen good events were stuck at the end, after three hundred ninety-seven tries.

7:07

Policy two, immediate: three tries, then park the poison message in a dead-letter queue, the DLQ. The box for problem letters. Parked after a fifth of a second. The other partitions never slowed.

7:22

Policy three, retry topics: try-later shelves, where a failed event waits five seconds, then fifteen, then forty-five before its next try. Sixty-five seconds of patience in all. But it first asks what kind of failure this is. A malformed message is a permanent failure: it will never work. So it goes straight to the DLQ, after one try.

7:4606 · A 30-second outage

7:48

Now a transient failure, one that may work later: the payment service is down for thirty seconds, simulated. A hundred events a second, so three thousand arrive during the outage. Nothing is wrong with them.

8:02

Immediate retries parked three hundred ninety-four good events in the DLQ. Not all three thousand. Each failing event takes three tries, a tenth of a second apart. Three clerks for thirty seconds is ninety clerk-seconds; at a little more than a fifth of a second each, that’s about four hundred. Every event tried during the outage was parked: three hundred ninety-four. The other twenty-six hundred waited in the pile until payments were back.

8:30

Retry topics parked none. Their sixty-five seconds of patience outlasted the thirty-second outage. All three thousand succeeded on a retry. The longest waits, sixty-six seconds, were the first events of the outage: by the ladder’s arithmetic, five plus fifteen seconds wasn’t enough for a thirty-second outage, so they needed all three shelves. One catch: a retried event leaves its partition, so a later event from the same user can overtake it. I didn’t measure order here.

9:01

Then I moved the three hundred ninety-four from the DLQ back onto the main topic. That’s called a redrive. Every payment was recorded exactly once: none lost, none twice. That needs consumers that remember what they already did, from part twenty-six.

9:20Back to Lucía

9:22

So, three lessons.

9:24

Lag is arithmetic. In minus out, times how long. Measure the capacities, and you can predict the peak, the drain, and the longest wait.

9:35

Key by what must stay in order. A random key looks fine, until the first time you fall behind.

9:43

And retry with patience longer than the outage. Send what will never work straight to the DLQ, and redrive only after a fix.

9:53

Next time: a broker dies. What acks equals one loses, and how fast Kafka really is.

10:00

For today: do the arithmetic.Lucía: Do the arithmetic.

10:04Summary

10:05

Predict lag with arithmetic, key by what must stay in order, and retry with patience.

Key takeaways

  • ✓Consumer lag, the number of events written but not yet processed, is arithmetic: while consumers run slower than the producer, it grows by arrivals minus capacity (300 minus 148 a second, about 152), and the lab's peak of 45,581 was predicted at 45,495, within 0.2%.
  • ✓A backlog drains at the spare speed, not the full speed: the fast consumers' 725 events a second minus the 300 still arriving leaves 425 a second, so the 45,581 pile took 105 seconds to clear, against a predicted 107 and a naive guess of about 63 seconds (peak divided by 725).
  • ✓The event that waited longest was the one written halfway through the slowdown, at 153 seconds against a predicted 152, because the pile grows almost as fast as the slow consumers clear it, so each event waits about as long as the slowdown has run so far.
  • ✓The lag monitor, which reads each consumer's committed position every 5 seconds, recorded a peak of 46,896, about 1,300 above the true peak; a dashboard number can run high by the commit interval times the arrival rate.
  • ✓A partition key decides which partition an event lands on, and order is kept only within a partition: keyed by user id, 0 of 12,000 events were out of order, while a random key gave 24 (0.2%) while consumers kept up and 7,135 (59.5%, every one of 200 users affected) while they drained a backlog.
  • ✓A poison message, one that fails every time, stopped 2 of 6 partitions under retry-in-place and left 2,215 good events stuck after 397 tries, while an immediate policy of 3 tries then a dead-letter queue (DLQ, a holding topic for failed messages) parked it after 0.21 seconds and the retry-topic policy after one try and 0.01 seconds.
  • ✓Retry topics (separate topics that retry after 5, 15 and 45 seconds, 65 seconds of patience in all) outlasted a 30-second payment outage: all 3,000 events that arrived during it succeeded on a retry and none reached the DLQ, while immediate retries parked 394 of them, and redriving those 394 lost none and applied none twice.

Two thousand two hundred and fifteen good events were stuck behind one bad message in the block policy, and 394 were parked in a dead-letter queue by the immediate policy. This chapter covers the three things that go wrong when consumers fall behind: the pile of unprocessed events grows and drains in a way the arithmetic predicts, the order of a user's events breaks under a random partition key, and a message that will never succeed needs a way out of the line.

The examples come from Lab 12 (Queues and Event Streams (Kafka)) of the system design labs, scripts 04_lag_order.py (lag, and order by partition key) and 05_failures.py (a poison message, a 30-second outage, and redrive). The Docker setup is the one from Chapter 25: three Kafka brokers, the consumers and the database, all on one laptop, an Apple M4 Max with 16 virtual CPUs. The consumers' work times are simulated, and each configuration is one recorded run.

Consumer lag: a pile that drains at the consumer's rate

Three terms first. A partition is one ordered slice of a topic, the named stream that events are written to. An offset is an event's position within its partition. Lag is how far behind a consumer group is: the newest offset minus the group's position, summed over partitions. Lag is the number of events written and not yet processed.

Think of a sorting office. Each partition is a conveyor belt of letters, each consumer is a clerk, lag is the pile waiting on the belts, and a commit (the consumer recording how far it has got) is the clerk's tally sheet.

In the lab, four consumers read eight partitions. Their capacity was measured by draining a backlog: 725 events a second at 4 ms of work each, and 148 a second at 25 ms. The producer wrote 300 a second. For five minutes (from 60 s to 360 s) the consumers ran at the slow speed, which is less than half the arrival rate.

While they are slower than the producer, the pile grows by arrivals minus capacity: 300 minus 148.4, about 152 events a second, for 300 seconds. That predicts a peak of 45,495, and the lab measured 45,581. Once the consumers are fast again, the pile drains at the spare speed, 725 minus 300 = 425 a second, which predicts 107 seconds, against 105 measured. The pile then stays at zero, because it cannot go below zero.

Try it · The pile during the slowdownLab 12 · 04_lag_order.py · recorded run
010,00020,00030,00040,00050,0000 s100 s200 s300 s400 s500 sconsumers at half speed
measured lagbacklog.py prediction
Peak, measured
45,581
Peak, predicted
45,495
Drain, measured
105 s
Drain, predicted
107 s
Longest wait, measured
153 s
Longest wait, predicted
152 s

Arriving 300 a second, served 148 a second at half speed: the pile grows by about 151 a second for 300 seconds, then the fast consumers (725 a second) clear it at 725 − 300 = 425 a second. The lab's committed-offset monitor, which reads the tally sheet every 5 s, peaked at 46,896, about 1,300 above the true peak.

Which event waited longest? A guess would be the last event before the speed-up: it has the whole pile ahead of it, but fast clerks. That gives 45,495 divided by 725, about 63 seconds, and it is wrong by more than twice. The measured longest wait was 153 seconds, against a predicted 152. The model says it is the event written halfway through the slowdown. The pile grows at about the rate the slow clerks clear it, so an event waits about as long as the slowdown has run so far, and the events written later get the fast clerks for part of their wait.

The lab also ran a lag monitor, the number a dashboard shows. It reads committed positions, which are updated only every five seconds, so it can miss up to five seconds of progress. Its recorded peak was 46,896, about 1,300 above the true 45,581. On a dashboard, a lag of a few thousand with five-second commits can mean nothing is wrong.

Keys: what a random key does to order

Kafka keeps order only within a partition, and the partition key decides which partition an event goes to. Events that must stay in order (one user's, one order's) need the same key, so they land on one belt and are handled by one clerk. The lab's order test used 200 users and 12,000 events, and each event's work varied at random (about 3 ms, give or take 80%). An event is out of order if it was processed after a later event from the same user.

Try it · Belts and clerksIllustration of the mechanism, not a measurement
Belt 1 · fast clerk (725 a second)A2B5A2 done firstBelt 2 · slow clerk (148 a second)A1B3B4A1 still waiting

Both A events belong to one user, on different belts. A2 was written later but finished first: the fast clerk on its belt reached it while the slow clerk was still on A1.

The result depends on whether consumers are keeping up or draining a backlog:

  • User-id key: 0 of 12,000 out of order, both while keeping up and while draining. One user, one belt, one clerk.
  • Random key, keeping up: 24 of 12,000 (0.2%), touching 21 of 200 users. Events of one user are rarely on two belts at the same moment, so there is little to overtake.
  • Random key, draining: 7,135 of 12,000 (59.5%), and every one of the 200 users was affected. Here all 12,000 events were written first and the consumers started afterwards. Each belt drains at its own speed, so a user's later event on a fast belt overtakes an earlier one on a slow belt.

An ordering bug like this passes every test until the first time consumers fall behind.

Try it · Order by partition keyLab 12 · 04_lag_order.py · Exercise 2 · recorded runs
59.5%
Out of order
7,135 of 12,000
Users affected
200 of 200

Out of order means processed after a later event from the same user. The draining runs wrote all 12,000 events first and then started the consumers.

Poison messages, retries and the dead-letter queue

A poison message is one that fails every time, like a letter with an unreadable address. Retrying it cannot help. Kafka has no built-in dead-letter queue (RabbitMQ and SQS do), so you build one: a DLQ, a topic where a message goes after it has failed too often, so that the rest keep flowing. The lab's DLQ topic is orders.dlq, and its retry topics are orders.retry.1, orders.retry.2 and orders.retry.3, which hold a failed message for 5, 15 and then 45 seconds before the next try.

The poison test used 200 events a second over 45 seconds, six partitions and three consumers, with one bad message 10 seconds in. Three policies were compared:

  • Block (retry in place, forever): the consumer retries the bad message and does nothing else. It stopped 2 of 6 partitions, the two that its consumer owned, for the last 35 seconds. The run ended with 2,215 good events stuck, after 397 tries.
  • Immediate (3 tries, then the DLQ): parked after 0.21 seconds. The other partitions kept running at about 33 events a second each.
  • Retry topics: the lab's classifier (retry_policy.py) sees that this failure is permanent, a malformed message, and sends it to the DLQ after one try, at 0.01 seconds.

A transient failure, such as a timeout, may work later, so it is worth retrying with a delay. A permanent one never will, so it should go to the DLQ at once. The classifier is what makes the difference between one try and three.

Try it · Poison messages and the DLQLab 12 · 05_failures.py · recorded runs
Partitions stopped
2 of 6
Events stuck at end
2,215
Tries on the poison
397
Parked in the DLQ
no

Six partitions, three consumers, 200 events a second. Block stopped the two partitions that the failing consumer owned, for the last 35 seconds of the run.

The harder case is a transient one. In the 30-second outage test, the payment service failed from 15 s to 45 s. Events arrived at 100 a second for 80 seconds (8,000 in all, 3,000 of them during the outage), and nothing was wrong with any of them.

  • Immediate retries parked 394 good events in the DLQ. Each event tried during the outage took 3 tries about 0.1 seconds apart, so the consumers were busy failing and the rest of the outage's events waited in the pile. Only the 394 tried during the outage were parked; the DLQ count depends on how fast you fail, not only on how long the outage lasts.
  • Retry topics parked none. Their 65 seconds of patience outlasted the 30-second outage, and all 3,000 events that arrived during it succeeded on a retry. The median wait was 20.0 seconds, and the longest, 65.6 seconds, belonged to the first events of the outage.

Then the lab redrove the 394 DLQ events back into the main topic, which is the step that follows a fix. Every payment was recorded exactly once: none lost, none applied twice. That only holds when the consumers remember what they have already processed (an idempotency table from [Chapter 25], a record of processed event ids checked before each side effect), because a redriven message may already have been partly processed.

The workflow and the recorded results

The two scripts run the lab's own consumers, failure policies and lag model against a real Kafka cluster in Docker. 04_lag_order.py takes about 19 minutes; it first measures the capacities, then runs the five-minute slowdown and recovery, then the order test with two keys. 05_failures.py runs the poison test, then the outage with both policies and the redrive.

What the run recorded, in order:

  • Lag: peak 45,581 measured against 45,495 predicted; drain 105 s against 107 s; longest wait 153 s against 152 s; lag monitor peak 46,896.
  • Order: user-id key, 0 of 12,000 out of order in both states; random key, 24 keeping up and 7,135 draining.
  • Poison: block stopped 2 of 6 partitions, 2,215 events stuck, 397 tries; immediate parked after 0.21 s with 3 tries; retry topics parked after 0.01 s with 1 try.
  • Outage: immediate parked 394 (1,186 failed tries) and redrove all 394 with 0 lost and 0 applied twice; retry topics parked 0, with 3,000 succeeding on a retry (6,498 failed tries).

Caveats

  • One run per configuration. Each result is a single recorded run on one laptop with a load average of about 6 to 9, so read the shapes more than the last digit.
  • Simulated work. The 4 ms, 25 ms and 300 ms of work are simulated, and the broker, database and consumers share one machine. The arithmetic carries over; the milliseconds will not.
  • The monitor's peak needs care. The results file records a lag monitor peak of 46,896, but the per-sample series saved beside it tops out at 45,694. The chapter quotes the recorded summary, so treat that exact peak as uncertain.
  • Order under retries was not measured. A retried event leaves its partition and goes to a later retry topic, so a later event from the same user can overtake it. The video says so as well, and the lab did not check it.
  • Not covered: the rebalancing of consumers when one joins or leaves, broker failures, throughput, and RabbitMQ's dead-lettering as a comparison. The lab includes a RabbitMQ run for the poison message and outage, but this chapter uses the Kafka numbers only.
  • Only the 30-second outage was tested. A longer outage than 65 seconds would outlast the retry topics, and those events would go to the DLQ; the lab did not measure that case.

The checklist

  1. Write the arithmetic before the incident. Arrivals minus capacity is the growth rate; the pile divided by the spare speed (capacity minus arrivals) is the drain. The lab's version predicted the peak within 0.2%.
  2. Alert on lag in time, not messages. 45,000 events is a few seconds at one rate and most of an hour at another.
  3. Key by what must stay in order. A user-id key gave 0 out-of-order events; a random key gave 7,135 once the consumers fell behind.
  4. Classify the failure before retrying. A malformed message goes to the DLQ after one try; a timeout gets a delay ladder longer than the outage you expect.
  5. Redrive only after the fix, and only into idempotent consumers. The 394 redriven events were all processed exactly once, because the consumers had a record of what they had done.

Check your understanding

Try each question before opening its answer.

Keeping up, a random key put 24 of 12,000 events out of order. Draining a backlog, it put 7,135. Why the difference?

While keeping up, the consumers are close to the arrival time, so one user's events are rarely on two partitions at the same moment and there is little to overtake. While draining, every partition runs at its own speed, so a later event on a fast partition can finish before an earlier one on a slow partition. The same key and the same data gave 0.2% and 59.5%, which is why an ordering bug can pass tests and appear only during a backlog.

Why did the pile take 105 seconds to clear, and not the 63 seconds that peak divided by 725 suggests?

The producer kept writing at 300 events a second during the drain, so the consumers' spare capacity was only 725 minus 300 = 425 a second. The pile, 45,581, divided by 425 is about 107 seconds, and the lab measured 105. Dividing by the full 725 ignores the arrivals that continue while the pile is cleared.

The lag monitor read a peak of 46,896 against a true peak of 45,581. Why does the monitor read high?

It reads each consumer's committed position, and consumers commit only every five seconds. Work done since the last commit is still counted as lag, so the monitor overstates by about the commit interval times the arrival rate. The lab's recorded peak is about 1,300 above the true peak; the saved samples in the same file are lower, so check the source before quoting that exact figure.

Why did immediate retries park 394 events during the outage, when 3,000 arrived?

Each event tried during the outage was retried three times about 0.1 seconds apart and then parked, so the consumers spent about 0.2 seconds on each event. The events not yet tried waited in the pile until payments were back, and only the 394 tried during the outage ended in the DLQ. Retry topics, which waited 5, 15 and 45 seconds, did not run out of patience within the 30-second outage, so none were parked.

Why does a redrive from the DLQ need idempotent consumers?

A parked event may already have been partly processed before it failed, and redriving sends it through the consumer again. Without a record of processed events, the second pass could repeat a side effect, such as charging the card twice. With the idempotency table the lab used, all 394 redriven events were applied exactly once, with 0 lost and 0 applied twice.

Next up: Chapter 28: Kafka acks and lost messages.

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.