Ömer Faruk YILDIRIM
tutorials

Node.js Production Failure Lab · part 15

How Does a Single Message Stop an Entire Queue? Poison Messages, Unbounded Retries and the Dead-Letter Topic

The worker is running, its CPU is idle, the email provider is up and answering in 100 ms; yet for an hour not a single confirmation email has gone out. The culprit is one order from a customer with a broken address, and a sequential consumer that retries it forever. We walk through recognizing a poison message, why the offset doesn't budge, skipping it by hand with rpk group seek, and parking the message together with its reason in a dead-letter topic. The final part of the series.

33 min read75 min hands-oncode(opens in a new tab)

Node.js Production Failure Lab · Part 15 (final part) · Difficulty ★★★ · Reading ~25 min · Lab ~45–75 min

On the afternoon of November 18, 2022, incident.io’s app crashed again and again: 13 minutes of downtime in total within a 32-minute window (incident.io’s write-up). The team quickly came to suspect one thing: a single asynchronous event in the queue (Google Cloud Pub/Sub) was bringing down every server that processed it. When the event couldn’t be processed, the queue handed it out again, and the next server to pick it up crashed too. In the write-up’s words, this is what’s often called a poison pill. What stopped the outage was purging the relevant subscriptions on the queue: those events were deliberately lost, because the team treated asynchronous events as “best-effort”.

This part’s incident is a quiet member of the same family. Nothing crashes. The worker is up, its CPU is idle, the email provider is healthy. But for an hour nobody has received an order confirmation email. The culprit is a single message: an order from a customer with a broken address. And we don’t have incident.io’s luxury: confirmation emails aren’t “best-effort”, so we can’t purge the queue and forget about it. We’ll ask one of the oldest questions in queueing systems: what do you do with a message you can’t process?

What you’ll learn

  • Recognizing a poison message: the consumer is running, the dependency is healthy, but the offset isn’t moving
  • The difference between a consumption rate that’s “slow” and one that’s “zero”; a different signature from the lag in Part 14
  • What happens in kafkajs when an eachMessage throws: retries, backoff, the consumer restarting, and the last committed offset
  • Permanent (4xx) versus transient (5xx, timeout) errors; why retrying only helps with one of them
  • Skipping by hand with rpk group seek: how to do it, and why it isn’t enough
  • The dead-letter topic (DLQ): parking a message unchanged, together with its reason, and moving on
  • Alerting on progress, not on errors

Prerequisites

You can read this article without the lab. These help:

TopicWhySource
Topic, partition, consumer group, consumer lagWhere the incident happens; this part follows on from itPart 14
Offset commits and “resume from the last committed offset”To understand where a consumer reads from when it restartsConfluent, Kafka Consumer
Consuming messages with kafkajseachMessage being called sequentially, offset commitsKafkaJS, Consuming Messages
Retries, backoff and retry budgetsWhen retrying helps and when it hurtsPart 11
Dead Letter ChannelThe classic answer queueing systems give to this questionEnterprise Integration Patterns, Dead Letter Channel

1. The concept: a log read in order, and a message that can never pass

In Kafka, a partition is an append-only log. A consumer group keeps track of where it is in that log with a single number: the committed offset. It means “everything before this is done.” If the consumer stops or restarts, it resumes from where it left off, that is, from this number.

In this model there is no such thing as “skipping a message”. The offset only advances once a message is done. If a message can never be done, a consumer has three options:

OptionResult
Retry until it worksForever, if the message permanently can’t be processed. Every message behind it waits.
Log it and forget it (swallow the error, advance the offset)The queue flows. That message’s work is silently lost.
Set it aside (dead-letter) with its reason, then move onThe queue flows. The message isn’t lost: once someone looks at the reason and fixes it, it gets replayed.

The first two each look reasonable on their own: one says “lose nothing”, the other “stop nothing”. The third is the only option that delivers both.

Let’s also settle up front where retrying helps. An email provider’s 503 (temporarily unable to serve) or a network timeout may clear up a few seconds later: retrying is right. A 422 (this request is invalid and can’t be processed), on the other hand, is permanent: if the address is wrong, the same request gets the same answer every time. Retrying a permanent error only burns time; and if messages are processed in order, that time is everyone else’s time too.

See it yourself: a 40-line experiment

Before going into the lab, it takes a minute to see the three options side by side on your own machine. A log receiving 20 messages a second, the 5th message has a broken address, and the consumer reads messages in order:

// poison.mjs: a log read in order, with a single "poison" message in it.
// Usage: node poison.mjs <retry|drop|dlq>
const mode = process.argv[2] ?? 'retry';
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));

