Node.js Production Failure Lab · part 14
A Queue Doesn't Lose Work, It Makes It Wait: Consumer Lag, Partitions and a Worker That Can't Keep Up
Orders go through fine, but confirmation emails arrive late: first by a few minutes, then by close to an hour. The CPU is idle, the broker is idle, the database is idle. The culprit is a worker that handles messages one at a time and a topic with a single partition. We walk through reading consumer lag, calculating a consumer's capacity as concurrency ÷ latency, and processing concurrently while committing offsets without losing messages.
Node.js Production Failure Lab · Part 14 · Difficulty ★★★ · Reading ~25 min · Lab ~60–90 min
On August 28, 2025, PagerDuty’s Kafka cluster had problems twice in the same day (PagerDuty’s postmortem). The cause isn’t our topic (a bug that opened a new Kafka producer on every API request), but the result is exactly this part’s topic. ~23% of notifications were delayed by more than 5 minutes, and the report also notes: “No notifications were dropped completely.” The messages weren’t lost; they waited in the queue. While recovering, the system had to work through a backlog of stale messages. Some customers got the same webhook twice.
That is exactly what a queue promises: work isn’t lost, it waits. But “waits” comes with no upper bound. How long it waits depends on how fast the reading side reads, and most of the time nobody does that math. In this part we follow a team that moves order confirmation emails to a new worker. Orders go through fine, the CPU is idle, the broker is idle, the database is idle. The emails, meanwhile, arrive late: first by a few minutes, then by close to an hour.
What you’ll learn
- Reading consumer lag: the rate of messages written and consumed, and lag as a message count versus lag as time
- Throughput = concurrency ÷ time per message, wait ≈ lag ÷ throughput (Little’s law)
- “Busy” versus “waiting”: why a service with an idle CPU can’t keep up
- Kafka’s unit of parallelism, the partition, and why a group can’t use more consumers than it has partitions
- The difference between
eachMessageandeachBatchin kafkajs;eachBatchAutoResolve: false,resolveOffset,heartbeat - Committing offsets without losing messages while processing concurrently; at-least-once and idempotency
Prerequisites
You can read this article without the lab. These help:
| Topic | Why | Source |
|---|---|---|
| Kafka basics: topic, partition, ordering | Where the incident happens; order is only preserved within a partition | Apache Kafka, Introduction |
| Consumer group, offset commit, at-least-once | Who reads what, and where they resume from | Confluent, Kafka Consumer |
| Consuming messages with kafkajs | eachMessage, eachBatch and their helpers | KafkaJS, Consuming Messages |
| MailWave’s idempotency key, the outbox | Keeping the same email from going out twice; keeping events from getting lost | Part 3 |
| The general idea of an idempotency key | A repeated operation producing a single result | Part 10 |
1. The concept: how fast does a queue drain?
A queue is always governed by two rates: the rate at which messages arrive (λ) and the rate at which the consumer processes them. For any system that processes messages in parallel, the second one works out like this:
throughput = messages processed at the same time ÷ time per messageA consumer that waits 650 ms per message and processes messages one at a time handles at most 1 ÷ 0.65 ≈ 1.5 messages a second. If 3 messages a second arrive, 1.5 messages pile up every second: ~5,400 an hour. If the same consumer processes 32 messages at once, its capacity becomes 32 ÷ 0.65 ≈ 49 messages/s.
So how long does a newly arrived message wait in a backed-up queue? Roughly the number of messages ahead of it ÷ throughput. This is the everyday form of queueing theory’s Little’s law (L = λW): the work waiting in a system is the arrival rate times the waiting time. A lag of 1,500 messages at 1.5 messages/s means ~17 minutes. The same lag at 49 messages/s means 30 seconds.
Here’s the trap: throughput isn’t set by the CPU. The consumer spends almost all of its time waiting (for a reply from the network, for rows from the database). The CPU graph is flat and says “we have plenty of capacity”. Yet the limit is how many jobs can be waited on at the same time.
See it yourself: a 30-line experiment
Before going into the lab, it takes a minute to see this on your own machine. A queue that receives 3 messages a second, a fake “email service” that waits 500–800 ms per message, and a consumer that reads it with adjustable concurrency:
// queue.mjs: a queue receiving 3 messages a second, a consumer waiting ~650 ms per message.
// Usage: node queue.mjs <concurrency> [seconds]
const concurrency = Number(process.argv[2] ?? 1);
const seconds = Number(process.argv[3] ?? 20);
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
const sendEmail = () => sleep(500 + Math.random() * 300); // "MailWave": 500–800 ms
const queue = []; // each message: its arrival time
let done = 0;
const delays = [];
const t0 = Date.now();
const producer = setInterval(() => queue.push(Date.now()), 1000 / 3); // 3 orders a second
async function consumer() {
while (Date.now() - t0 < seconds * 1000) {
const placedAt = queue.shift();
if (placedAt === undefined) { await sleep(10); continue; }
await sendEmail();
done++;
delays.push((Date.now() - placedAt) / 1000);
}
}
await Promise.all(Array.from({ length: concurrency }, consumer));
clearInterval(producer);
const last = delays.slice(-10);
console.log(
`concurrency ${concurrency}: ${done} emails in ${seconds} s (${(done / seconds).toFixed(1)}/s), ` +
`${queue.length} messages in the queue, recent confirmations delayed ~${(last.reduce((a, b) => a + b, 0) / last.length).toFixed(1)} s`,
);node queue.mjs 1 20; node queue.mjs 1 40; node queue.mjs 32 20; node queue.mjs 32 40On my machine (Node.js 22):
concurrency 1: 31 emails in 20 s (1.6/s), 29 messages in the queue, recent confirmations delayed ~8.3 s
concurrency 1: 62 emails in 40 s (1.6/s), 58 messages in the queue, recent confirmations delayed ~18.0 s
concurrency 32: 59 emails in 20 s (3.0/s), 2 messages in the queue, recent confirmations delayed ~0.7 s
concurrency 32: 119 emails in 40 s (3.0/s), 1 messages in the queue, recent confirmations delayed ~0.7 sNotice three things:
- The one-at-a-time consumer gets stuck at 1.6/s; double the duration and both the backlog and the delay double (8 s → 18 s). The delay isn’t constant, it grows over time: the signature of arrivals exceeding capacity.
- With concurrency 32 the consumer processes at exactly the arrival rate (3.0/s); the queue is empty and the delay is only the email’s own duration (~0.7 s). Its capacity is 49/s; it handles 3/s with ease.
- In both cases the CPU is barely used. The difference is how many
awaits are waiting at the same time.
2. The incident: a Tuesday morning before Christmas
📨 [TICKETS] “I paid, but got no confirmation”: 37 tickets since this morning
Tuesday, December 22, 10:00, the last shopping days before Christmas. A message from the support team: order confirmation emails have been late since yesterday. A few minutes yesterday afternoon, almost an hour this morning, and later every hour. Some customers who couldn’t tell whether their order went through have ordered again. The orders themselves are fine: they’re placed, paid for, and show up under “My orders”.
What changed?
- 2.27.0, yesterday morning: confirmation emails are now sent by a new worker. For every order the API publishes an event to the
order-eventstopic on the message broker (Redpanda, Kafka-compatible); the worker reads the events and sends the email through MailWave. The goal is a good one: when MailWave goes down, emails shouldn’t be lost, they should wait in the topic. In Part 3 we saw how an email the API sent in the background brought down the whole process; this change continues that story. - MailWave moved its API to a new region last Thursday: “slightly higher latency for some customers”.
- Part 13’s fix is live:
/readynow only looks at the database.
| Version | When | Change |
|---|---|---|
| 2.27.0 | yesterday | feat(notifications): confirmation emails sent by a new worker from the order-events topic |
| 2.26.1 | 4 days ago | fix(ops): /ready only checks the database |
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 014In the lab the scenario’s “yesterday” is compressed: the backlog starts building the moment traffic is switched on, and within 10–15 minutes delays reach several minutes.
💡 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 014.
3. Investigation, step by step
Step 1: Is the customer side really healthy?
Support says “orders are fine”. Verify that first: the edge metrics at the top of the dashboard. Then take a look at the Partitions, by topic panel in the Queues row; you’ll need it later.
What do we see?
~66 req/s at the edge, all 200 and 201. No errors. The order request (POST /api/orders) returns 201. From the API’s point of view, nothing is happening.