const log = [];                       // topic: append-only
const dlq = [];                       // dead-letter topic
let committed = 0;                    // the consumer group's offset
let sent = 0, lost = 0, attempts = 0;

// 20 messages a second; the 5th message has a broken address.
const producer = setInterval(() => {
  const offset = log.length;
  log.push({ offset, to: offset === 5 ? 'orders@balticoffice' : `c${offset}@example.com` });
}, 50);

async function sendEmail(msg) {       // "MailWave": 10 ms, always 422 for an invalid address
  await sleep(10);
  if (!msg.to.includes('.', msg.to.indexOf('@'))) throw new Error('422 invalid_recipient');
}

async function consumer(seconds) {
  const end = Date.now() + seconds * 1000;
  while (Date.now() < end) {
    const msg = log[committed];
    if (!msg) { await sleep(5); continue; }
    try {
      attempts++;
      await sendEmail(msg);
      sent++;
    } catch (err) {
      if (mode === 'retry') { await sleep(100); continue; }          // offset doesn't advance, same message
      if (mode === 'drop') lost++;                                     // log it and forget it
      if (mode === 'dlq') dlq.push({ ...msg, headers: { error: err.message, 'source-offset': msg.offset } });
    }
    committed++;                                                       // move on to the next message
  }
}

await consumer(3);
clearInterval(producer);
console.log(`${mode.padEnd(5)}: written ${log.length}, sent ${sent}, attempts ${attempts}, ` +
  `offset ${committed}, lag ${log.length - committed}, lost ${lost}, DLQ ${dlq.length}` +
  (dlq.length ? ` ${JSON.stringify(dlq[0].headers)}` : ''));
for m in retry drop dlq; do node poison.mjs $m; done

On my machine (Node.js 22.18):

retry: written 58, sent 5, attempts 29, offset 5, lag 53, lost 0, DLQ 0
drop : written 59, sent 58, attempts 59, offset 59, lag 0, lost 1, DLQ 0
dlq  : written 59, sent 58, attempts 59, offset 59, lag 0, lost 0, DLQ 1 {"error":"422 invalid_recipient","source-offset":5}

Notice three things:

  1. retry: 58 messages arrived in 3 seconds, 5 went out. The consumer isn’t idle (29 attempts), but they’re all for the same message. The offset is stuck at 5; lag grows at the arrival rate. Nothing was lost, and nothing made progress either.
  2. drop: the queue flows, lag is zero. The 1 lost message is known only to a log line.
  3. dlq: the queue flows, nothing was lost. The poison message waits in a separate place, together with its reason and source.

And one more thing: to anyone looking at its CPU or its dependency, the consumer on the retry line looks perfectly healthy. It’s running, making calls, getting answers.


2. The incident: two days before Christmas, a Wednesday afternoon

🔥 [FIRING] ConfirmationsStuck: no order confirmation sent for 10 minutes, while orders keep coming in

Wednesday, December 23, 14:40. Since about 14:02, nobody has received a single order confirmation email. Orders are being placed and paid for as usual.

What’s strange:

  • The worker is running: no crashes, no restarts, its CPU is idle.
  • MailWave is up: the status page is green, and it answers the worker’s requests in under 100 ms.
  • Part 14’s fix went live yesterday: the worker was sending 32 emails at once and lag was at zero.
  • Another release went out this morning:
VersionWhenChange
2.28.0this morningfeat(notifications): the worker processes order events in order again, one at a time: shipping and delivery emails are coming, and none of them may overtake the confirmation
fix(notifications): a confirmation that can’t be sent is no longer dropped with an error in the log: the message fails and is retried from the topic
2.27.1yesterdayfix(notifications): the worker sends 32 confirmation emails at once

Both changes are well-intentioned, and each makes sense on its own. MailWave answering in ~90 ms again makes sequential processing sufficient (~10 messages a second, three times the incoming 3). The second change is part of a story that has been running since Part 3: emails must not get lost.

ShopFlow also has a convention for consumers: a message a consumer gives up on is published unchanged to <topic>.dlq, with the reason in a header. Nothing is lost; once the reason is fixed, someone can replay it.

If you’ve set up the lab, start the incident:

git clone https://github.com/FARUK-YILDIRIM/nodejs-production-failure-lab.git
cd nodejs-production-failure-lab
./lab start 015

In the lab the scenario is compressed: the queue stops a minute after traffic is switched on.

💡 Want to try it yourself first? Stop here, open Grafana (http://localhost:3000), scroll down to the Queues row and investigate on your own for 30 minutes. The results of each step below are in collapsed boxes; open them when you get stuck. For the lab’s own hints: ./lab hint 015.


3. Investigation, step by step

Step 1: Slow, or stopped?

We have a reflex from the previous part: look at the Consumer lag and Messages per second, written and consumed panels in the Queues row, then put the worker’s own counter side by side with the rate written to the topic.

What do we see?

Grafana: on the left consumer lag, rising in a straight line from 05:45, ~1,450 at 05:53; on the right ~3/s written to the topic, consumed at zero after 05:45

From 05:45 the lag rises as if drawn with a ruler: ~1,450 at 05:53. On the right, “consumed” (yellow) drops to zero at 05:45 and stays there; written (green) is ~3 a second.

Grafana Explore: ~2.9/s written to order-events; confirmations sent by the worker sit on top of the written rate until 05:45, then drop to zero at 05:46

The worker’s own counter (order_confirmations_sent_total): for the first minute it sends at the incoming rate, after 05:45 nothing at all. The 1-minute window spreads the drop out to 05:46.

In Part 14 the consumption rate was low but a flat line: the consumer had hit a ceiling. Here consumption is zero. The lag’s growth rate is exactly the order rate (~3/s). That’s the signature telling you the worker isn’t slow, it isn’t making any progress.

Lesson: “Lag is growing” can be a symptom of two different diseases. If the consumption rate is flat and above zero, it’s a capacity problem; if it’s zero, the consumer is stuck somewhere.

Step 2: Could MailWave be down? Is the worker overloaded?

The first two suspects are always the dependency and the service itself. Look at MailWave’s responses by status code, the worker’s CPU and MailWave’s response time:

sum by (status) (rate(mailwave_requests_total[1m]))
rate(process_cpu_seconds_total{job="worker"}[1m])
sum(rate(mailwave_request_duration_seconds_sum[1m])) / sum(rate(mailwave_request_duration_seconds_count[1m]))
What do MailWave and the worker say?

Grafana Explore: MailWave's 202 responses drop from ~2.9/s to zero at 05:45; at the same moment 422 responses begin and hold steady at ~0.3/s; no 503s

Green: emails accepted by MailWave (202). Zero after 05:45. Yellow: 422s, ~0.3 a second, nonstop. The worker keeps calling MailWave; MailWave keeps answering, but always with the same answer.

Grafana Explore: worker CPU flat around 0.02 cores; MailWave's average response time between 0.08 and 0.11 s

The worker’s CPU is ~0.02 cores; MailWave’s average response time is 80–110 ms. The worker isn’t busy and MailWave isn’t slow.

  • It’s not “MailWave is down”: it answers within milliseconds. There are next to no 503s (transient errors); every answer is a 422.
  • It’s not “the worker is overloaded”: the CPU is idle.

But the 422 is a clue: in HTTP it’s Unprocessable Content, meaning “the request is well-formed but I can’t process its content”. It isn’t transient. So whose email is being sent in these ~18 requests a minute?

Lesson: A dependency being “up” doesn’t mean your requests are succeeding. Break them down by status code.

Step 3: Where is the group?

Ask the broker: is the consumer group’s offset moving? Run the command twice, a minute apart.

./lab shell redpanda
rpk group describe order-confirmations
What does the broker say?

rpk output: at 05:46:51 the group is Empty, 0 members, CURRENT-OFFSET 178, LOG-END-OFFSET 491; a minute later at 05:47:52 Stable, 1 member, CURRENT-OFFSET still 178, LOG-END-OFFSET 662

Between the two runs the end of the topic moved from 491 to 662; the group’s offset stayed at 178. In the first run the group has no members at all (Empty): at that very moment the worker was leaving the group and rejoining it. In the second there is a member, but the MEMBER-ID is from a different session.

Two things together:

  1. The offset is frozen on a single message: 178.
  2. The consumer keeps leaving the group and rejoining it. The process isn’t restarting (Docker shows no restarts), but kafkajs’s consumer is.

Step 4: What does the worker say?

./lab logs worker
The worker’s log

Worker log: from 05:45:04 onward, always "Error when calling eachMessage, MailWave responded 422 invalid_recipient" for offset=178; after six attempts "Crash: KafkaJSNumberOfRetriesExceeded" and "Restarting the consumer in 7176ms"; then the same loop, this time 10848 ms

Always the same offset (178), always the same error (422, invalid_recipient). The time between attempts roughly doubles each time; after the sixth, kafkajs gives up and restarts the consumer 7–12 seconds later. Then it starts over.

Let’s unpack the loop step by step:

  1. The worker processes message 178; MailWave returns 422. The worker’s MailWave client treats 422 as non-retryable and throws the error immediately.
  2. Since 2.28.0 nobody inside eachMessage catches that error. kafkajs considers the message unprocessed; the offset doesn’t advance.
  3. With kafkajs’s default retry settings (5 retries, exponential backoff starting at 300 ms) the same message is retried. All 422.
  4. When the retries run out the consumer “crashes” (KafkaJSNumberOfRetriesExceeded), and the restartOnFailure default restarts it (KafkaJS, Configuration).
  5. The restarted consumer joins the group and resumes from the last committed offset: 178. Back to the start.
  6. Because messages are processed in order (“by default, eachMessage is invoked sequentially for each message in each partition”, KafkaJS, Consuming Messages), 179 and everything after it never get their turn.

Most of the worker’s time is spent in the backoff before a retry and in waiting to restart. That’s why the CPU is idle.

Lesson: The same error logged over and over for the same offset is the fingerprint of a poison message. “There are errors” isn’t enough; look at which message they’re for.

Step 5: Read the message

You know the offset. Look at the message itself and at the customer it belongs to:

./lab shell redpanda
rpk topic consume order-events --offset 178 --num 1
-- ./lab psql
SELECT o.id AS order_id, o.customer_id, c.name, c.email, o.created_at, o.confirmation_sent_at
  FROM orders o JOIN customers c ON c.id = o.customer_id
 WHERE o.id = 487325;
The poison message

rpk and psql output: the message at offset 178 has key 50001, value orderId 487325, customerId 50001, total $5,969.55; in psql the customer is Baltic Office Supply, email orders@balticoffice, confirmation_sent_at empty

The message at 178 is order 487325: customer 50001, Baltic Office Supply. The email address is orders@balticoffice: no top-level domain. Its confirmation never went out.

Customer 50001 is a business customer imported from a marketplace partner in mid-December. The partner’s export truncated the address. It reorders office supplies at regular intervals (every 5 minutes in the lab). It had never placed an order until today; its first order came in at 14:02 (05:45:04 in the lab).

MailWave is right: no email can be sent to this address. And no amount of retrying will change that.

Step 6: MailWave’s side

MailWave’s delivery log (like a provider’s dashboard) shows every send attempt for that order:

curl -s "http://localhost:8025/v1/messages?orderId=487325"
What did MailWave see?

MailWave delivery log summary: 84 attempts, all 422, all to orders@balticoffice; among the first 20 attempts gaps of 0.4, 0.7, 1.2, 2.2, 4.6 seconds, then 7–12 second gaps

In five minutes, 84 attempts, all 422, all to the same address. The gaps mirror kafkajs’s backoff and restart exactly: 0.4 → 0.7 → 1.2 → 2.2 → 4.6 s, then a 7–12 second restart gap, then 0.4 s again.

MailWave is healthy and consistent: it gives the same answer to the same question every time. We’re the ones asking it again every time.

Step 7: The latest code

You now know where to look: app/src/worker.ts.

await consumer.run({
  // In order, one message at a time: order status emails (shipped, delivered) are
  // coming, and must never overtake the confirmation. MailWave answers in ~90 ms
  // again, so this keeps up with about 10 orders per second.
  eachMessage: async ({ message }) => {
    const event = JSON.parse(message.value?.toString() ?? '{}') as OrderPlaced;
    // No confirmation is dropped anymore: if it can't be sent, the message fails,
    // its offset isn't committed, and it's retried from the topic.
    await confirm(event);
  },
});

The comments are honest, and both decisions are spelled out: (1) in order, one at a time; (2) a confirmation that can’t be sent throws and is retried from the topic. The previous version caught the same error with a try/catch and logged it: the queue flowed and the confirmation was silently lost. 2.28.0 set out to fix that and swung to the other extreme.

Taken together, the two decisions say: a single message that can never succeed stops everything behind it. The change had been tested against MailWave’s transient errors (503); there, retrying is exactly the right behavior. Nobody tested it with a permanent error.

The lab’s diagnosis questions and answers (./lab submit 015)
QuestionAnswer
Why did the confirmations stop?The worker is stuck on one message it can never send, retrying it forever, and every message behind it waits
Why can’t that one message be sent?Its customer’s email address is invalid, and MailWave refuses it
What should the worker do with a message it can’t process?Set it aside, with the reason, where someone can fix and replay it, and move on

4. Mitigation: stop the bleeding first by moving the group forward by hand

A code fix needs review. In the meantime, the way to get the queue moving is to move the consumer group one past the poison message. rpk group seek does exactly that (Redpanda, rpk group seek); --to-file expects topic partition offset on each line. Kafka only lets you change a group’s offset while the group has no active members, so stop the worker first.

Write the message down before you skip it. Its confirmation still has to go out; once the address is fixed, you’ll need to trigger it by hand.

# from the repo root; 179 = the stuck offset (178) + 1
docker compose -f incidents/015-stuck-queue/compose.yaml stop worker
docker compose -f incidents/015-stuck-queue/compose.yaml exec redpanda sh -c \
  "echo 'order-events 0 179' > /tmp/seek.txt && rpk group seek order-confirmations --to-file /tmp/seek.txt"
docker compose -f incidents/015-stuck-queue/compose.yaml start worker

Seek output: the worker is stopped at 05:54:57, the group is moved from 178 to 179, the worker starts at 05:55:01; two and a half minutes later the group is at 1046, lag 1294

The group moved from 178 to 179 and the worker started. Two and a half minutes later the group is stuck again: this time at offset 1046.

Grafana: lag drops from ~2,020 to ~1,150 at 05:56:40, then rises again with the same slope; in the consumption panel a single ~58/s spike at 05:56:40

After the seek the worker sent ~870 confirmations (lag from ~2,020 to ~1,150), then stopped again. The drop is a single vertical line because kafkajs commits the offsets of a large batch all at once when an error occurs.

What’s at 1046? The partner’s next order. It was placed at 05:50:04; when we did the seek it was already in the queue, waiting behind the first poison message. Because the partner orders every 5 minutes, skipping by hand buys you at most until its next order. And every skip means one more confirmation lost: nobody notes the skipped message down anywhere in the topic.

Two more things can be done in the meantime:

  • Fix the customer’s address together with the partner. That lets today’s confirmations go out and keeps the next order from being poisonous. But it only clears this poison.
  • Don’t: restart the worker. It resumes from the last committed offset, which is the same message. kafkajs is already doing that every ~20 seconds.
  • Don’t: move the group to the end of the topic (--to end). The queue empties instantly, and with it the confirmations of the ~1,500 customers behind it.

5. The fix: park what you can’t process, and move on

For a permanent error, retrying isn’t the answer; losing the message isn’t the answer either. ShopFlow’s own convention provides the answer: publish the message unchanged, together with its reason, to order-events.dlq, and move on.

const DEAD_LETTER_TOPIC = `${ORDER_EVENTS_TOPIC}.dlq`; // order-events.dlq
const producer = kafka.producer();                     // connect at startup, disconnect at shutdown
const deadLettered = new Counter({ name: 'order_events_dead_lettered_total', /* … */ });

await consumer.run({
  // Order is preserved: one at a time, in sequence (2.28.0's requirement)
  eachMessage: async ({ topic, partition, message }) => {
    try {
      const event = JSON.parse(message.value?.toString() ?? '') as OrderPlaced;
      await confirm(event);
    } catch (err) {
      // sendOrderConfirmation already retried MailWave's transient errors. Trying
      // this message again won't change the answer, and would hold up every message
      // behind it: park it in the dead-letter topic, with the reason, and move on.
      // Nothing is dropped: it's waiting there for someone to fix and replay it.
      await producer.send({
        topic: DEAD_LETTER_TOPIC,
        messages: [{
          key: message.key,
          value: message.value,                         // unchanged
          headers: {
            error: err instanceof Error ? err.message : String(err),
            'source-topic': topic,
            'source-partition': String(partition),
            'source-offset': message.offset,
            'failed-at': new Date().toISOString(),
          },
        }],
      });
      deadLettered.inc();
      logger.error({ err, offset: message.offset }, 'order event parked in the dead-letter topic');
    }
  },
});

Line by line:

  1. Every error is caught, JSON.parse included. A malformed message is just as poisonous as one that can’t be sent. (?? '' instead of ?? '{}': an empty message no longer silently becomes {}; it fails to parse and gets parked.)
  2. Transient errors are still retried first, but in the right place: sendOrderConfirmation retries MailWave’s 5xx responses and network errors internally, a bounded number of times (3 attempts). What ends up in the catch is what still fails after that.
  3. The message is published unchanged, with the same key. Its reason, source (topic, partition, offset) and time are in the headers. When someone looks at the DLQ, the answers to “what, from where, why, when” are right on the message.
  4. Then eachMessage returns normally. kafkajs considers the message processed, the offset advances, and it moves on to the next message.
  5. If publishing to the DLQ also fails (the broker is down), the error propagates and the message is retried as before. Nothing is lost; in that case the queue stopping is the right behavior too.
  6. A counter and a log line: every parked message is visible. The biggest danger with a DLQ is messages quietly going there and being forgotten.

The ordering requirement is left intact: the worker still processes one at a time, in sequence. That has a cost, which we’ll come back to below (Section 8).

6. Verification

./lab deploy
./lab verify 015

What happened to the queue?

The deploy finished at 06:00:42; the new worker started consuming at 06:00:37 and, one second later (06:00:38), parked the first poison message (1046). Then it set about draining the ~2,000 backed-up messages.

Before and after the fix: lag rises to ~2,020 from 05:45 to 05:56, drops to ~1,150 with the seek and rises again, then from ~2,430 at 06:04 falls in steps to zero around 06:05:40 and stays there; on the right, a new series in the consumption panel for messages written to order-events.dlq

Orange dashed lines: the lab’s start (05:44) and the deploy (06:00). After the deploy, lag drops to zero in ~5 minutes and stays down. The stepped look comes from commits happening at the end of each batch; the real rate is in the graph below.

Grafana Explore: confirmations sent by the worker rise to ~9/s after 06:00:40 and merge with the written rate (~3/s) at ~06:05:40; the blue line is the number of messages in the DLQ, 1 at 06:00:38, then 2, 3 and 4 at 06:05:25

Yellow: confirmations sent by the worker. After the deploy ~9.1/s (the ceiling of sequential processing), then on top of the incoming rate (~3/s) once the backlog has drained. Blue: the number of messages in order-events.dlq, climbing step by step to 4. The 05:55–05:57 peak in the middle is the brief breather after the seek.

The backlog contained three more orders from the partner (05:50, 05:55, 06:00); each was parked when its turn came, and the queue never stopped. Its new order at 06:05:04 was parked 21 seconds later (06:05:25); at that moment the worker was still draining the tail end of the backlog.

rpk output: the first message in order-events.dlq; key 50001, value the original order event, headers error "MailWave responded 422 invalid_recipient", source-topic order-events, source-partition 0, source-offset 1046, failed-at; below it a summary of the four messages in the DLQ: source-offset 1046, 1920, 2778, 3658

Every message in the DLQ is an exact copy of the original plus its reason. source-offset gives its place in the topic, error its reason, failed-at its time. Four messages, the partner’s four orders.

psql output: of the 338 orders in the last two minutes, all 338 got their confirmation, p95 delay 0.27 s; none of the partner's five orders has a confirmation_sent_at, the first one, 487325, highlighted

Of the 338 orders in the last two minutes, all 338 were confirmed, p95 delay 0.27 seconds. At the bottom, the partner’s five orders: none of their confirmations went out, and none could have. Four are waiting in the DLQ. The highlighted one, 487325, isn’t there: we skipped it with the seek. That’s the cost of skipping by hand: had we not written it down, this table would be the only place that knows this confirmation still needs to be sent.

./lab verify 015

verify first drains the topic (by restarting the broker), then runs a normal Wednesday’s traffic (~66 req/s, ~3 orders a second) for 60 seconds; at second 10 an order comes in from customer 50001:

MetricTargetBeforeAfter
Confirmation email delay p95 (from order to MailWave’s acceptance)< 5 s48.66 s267 ms
Undeliverable confirmations parked in order-events.dlq≥ 1none (the topic was never created)1: the partner’s order
CPU (API)0.30 cores0.29 cores
Event loop utilization (API)13%13%
Waiting in the pool (max)00

The 48.66 seconds in the “Before” column is an interesting number: the measurement lasts 60 seconds and the partner’s order arrives at second 10. No confirmation for any order after that goes out before the measurement ends; the SLO query counts unsent confirmations as having waited until the end of the measurement. So 48 seconds isn’t a ceiling, it’s the length of the measurement: had the measurement lasted an hour, the p95 would have approached an hour. In the “After” column the partner’s order is in the DLQ, and every other confirmation went out in ~0.3 seconds.

The API’s rows don’t change: the API was never sick in this incident. One of the functional checks confirms that placing an order really does send a confirmation email.


7. Fixes that look right but aren’t

AttemptWhy it falls short
Catching and logging the error (as before 2.28.0)The queue flows, the confirmation is silently lost and nobody sends it. That’s exactly what 2.28.0 set out to fix. The lab’s second SLO (≥ 1 message in the DLQ) catches it.
Retrying with a longer backoffA permanent error is permanent. Every message behind it just waits longer.
Validating the email in the worker and skipping the orderOnly covers this poison; the next broken field, malformed JSON or deleted product stops the queue again. And the confirmation is still lost.
Going back to concurrent processing (as in 2.27.1)The other confirmations go out, but the batch’s offset never advances: every retry resends all of them, and lag grows. It also breaks the ordering requirement.
Restarting the workerIt resumes from the last committed offset, which is the same message. kafkajs is already doing that every ~20 seconds.
Moving the group forward by hand (rpk group seek)Saves today, doesn’t stop the next poison message. In the lab the queue flowed for ~1.5 minutes, then got stuck again on the partner’s next order. If the skipped message isn’t written down, it’s lost.
“MailWave is down”It returns the same 422, every time, within milliseconds.

8. In production: alternatives and prevention

Classify errors. Our fix keeps it simple: whatever is left after sendOrderConfirmation’s few attempts goes to the DLQ. A more mature version separates two paths: permanent errors (4xx, malformed data) go to the DLQ immediately; transient errors (5xx, timeouts) get backoff for a bounded time, or go through a delayed retry topic (order-events.retry). Uber’s Building Reliable Reprocessing and Dead Letter Queues with Apache Kafka describes this pattern: a failed message is published to a retry topic and the original offset is committed; each retry level passes it on to the next with its own delay, and finally to the DLQ. The article also suggests routing by error type, such as network errors to retry and code errors straight to the DLQ.

Don’t dump everything into the DLQ during a real outage. If MailWave goes completely down for half an hour, our fix parks every confirmation from that half hour in the DLQ. The messages aren’t lost, but thousands of them need replaying. For that, pause the consumer while the dependency is unhealthy (a circuit breaker; consumer.pause() in kafkajs) and resume when MailWave is back. A poison message is “one message always fails”, an outage is “every message fails”: looking at the error rate is enough to tell them apart.

A DLQ breaks ordering; choose it knowingly. The goal of 2.28.0 was that an order’s “shipped” email must never overtake its confirmation. When the confirmation is parked in the DLQ, that order’s next event overtakes it. AWS gives the same warning in the SQS documentation: don’t use a DLQ with a FIFO queue whose order must be strictly preserved (Using dead-letter queues in Amazon SQS). If ordering is truly critical, then when one message is parked, the later messages with the same key need to be parked behind it too. That way only that customer’s events wait, not the whole queue.

Give the DLQ an owner, an alert and a replay procedure. A DLQ nobody looks at is where messages go to be forgotten. Kafka Connect’s DLQ offers writing the error context to headers as a separate setting (Confluent, Error Handling and Dead Letter Queues); SQS has a built-in redrive that moves messages back to the source queue. For us the minimum is a small tool that reads the DLQ and, once the reason is fixed, republishes the messages unchanged to order-events, plus a runbook.

Alert on progress, not on errors. In this incident the worker looked healthy: running, CPU idle, dependency up. The real signal was the committed offset not moving:

- alert: ConsumerStuck
  # There's lag, but the group hasn't advanced a single offset in the last 10 minutes.
  expr: |
    sum by (consumergroup, topic) (kafka_consumergroup_lag) > 0
    and
    sum by (consumergroup, topic) (delta(kafka_consumergroup_current_offset[10m])) == 0
  for: 5m
  labels:
    severity: page
- alert: DeadLetteredMessages
  expr: sum by (topic) (increase(kafka_topic_partition_current_offset{topic=~".*\\.dlq"}[15m])) > 0
  labels:
    severity: ticket
  annotations:
    summary: "{{ $labels.topic }}: unprocessable messages were parked; runbook: DLQ replay"

The first would have fired in this incident ~15 minutes after the partner’s first order, independently of the worker’s own metrics. The second makes sure that, after the fix, a human looks at the partner’s address.

Prevent the poison at the source. Validate email addresses when customers are created, and especially in partner imports. This part’s poison came from a partner import 9 days earlier.

Code review checklist (for every consumer):

  • What happens if a message arrives that can never succeed? Does the queue stop, is the message lost, or is it parked somewhere?
  • Are retries bounded? By count or by time. Unbounded retries on a single message are an outage for the whole partition.
  • Which errors are retried? If 4xx responses are retried, why?
  • Are JSON.parse and schema validation inside the try?
  • Does the DLQ have an owner, an alert and a replay tool?
  • Do the tests cover not only transient errors (503) but also permanent ones (422, malformed message)?

Key takeaways

  • In a queue processed in order, a single message that can never succeed stops everything behind it.
  • If lag is growing and consumption is zero, the consumer isn’t slow, it’s stuck. If the same error is logged over and over for the same offset, there’s a poison message.
  • A restart resumes from the last committed offset, which is the same message.
  • Retrying only helps with transient errors. Retrying a permanent error wastes the time of everyone behind it.
  • Between “log it and forget it” and “retry until it works” there is a third way: park it with its reason, and move on. And have a way to replay what’s parked.
  • Measure a healthy-looking consumer by its progress, not by its error count.
  • Two changes that each make sense on their own (“process in order”, “throw the error”) can add up to an outage.

Test yourself

1. Lag is growing. How do you tell a capacity problem from a poison message?

Look at the consumption rate and the committed offset. With a capacity problem, consumption is above zero and flat (Part 14: 1.5/s), and the offset advances, even if slowly. With a poison message, consumption is zero, the offset freezes at a single value, and the logs repeat the same error for the same offset.

2. Why are MailWave’s 503 and 422 different things for the worker?

A 503 is transient: the same request may succeed a few seconds later, so retrying is right. A 422 is permanent: the request (here, the address) is invalid, and the same request gets the same answer every time. Retrying a 422 does nothing except stop the queue; the message belongs in the DLQ.

3. Why doesn’t restarting the worker help? Why is moving the group to the end with rpk group seek —to end a bad idea?

A restarted consumer resumes from the last committed offset, which is the poison message; kafkajs is already doing that every ~20 seconds. Moving to the end empties the queue instantly, but skips every message behind it (here, the confirmations of ~1,500 customers). The right manual mitigation is to move just one past the poison message and write down the skipped message.

4. After the fix, MailWave goes completely down for half an hour. What happens, and what would be better?

sendOrderConfirmation tries every email three times, then the worker parks the message in the DLQ. Every confirmation arriving during the outage (~5,000) goes to the DLQ; they aren’t lost, but all of them need replaying. Better is to separate errors: permanent errors to the DLQ, transient errors to a retry topic; and to pause the consumer while the dependency is entirely unhealthy (a circuit breaker).

Further reading

Basics

Deep dives

Real-world incidents


That’s the series: what did we see in 15 parts?

This is the last part of the series. All fifteen incidents took place in the same online store, ShopFlow, and in every one we followed the same method: first the symptom the customer sees, then a hypothesis from telemetry, and only then the code. Looking back, the incidents fall into four groups:

The Node.js process: the event loop, memory, error handling, libuv.

  1. Event loop blocking: a single CSV report slowed down the whole API; why you look at max for event loop delay.
  2. Memory leak: an unbounded cache killed the service every four minutes; finding the leak’s owner with a heap snapshot.
  3. Unhandled promise rejection: the error from an email sent in the background took down the whole process.
  4. DNS and the libuv thread pool: CPU idle, shared service fast, checkout slow; dns.lookup, the thread pool and keep-alive.

The database: queries, connections, locks.

  1. Missing index: Googlebot showed up, the database fell over; pg_stat_statements and EXPLAIN.
  2. N+1 queries: every query 0.04 ms, the page half a second; the cost of network round trips.
  3. Connection pool leak: a connection never released on the error path froze the API.
  4. Hot row lock contention: waiting for a payment inside a transaction on Black Friday.

Dependencies and resilience: timeouts, retries, idempotency.

  1. Dependency timeouts: an optional service took down the product pages; timeout budgets and graceful degradation.
  2. Idempotency keys: the app said “payment failed”, and the card was charged four times.
  3. Retry storms: a ten-second hiccup turned into a never-ending outage; metastable failure.

The platform and async work: deploys, health checks, queues.

  1. Graceful shutdown: the promise of “zero-downtime deploys”, and 150 errors on every deploy.
  2. Readiness checks: the check meant to keep the site up took it down.
  3. Consumer lag: a queue doesn’t lose work, it makes it wait; a worker that can’t keep up and a single partition.
  4. Poison message: a single message stopped the whole queue; the dead-letter topic.

The whole series fits in a few sentences:

  • Measure latency in more than one place. At the edge, inside the service, in the queue. The gap between them tells you where the time is waiting (1, 4, 14).
  • Not everything that looks “full”, “slow” or “down” is the culprit. The pool, the database, the dependency are often the victims of something else (1, 7, 8, 9, 15).
  • The trigger and the root cause are different things. The quarter-end report, Googlebot, Black Friday, a partner’s CSV only triggered things; the root cause was always in the code or the design.
  • Retrying is a medicine, and it has a dose. In the right place it saves lives (10); in the wrong place it causes outages (11, 15).
  • Anything unbounded eventually hits its limit. A cache (2), a wait (9), retries (11, 15), a queue (14).
  • Health checks and alerts should measure progress, not “is it up” (12, 13, 15).
  • Don’t guess, measure. Flame graph, heap snapshot, EXPLAIN, trace, offset: in every part, a measurement gave the answer.

Thank you for reading and for working through the labs. The best way to learn from an incident once you’ve solved it is to write it up: ./lab report <NNN> generates a postmortem template for every incident.

The full lab: https://github.com/FARUK-YILDIRIM/nodejs-production-failure-lab. If you’ve solved the lab, run ./lab report 015 to generate the postmortem template and compare it with your own write-up.