On the right the site is healthy: ~66 req/s, no 5xx. On the left, a detail that will matter later: the order-events topic has a single partition.
Lesson: If a customer complaint is about “slowness” and the API is fast, the slowness happens after the API’s response. Part of the work is now done outside the request.
Step 2: Where are the emails waiting?
Between an order and its email, the places a confirmation could be waiting: the API, the topic, the worker, MailWave, the customer’s inbox. Look at two panels in the Queues row: Consumer lag and Messages per second, written and consumed.
What does the lag say?
The lag of the order-confirmations group on order-events grows in a straight line: 0 at 05:12, ~1,150 at 05:22. It never levels off. The rate of messages written to the topic (green) is ~2.8/s.

On the left the lag keeps growing; there are occasional drops, but each time it climbs higher than before. The “consumed” line on the right is misleading: mostly zero, with occasional sharp spikes.
Why does the “consumed” line look like that? This panel is computed from the offset committed to the broker. When running with eachMessage, kafkajs “resolves” the offset locally as it processes each message, but commits to the broker only when the batch it fetched is finished. As batches grow, commits get rarer: the lag and consumption panels draw a sawtooth. To see the worker’s real rate, look at its own metric. In Prometheus or Grafana Explore:
sum(rate(kafka_topic_partition_current_offset{topic="order-events"}[1m])) # written
sum(rate(order_confirmations_sent_total[1m])) # emails sent
Green: written to the topic, ~2.8/s. Yellow: emails sent by the worker, flat at 1.5/s as if drawn with a ruler. Traffic fluctuates, the worker’s rate never changes: it has hit a limit.
The difference is ~1.3 messages/s: ~4,700 messages pile up every hour.
Lesson: Don’t look at consumer lag on its own; put the written and consumed rates side by side. If lag is growing and the consumption rate is flat, the consumer has hit a ceiling.
Step 3: What is the customer experiencing?
Lag is a message count. Customers don’t count messages, they count minutes. Every time the worker sends an email, it records the time elapsed since the order was placed in a histogram: order_confirmation_delay_seconds.
How late are the confirmations?
histogram_quantile(0.95, sum by (le) (rate(order_confirmation_delay_seconds_bucket[1m])))
The p95 of confirmation delay goes from zero to ~10 minutes in ten minutes and doesn’t stop. The stepped look comes from the histogram’s buckets (60, 120, 300, 600 s); the trend is real.
The exact numbers are in the database. Every order has created_at and confirmation_sent_at columns (./lab psql):
SELECT id AS order_id,
to_char(created_at, 'HH24:MI:SS.MS') AS placed_at,
to_char(confirmation_sent_at, 'HH24:MI:SS.MS') AS email_sent_at,
round(extract(epoch FROM confirmation_sent_at - created_at)::numeric, 1) AS delay_s,
round(1000 * extract(epoch FROM confirmation_sent_at
- lag(confirmation_sent_at) OVER (ORDER BY confirmation_sent_at))::numeric) AS ms_since_prev_email
FROM orders
WHERE confirmation_sent_at > now() - interval '1 minute'
ORDER BY confirmation_sent_at DESC
LIMIT 10;
The emails going out at 05:25:54 belong to orders placed at 05:19: a delay of ~400 seconds. The last column is even more interesting: there are always 530–800 ms between two consecutive emails. Never less, and never two emails at the same time.
The two numbers agree: the lab started at 05:11:50; over 14 minutes the worker has only managed ~54% of the incoming rate, so right now it’s working on orders from ~6.5 minutes ago (≈ 400 s). And an order placed right now will wait for the ~1,500 messages ahead of it ÷ 1.5/s ≈ 17 minutes. It gets worse every minute.
Step 4: What is the worker spending its time on?
The 650 ms rhythm in the last column is a clue. Open the trace of an order request: when the API publishes the event it puts the trace context into the message headers, and the worker continues it when reading. So a single trace shows the whole journey from order to email.
An order’s end-to-end trace

The order was placed at 05:18:24; the API’s work finishes in 637 ms and the event is in the topic in 1.5 ms. Then ~6 minutes of nothing. The worker’s span is at the far right of the trace: 693 ms, of which 674 ms is a single POST to MailWave.
The worker’s work per message: a SELECT reading the customer (~8 ms), a POST to MailWave (~650 ms), an UPDATE marking the order (~8 ms). Processing the message takes 0.7 seconds; waiting for its turn takes 6 minutes.
Step 5: Capacity or concurrency?
When people hear “the worker can’t keep up”, the first thing that comes to mind is that the worker is busy. Check: the worker’s CPU and MailWave’s response time.
Is the worker busy?
rate(process_cpu_seconds_total{job="worker"}[1m])
sum(rate(mailwave_request_duration_seconds_sum[1m])) / sum(rate(mailwave_request_duration_seconds_count[1m]))
The worker’s CPU is 0.025 cores: 2.5% of a 1-CPU container. MailWave’s average response time is ~0.65 s. The worker isn’t busy; it’s waiting.
The math: 1 ÷ (0.65 + 0.02) s ≈ 1.5 messages/s. Exactly the 1.5/s on the dashboard. While waiting for MailWave’s reply, the worker does nothing else.
Consider that MailWave used to take ~90 ms per email in its old region: the same worker would have handled ~10 messages a second, three times the capacity needed for 3 orders a second. Nobody noticed the worker was sequential, because it took a dependency slowing down for anyone to notice. The trigger is MailWave’s move; the root cause is the ceiling built into the worker’s design.
Lesson: A service with an idle CPU is not “comfortable”. The limit of a consumer waiting on I/O is how many jobs it waits on at the same time.
Step 6: What if we run more workers?
The first suggestion on the team: “let’s scale the worker to 4 instances”. Before trying it, ask the broker:
./lab shell redpanda
rpk topic describe order-events -p
rpk group describe order-confirmationsWhat does the broker say?

The topic has a single partition. The group has one member, and partition 0 is assigned to it; the committed offset is 852, the end of the topic 2350, the lag 1,498.
In Kafka, a partition is assigned to one consumer at a time within a consumer group. The unit of parallelism is the partition. Confluent’s documentation says so plainly: if a group has more consumers than partitions, the extra ones sit idle. Run 4 workers and one of them gets partition 0, the other three get nothing. Throughput is still 1.5/s.
So why does the topic have a single partition? Nobody asked for that. When the API published the first message, the broker auto-created the topic with default settings; Redpanda’s default_topic_partitions defaults to 1 (Redpanda cluster properties). On the lab’s broker, rpk cluster config get default_topic_partitions → 1.
Step 7: The latest code
You now know where to look: app/src/worker.ts.
await consumer.connect();
await consumer.subscribe({ topic: ORDER_EVENTS_TOPIC, fromBeginning: true });
await consumer.run({
// Each message is handled when the previous one is done, and its offset committed.
eachMessage: async ({ message }) => {
const event = JSON.parse(message.value?.toString() ?? '{}') as OrderPlaced;
try {
await confirm(event); // findCustomer (~8 ms) + MailWave (~650 ms) + UPDATE (~8 ms)
} catch (err) {
confirmationFailures.inc();
logger.error({ err, orderId: event.orderId }, 'order confirmation email could not be sent');
}
},
});The comment is honest: each message is processed once the previous one is done. The KafkaJS documentation says the same thing: by default eachMessage is invoked sequentially for each message in each partition (Consuming Messages). One partition × sequential processing = a single lane for the whole group.
The lab’s diagnosis questions and answers (./lab submit 014)
| Question | Answer |
|---|---|
| Where are the confirmation emails waiting? | In the order-events topic: the worker reads it more slowly than orders come in |
| Why can’t the worker keep up? | It handles one message at a time, and each one waits ~650 ms for MailWave |
| Would running four worker instances fix it? | No: the topic has a single partition, and a partition is read by one consumer of the group at a time |
4. Mitigation: stop the bleeding first
- Tell customers: a banner on the site, “Confirmation emails are delayed; your order has been received and appears under My orders.” That’s what stops the duplicate orders; until the emails recover, it’s the most valuable step.
- Don’t: restart the worker. It resumes from the committed offset at the same rate. The backlog stays exactly where it is.
- Don’t: add worker instances. One partition; the extra instances sit idle.
- Don’t: blame MailWave. It got slower and it isn’t ours, but it answers every email we send. The problem is that we never send it more than one email at a time.
5. The fix: many emails at once, offsets once the work is done
The emails don’t depend on each other: nobody minds if order 1001’s confirmation goes out before order 1000’s. So we can process the messages in a batch concurrently. The real question is a different one: when do we advance the offset?
// MailWave takes ~650 ms per email: one at a time, that's 1.5 emails per second,
// fewer than the orders coming in. Emails don't depend on each other, so send up
// to 32 at once.
const CONCURRENCY = 32;
await consumer.run({
eachBatchAutoResolve: false,
eachBatch: async ({ batch, resolveOffset, heartbeat, isRunning, isStale }) => {
let next = 0;
const sendNext = async (): Promise<void> => {
while (next < batch.messages.length && isRunning() && !isStale()) {
const message = batch.messages[next++];
if (message) await handle(message); // confirm(event); errors are logged, not thrown
await heartbeat();
}
};
await Promise.all(Array.from({ length: CONCURRENCY }, sendNext));
// Offsets are committed only once every message of the batch is handled: if the
// worker dies halfway, the batch is read again, and MailWave's idempotency key
// keeps customers from getting the same email twice.
if (isRunning() && !isStale()) resolveOffset(batch.lastOffset());
},
});Line by line:
eachBatch: kafkajs hands the worker every message the broker can give at that moment (up to the size limit) in one go.- 32 “lanes”: 32 copies of the
sendNextfunction are started; each takes the next message and processes it. At most 32 MailWave calls at once: not unbounded, but a deliberate number. Capacity is 32 ÷ 0.67 s ≈ 48 emails/s. eachBatchAutoResolve: false+resolveOffset(batch.lastOffset()): the offset only advances once every message in the batch is done. The kafkajs default (true) is to commit the batch’s last offset automatically ifeachBatchdoesn’t throw; here we do it explicitly ourselves, and only if the worker is still running.heartbeat(): telling the broker “I’m alive” during a long batch. Otherwise the broker might decide the worker is dead and give the partition to someone else.isRunning()/isStale(): if the worker is shutting down or the batch has gone stale because of a rebalance, don’t take new messages and don’t advance the offset.
This design has a deliberate cost: if the worker dies in the middle of a batch, the whole batch is read again. For some emails MailWave gets called a second time. This is called at-least-once delivery: a message is never lost, but it can be processed more than once. Customers don’t get two emails thanks to the idempotency key added in Part 3 (Idempotency-Key: order-confirmation-<id>): MailWave recognizes a second request arriving with the same key.
6. Verification
./lab deploy
./lab verify 014How long did the backlog take to drain?
The deploy finished at 05:26:51. Looking at the worker’s own counter with a 15-second window (rate(order_confirmations_sent_total[15s])), the email rate went from 1.5/s to ~47/s: just below the calculated 48/s. The ~1,650-message backlog drained in ~30 seconds (05:26:58–05:27:30); after that the worker runs at the arrival rate, ~2.8/s.

Orange dashed lines: the lab’s start (05:11:50) and the deploy (05:26:51). After the deploy, lag drops to zero within a minute and never rises again. On the right, the consumption rate now sits on top of the written rate.

The deploy is at 05:26:51. The 1-minute window flattens the peak by spreading it out to ~24/s; the 15-second window shows ~47/s. Afterwards the yellow and green lines are indistinguishable.

The deploy is at 05:26:51. The delay drops from ~10 minutes to a few seconds. The descent looks a bit late, because the last messages of the backlog were also orders that had already waited for minutes.
Put two traces side by side and the difference is stark. A batch from the worker after the fix:

A single batch: 4 messages, 4 MailWave calls starting at the same time. The batch takes as long as its slowest email (786 ms). In the earlier trace, 4 emails would have taken ~2.7 seconds.
And from the database, 7 minutes after the fix:

The delay dropped from 400 seconds to 0.7–1.5 seconds. The time between consecutive emails now drops as low as 21 ms (the ones sent together), and the order numbers are out of sequence: 494773 went out before 494771. Since order doesn’t matter here, we accepted that knowingly.
./lab verify 014
verify first drains the topic, then runs a normal Tuesday’s traffic (~66 req/s, ~3 orders a second) for 60 seconds and measures confirmation delay from the database:
| Metric | Target | Before | After |
|---|---|---|---|
| Confirmation email delay p95 (from order to MailWave’s acceptance) | < 5 s | 37.90 s | 1.44 s |
| CPU (API) | 0.28 cores | 0.28 cores | |
| Event loop utilization (API) | 13% | 12% | |
| Waiting in the pool (max) | 0 | 0 |
The 37.9 seconds in the “Before” column is a single-minute measurement starting from an empty topic. Because the backlog grows by ~90 messages a minute (3/s in, 1.5/s out), the delay keeps rising as the measurement runs: roughly half the elapsed time. Had the measurement lasted an hour, the p95 would have approached half an hour. 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. The remaining ~1–2 seconds are MailWave’s ~650 ms plus waiting for the slowest email in the message’s batch.
7. Fixes that look right but aren’t
| Attempt | Why it falls short |
|---|---|
| More worker instances | The topic has a single partition; a partition is assigned to a single consumer within the group. The extra instances sit idle. |
partitionsConsumedConcurrently on its own | It provides concurrency across partitions. With one partition nothing changes. KafkaJS’s own advice is also not to set it higher than the number of partitions being consumed. |
confirm(event) without await inside eachMessage (fire-and-forget) | Fast and wrong. The offset advances before the email is sent; if the worker stops, in-flight emails are lost. Preventing exactly that was the reason the topic exists. There’s also no limit on how many calls happen at once: a 1,500-message backlog means 1,500 concurrent requests to MailWave. |
| Committing each message as soon as it finishes, out of order | A committed offset means “everything before this is done”. Committing 10 while 7 is still in flight loses 7 in a crash. |
| Restarting the worker | It resumes from the committed offset at the same rate. |
| “MailWave is slow, that’s their problem” | It got slower and it isn’t ours, but it answers every email at whatever speed. We just never ask for more than one at a time. |
| “The broker is slow” | It writes and serves messages in milliseconds (trace: send order-events 1.5 ms). The delay is on the consumer side. |
8. In production: alternatives and prevention
The Kafka way to scale: more partitions. Creating the topic with a deliberate partition count and consuming it with partitionsConsumedConcurrently or multiple worker instances is the natural way to scale a consumer group. The cost: order is only preserved within a partition. Send messages whose order matters (for example, the same customer’s events) with the same key; Kafka writes the same key to the same partition. In this lab the API already uses customerId as the key.
Concurrency independent of partition count. Our fix brings parallelism within a partition. There are mature implementations of the same idea: Confluent’s Parallel Consumer for Java (unordered, partition-ordered or key-ordered processing; it commits offsets only for completed messages, in order) and Uber’s Consumer Proxy. Uber’s article does the same math: processing 1,000 events a second with a 1-second call per message would need ~1,000 partitions in the classic model.
Measure lag as time. “Lag is 1,500 messages” says nothing on its own: for a system processing 1,000 messages a second it’s 1.5 seconds, for this worker it’s 17 minutes. What matters to the customer is the age of the oldest waiting message. WarpStream’s article explains this well: stop counting messages, start measuring time. In this lab the worker’s own histogram does the same job:
- alert: OrderConfirmationsDelayed
expr: histogram_quantile(0.95, sum by (le) (rate(order_confirmation_delay_seconds_bucket[5m]))) > 60
for: 5m
labels:
severity: page
annotations:
summary: "Confirmation email p95 delay is above 1 minute"
- alert: ConsumerLagGrowing
expr: deriv(sum by (consumergroup) (kafka_consumergroup_lag)[15m:1m]) > 0.5
for: 15m
labels:
severity: ticketThe second alert looks not at the absolute value of the lag but at its growth rate: a lag that keeps growing for minutes tells you consumption is slower than arrival. In this incident it would have fired within the first hour; customers noticed a day later.
Outbox. Today the API publishes the event after the order’s transaction. If the broker is unreachable at that moment, the order is placed and the event (and the email) is lost. A transactional outbox writes the event to a table in the same transaction as the order, and a separate process publishes it. That’s at-least-once too; the consumer has to be idempotent. We ran into this in Part 3 as well.
Design review checklist (for every consumer):
- Time per message? How many messages at once? Capacity = concurrency ÷ time. Is there at least 3–5× headroom over the expected peak arrival rate?
- What happens to capacity if a dependency gets 5× slower? (In this incident it got 7× slower.)
- Who creates the topic? Were the partition count, retention and key chosen deliberately, or are they the broker’s defaults from first use?
- When does the offset advance? If the worker dies mid-job, what is lost and what is repeated?
- Are the side effects (email, payment, webhook) idempotent if repeated?
- Was the load test run with the dependency’s realistic latency, or with the local mock’s 50 ms?
Key takeaways
- A queue doesn’t lose work, it makes it wait. How long depends on the consumer’s throughput: concurrency ÷ time per message.
- Wait ≈ lag ÷ throughput. Alert on the age of the oldest message, not on the message count.
- If lag is growing and the consumption rate is a flat line, the consumer has hit a ceiling.
- A service with an idle CPU isn’t comfortable; it’s waiting. For I/O-heavy work, the limit is how many jobs are waited on at the same time.
- In Kafka the unit of parallelism is the partition: the number of active consumers in a group can’t exceed the number of partitions. Don’t leave topics on defaults.
- When processing concurrently, only advance the offset once everything before it is done. At-least-once delivery requires idempotent side effects.
- The trigger (MailWave slowing down) is not the root cause (a sequential consumer, a single partition). When a dependency slows down, recalculate consumer capacity.
Test yourself
1. Lag is 1,500 messages, and the worker processes 1.5 messages a second. When does the email for an order placed right now go out? What if the worker processed 48/s?
Once the 1,500 messages ahead of it are processed: 1,500 ÷ 1.5 ≈ 1,000 s, about ~17 minutes (new messages arriving in the meantime are behind it and don’t affect it). At 48/s, 1,500 ÷ 48 ≈ 31 s. The drain time measured in the lab was also ~30 seconds.
2. Why is the worker’s CPU graph misleading in this incident?
The worker spends almost all of its time waiting for MailWave’s reply; waiting doesn’t use CPU. With CPU at 2.5% it looks like there’s “plenty of capacity”. But the limit isn’t the CPU, it’s that only one email is ever being waited on at a time. Throughput is set by concurrency and latency.
3. If the topic had 4 partitions, would 4 worker instances solve the problem?
Yes, roughly: each instance gets a partition, and total throughput becomes ~4 × 1.5 = 6 messages/s, above 3 orders a second. But the headroom is thin: if MailWave slows down a bit more, it falls behind again. And order is only preserved within a partition; messages are distributed by key (customerId). Increasing the partition count later changes the key → partition mapping.
4. Calling confirm(event) without await inside eachMessage speeds up the worker. Why is it wrong?
kafkajs considers the message processed the moment the handler returns, and advances the offset. The offset gets committed before the email has been sent; if the worker stops at that moment (a deploy, a crash), the in-flight emails are never read again. The point of the topic was to prevent loss. On top of that, concurrency has no limit: a large backlog means thousands of concurrent requests to MailWave, a storm of errors and retry load like in Part 11.
Further reading
Basics
- KafkaJS, Consuming Messages:
eachMessageandeachBatch,eachBatchAutoResolve,resolveOffset,heartbeat,isRunning/isStaleandpartitionsConsumedConcurrently. This part’s code comes straight from here. - Confluent, Kafka Consumer: consumer groups, partition assignment, consumers beyond the partition count sitting idle, offset commits and at-least-once.
- Apache Kafka, Introduction: topics, partitions, keys and the within-partition ordering guarantee.
Deep dives
- Little’s law: L = λW; the fundamental relationship between queue, latency and throughput.
- Uber, Kafka Async Queuing with Consumer Proxy: concurrency bounded by partition count and head-of-line blocking; a proxy that acknowledges out of order and only commits an offset once everything before it is done.
- Confluent Parallel Consumer: parallel processing independent of partition count with a single consumer, in key/partition/unordered modes. (The project is no longer maintained; its README points to a maintained fork and to Kafka’s share consumers. Still valuable as conceptual reading.)
- WarpStream, The Kafka metric you’re not using: measuring lag as time instead of a message count.
- microservices.io, Transactional outbox: writing the event in the same transaction as the business data; the need for an idempotent consumer.
- Redpanda, cluster properties:
default_topic_partitions(default 1) andauto_create_topics_enabled.
Real-world incidents
- PagerDuty, August 28 Kafka outages: a problem in the Kafka cluster delayed ~23% of notifications by more than 5 minutes; no notification was lost entirely, a backlog of stale messages was worked through during recovery, and some webhooks went out twice. The real-world face of the queue’s “doesn’t lose, but makes you wait” promise and of at-least-once.
Next up: The stuck queue. This part’s fix is live: the worker sends 32 emails at once and lag is at zero. The next day, for shipping and delivery emails, the worker deliberately goes back to sequential processing: a status email must not overtake the confirmation. In the afternoon, all of a sudden, nobody gets a confirmation. The worker is running, its CPU is idle, MailWave is up and answering in 100 ms. The consumption rate isn’t slow, it’s zero. We’ll learn about poison messages, dead-letter topics, and how to tell that a consumer is “stuck”.
The full lab: https://github.com/FARUK-YILDIRIM/nodejs-production-failure-lab. If you’ve solved the lab, run ./lab report 014 to generate the postmortem template and compare it with your own write-up.