📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

๐Ÿ“š Interview question

Tell me about a message queue backlog or poison messages you had to deal with in production. How did you notice, how did you work out whether it was a throughput problem or failing messages, what did you do with the backlog and the dead-letter queue, and what did you change afterwards?

A STAR story for an Azure Service Bus (or similar) backlog with poison messages: queue metrics, throughput maths, dead-letter analysis, safe replay, idempotency and alerting.

Senior RealWorldScenario Advanced azure-service-bus dead-letter-queue messaging poison-messages real-world star-story

๐ŸŽฏ Key points

  • Noticed via oldest-message age and active count; set up proactive alerts so it's caught before customers
  • Throughput maths in messages/second: arrivals vs processing x consumers, drain time at peak and off-peak
  • Used the numbers to decide: capacity drop, not demand rise, so look for failing work before scaling
  • Poison messages: MaxDeliveryCount, DeadLetterReason, failures grouped by message type and error
  • Separated poison from backlog; scaled consumers within downstream limits
  • Fixed the handler; replayed dead letters safely with idempotent handlers
  • Structured logs with MessageId, type and delivery count; DLQ and age alerts; KEDA with a cap
  • Numbers: backlog, drain time, messages lost (ideally zero)

โฑ 30-second answer

Our [invoice queue] on Azure Service Bus grew to [300,000] messages and invoices were [hours] late. I checked two things: throughput maths (arrivals [50/s] vs processing [30/s] with [4] consumers) and the dead-letter queue, which was filling with messages that had hit MaxDeliveryCount. A [schema change upstream] made some messages throw on every attempt; each one was retried [10] times, eating consumer capacity. I shipped a fix that dead-letters non-transient errors immediately, scaled consumers within what [SQL] could take, and replayed the DLQ after fixing the parser, relying on idempotent handlers. Backlog drained in [3 hours], no messages lost. The trade-off: scaling consumers drains faster but can overload the database, so I capped concurrency.

๐Ÿ—ฃ Full answer (senior)

How I would answer this in an interview

"At [company], our [invoice-processing worker] read from an Azure Service Bus queue. One [Monday] customers reported invoices taking [hours] to appear. The active message count was at [300,000] and the oldest message was [four hours] old. Nobody had been alerted because we only alerted on exceptions, and the worker wasn't crashing.

I looked at two things. First, throughput: about [50] messages a second arriving, and our [four] consumers processing about [30] a second, when normally they did [70]. So capacity had dropped, not just demand going up. Second, the dead-letter queue had [8,000] messages with the reason MaxDeliveryCountExceeded. [An upstream team] had added an optional field with a different date format, our deserialiser threw, and each bad message was retried ten times with a lock-duration wait between attempts. Those retries were eating about half our capacity.

I shipped a small fix the same morning: catch deserialisation and validation errors and dead-letter the message immediately with a clear reason instead of retrying it. Throughput went straight back up. I scaled to [8] consumers, but capped concurrency at what [Azure SQL] could handle. Then I fixed the date parsing, tested it against a sample of the dead letters, and replayed them in batches; our handlers were idempotent on invoice id, so replays were safe. The backlog drained in about [three] hours with nothing lost. Afterwards we added alerts on message age and DLQ count, KEDA scaling on queue length, and a contract test with [the upstream team]. My takeaway: a backlog is a maths problem first, and poison messages are the usual hidden term in the equation."


Diagnose: capacity or poison?

Observation Likely cause
Processing rate normal, arrivals up Capacity: scale consumers or optimise handler
Processing rate down, DLQ growing, same message ids retried Poison messages wasting capacity
Processing rate down, handler duration up Slow downstream (SQL, HTTP)
Consumers idle, queue growing Consumer not running, lock lost, or wrong subscription filter

Service Bus features in play

Feature Role
MaxDeliveryCount (default 10) After N failed deliveries, message moves to DLQ
DeadLetterMessageAsync(reason, description) Explicit dead-lettering for non-transient errors
Lock duration / lock renewal Prevents duplicate processing while working
MaxConcurrentCalls, prefetch Consumer concurrency
DLQ path queue/$deadletterqueue Inspect and resubmit

Production example

Template: [invoice queue] backlog [300k], oldest [4 h]; DLQ [8k] from [date-format change]; immediate dead-lettering restored [70 msg/s] per [4] consumers; replay of DLQ after fix; drained in [3 h]; [0] messages lost.

๐Ÿ” What the interviewer is checking

Checks whether you understand at-least-once messaging, can reason about rates and capacity, separate poison messages from load, and clear a backlog without losing or duplicating work.

Green flags

  • Arrival vs processing maths and drain time
  • Uses DLQ reasons and MaxDeliveryCount to find poison messages
  • Idempotent handlers; safe replay; nothing purged
  • Alerts on message age, capped autoscaling; numbers in the result

Red flags

  • "We added more workers" only
  • Purges the DLQ
  • No awareness of duplicates or idempotency

๐Ÿ“š Learn in depth

1. What the interviewer is really assessing

This checks messaging fundamentals (at-least-once delivery, retries, dead-lettering, idempotency) and quantitative thinking (rates, capacity, drain time). It also checks that you protect data: no purging of the DLQ, safe replay.

2. The throughput maths

Backlog growth = arrival rate - processing rate
Processing rate = consumers x concurrency / handler time
Drain time      = backlog / (processing rate - arrival rate)

Example: 300,000 backlog; arrivals 50/s; processing after fix 140/s
Drain time = 300,000 / (140 - 50) = ~3,300 s = ~55 min (longer at peak)

Poison messages subtract capacity: each one costs MaxDeliveryCount handler attempts plus waits.

3. Delivery semantics

Service Bus peek-lock gives at-least-once delivery. A message is redelivered when the lock expires or the handler abandons it; after MaxDeliveryCount it moves to the DLQ. Because duplicates can happen anyway, handlers must be idempotent (dedupe on a business key, upserts, or an inbox table). That idempotency is what makes DLQ replay safe.

4. Frameworks for telling it

STAR, with the maths as one crisp sentence in the Action. CAR for a short version.

5. How it is scored

Weak: "we scaled up the workers." Good: found the poison messages. Strong: did the maths, separated poison from capacity, replayed safely. Excellent: added message-age alerting, explicit dead-lettering policy and a contract test with the producer.

6. Adapting the story

Also answers "a time you worked across teams" (the upstream schema change), "a time you used data" (the maths) and "a time you improved monitoring". Non-technical version: "A batch of broken messages kept being retried and clogged the queue; I set them aside, fixed the bug, and processed them once it was safe."

Try it yourself

  1. Create a Service Bus queue (or use the emulator) and a worker that throws on certain messages; watch them hit the DLQ.
  2. Add explicit DeadLetterMessageAsync for a validation exception and compare throughput.
  3. Write a small tool that reads the DLQ and resubmits messages to the main queue.
  4. Calculate drain time for your own queue at 2ร— arrival rate.
  5. Write and time your STAR version.

๐Ÿ’ป Code

The handler change: dead-letter non-transient failures at once, let transient ones retry.

using Azure.Messaging.ServiceBus;

namespace Invoicing.Worker;

public sealed class InvoiceProcessor(ServiceBusClient client, IInvoiceService invoices, ILogger<InvoiceProcessor> log)
    : BackgroundService
{
    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        await using var processor = client.CreateProcessor("invoices", new ServiceBusProcessorOptions
        {
            MaxConcurrentCalls = 16,          // capped at what Azure SQL can absorb
            AutoCompleteMessages = false,
            PrefetchCount = 32
        });

        processor.ProcessMessageAsync += async args =>
        {
            try
            {
                var message = args.Message.Body.ToObjectFromJson<InvoiceRequested>()
                    ?? throw new InvalidDataException("Empty body");
                await invoices.CreateIfNotExistsAsync(message, args.CancellationToken); // idempotent on InvoiceId
                await args.CompleteMessageAsync(args.Message, args.CancellationToken);
            }
            catch (Exception ex) when (ex is JsonException or InvalidDataException)
            {
                // Non-transient: retrying ten times only wastes capacity.
                log.LogWarning(ex, "Dead-lettering {MessageId}", args.Message.MessageId);
                await args.DeadLetterMessageAsync(args.Message, "InvalidPayload", ex.Message, args.CancellationToken);
            }
            // Other exceptions propagate: the message is abandoned and retried up to MaxDeliveryCount.
        };
        processor.ProcessErrorAsync += args =>
        {
            log.LogError(args.Exception, "Service Bus error {Source}", args.ErrorSource);
            return Task.CompletedTask;
        };

        await processor.StartProcessingAsync(stoppingToken);
        await Task.Delay(Timeout.Infinite, stoppingToken).ContinueWith(_ => { });
        await processor.StopProcessingAsync();
    }
}

public sealed record InvoiceRequested(Guid InvoiceId, Guid CustomerId, decimal Amount, DateOnly DueDate);
STAR template
S: [Worker] on [Service Bus / RabbitMQ]; [arrival rate]; backlog [N], oldest [age].
T: I [owned / was on call for] clearing it without losing messages.
A: Maths: [arrivals vs processing]; DLQ showed [reason]; [dead-letter immediately]; scaled to [N] within [limit];
   fixed [bug]; replayed DLQ (idempotent handlers); added [alerts, KEDA, contract test].
R: Drained in [N h]; [0] lost; no backlog incidents in [period].

Illustrative only: invoice queue, 300k backlog; date-format change upstream; drained in ~3 h.

โš  Common mistakes

  • Mistake: Scaling consumers without checking the downstream. Why it is wrong: You move the bottleneck to SQL and make things worse. Instead: Cap concurrency at what the downstream can take.
  • Mistake: Purging the DLQ to make the alert go away. Why it is wrong: Data loss: those are real invoices. Instead: Analyse, fix, replay.
  • Mistake: Retrying non-transient errors. Why it is wrong: Wastes capacity and delays good messages. Instead: Dead-letter at once with a reason.
  • Mistake: Replaying without idempotent handlers. Why it is wrong: Duplicates. Instead: Dedupe on a business key.
  • Mistake: Logging failures without the message's identity. Why it is wrong: You can't tell one poison message retried 10,000 times from 10,000 different failures, or which message type or producer is the problem. Instead: Structured logs with MessageId, message type, producer, delivery count and error; a metric of failures per message type; DLQ reasons that say what was wrong.
  • Mistake: Alerting only on exceptions or on queue length. Why it is wrong: A slow backlog throws nothing, and length alone doesn't say how late customers' work is. Instead: Alert on oldest-message age, processing rate below arrival rate for N minutes, and DLQ count.
  • Mistake: Doing the drain-time maths on off-peak rates. Why it is wrong: At peak, arrivals rise and drain time can go negative (the backlog grows even after the fix). Instead: Use peak arrival rates and plan extra capacity or off-peak catch-up.
  • Mistake: Blaming the upstream team, or no numbers. Why it is wrong: Signals poor collaboration; impact unclear. Instead: Say you added a contract test together; give backlog, rates, drain time, messages lost.

๐Ÿ› Senior insight: trade-offs

The senior signal is quantitative reasoning plus data safety: you did the rate maths to separate capacity from failure, protected every message, and fixed the system (dead-letter policy, alerts on age, autoscaling with a cap, a contract with the producer).

How the numbers drove the decisions. Units matter: work in messages per second. Processing had dropped from [70/s] to [30/s] while arrivals were a normal [50/s]: a capacity drop, so scaling first would only have hidden the failing work and pushed more load at SQL. After the dead-letter fix, processing was [140/s] with [8] replicas; at the [50/s] daytime peak that drains [300,000] in about 300,000 / 90 โ‰ˆ [55] minutes, and faster in the evening when arrivals fall to [10/s]. That told me the backlog would clear the same day without more replicas than SQL could take.

Proactive monitoring for queues is what stops the next one: oldest-message age as the customer-facing SLO (for example, 95% of invoices processed within [5] minutes), processing rate versus arrival rate, DLQ count and growth, and failures per message type on a dashboard next to the consumer's dependencies.

Option When it fits Cost When not to
Scale consumers (KEDA) Healthy handler, more load Downstream pressure, cost Poison messages or slow downstream
Dead-letter non-transient errors Validation/deserialisation failures Needs DLQ handling process Transient errors
Optimise handler (batching, fewer round trips) Handler time dominates Engineering time Short-lived spike
Replay tool for DLQ After fix Must be idempotent Without root-cause fix
Contract tests / schema registry Cross-team payloads Coordination Single-team internal queue

๐Ÿ”— Follow-ups the interviewer may ask

  1. When: Candidate mentions the dead-letter queue or the same messages failing repeatedly. Why: Checks the technical drill-down on poison messages and DLQ handling.
    How to answer

    First I work out which problem I have:

    • Poison messages: a few messages always fail.
    • A failing dependency: every message fails.
    • Slow consumers: nothing fails, they just can't keep up.

    To tell them apart I use Service Bus metrics (incoming, completed, abandoned, dead-lettered), the DLQ's DeadLetterReason and DeadLetterErrorDescription, DeliveryCount, and traces grouped by exception.

    Poison messages loop when handlers catch and abandon forever, re-publish failures as new messages, or MaxDeliveryCount is huge. The fix: dead-letter permanent failures immediately, fix the handler or data, then resubmit from the DLQ in batches to an idempotent consumer. Scale consumers only up to the downstream's limit. To prevent it: alerts on oldest message age and DLQ count, plus a poison-message test. The trade-off: dead-lettering early keeps the queue flowing, but someone must own the DLQ.

  2. When: Candidate describes a daily backlog or throughput maths. Why: Checks capacity reasoning: scale consumers vs fix the handler.
    How to answer

    A queue only grows when the arrival rate is higher than the service rate, so I measure both: incoming versus completed messages per second. Service rate is consumers ร— concurrency รท handler time: 4 pods ร— 8 concurrent ร— (1 รท 0.4 s) is 80 messages/s, and if business hours bring 120/s the backlog grows by 40 every second until the evening. Little's law turns the backlog into a delay customers feel: 400,000 รท 80 โ‰ˆ 83 minutes. Before scaling I find where the 400 ms goes; often it's per-message database round trips or a slow partner call. Scaling out works until the bottleneck moves downstream or ordering caps it; fixing the handler (batching, concurrency, fewer calls) is usually cheaper. I separate poison messages, and alert on oldest-message age, not count.

  3. When: Candidate mentions KEDA, Kubernetes or idempotent processing. Why: Checks running a queue worker in production: shutdown, idempotency and scaling.
    How to answer

    Three things make a queue worker safe on Kubernetes or Container Apps. Graceful shutdown: on SIGTERM the host cancels stoppingToken. The worker stops receiving and finishes or abandons in-flight messages within HostOptions.ShutdownTimeout, which must be shorter than terminationGracePeriodSeconds. Idempotency: Service Bus peek-lock is at-least-once. A crash, a lock expiry or a shutdown redelivers the message, so the handler records the message id in a processed-messages table in the same transaction as the business change, and passes idempotency keys to the payment provider. Poison messages go to the dead-letter queue after MaxDeliveryCount. Scaling: a KEDA ScaledObject (or a Container Apps scale rule) on queue length adds pods as the backlog grows and scales to zero or a minimum when idle.

    The trade-off: more replicas clear backlogs faster but multiply concurrency against downstream systems and break ordering unless you use sessions.

๐Ÿ›  Real-world problems: how you handle them

Upstream date-format change floods the invoice queue with poison messages
Situation
[Invoice-processing worker] on [Azure Container Apps], reading [invoices] from Azure Service Bus, [~50] messages/s at peak, [4] replicas. Invoices feed [customer statements and payment reminders]. I was [the owning team's senior engineer].
Signals
Customer reports of invoices [hours] late; active message count [300,000]; oldest message [4 h]; DLQ count [8,000] and rising with reason `MaxDeliveryCountExceeded`; no alerts fired because the worker wasn't crashing; handler logs showing the same message ids failing repeatedly with `JsonException`.
Investigation
Throughput: arrivals [~50/s], processing [~30/s] versus normal [~70/s], so capacity had dropped. Ruled out SQL (DTU normal, handler SQL time unchanged) and the platform (replicas healthy). DLQ messages shared a new optional field with a non-ISO date format introduced by [the upstream team] on [date]; each bad message took ten attempts plus lock waits, consuming about half the capacity.
Resolution
Mitigation: shipped a handler change to dead-letter `JsonException`/validation failures immediately with reason `InvalidPayload`; throughput recovered to [~70/s] per [4] replicas; scaled to [8] replicas with `MaxConcurrentCalls` capped so Azure SQL stayed under [70%]. Real fix: tolerant date parsing for the new field, tested against a sample of [500] dead letters; replayed the DLQ in batches of [1,000] with a resubmit tool; handlers deduplicate on InvoiceId so replays were safe. Backlog drained in [~3] hours, nothing lost.
Prevention
Alerts on oldest-message age > [10 min] and DLQ count > [50]; KEDA scaling on queue length with a maximum replica cap; explicit dead-letter policy for non-transient errors; a consumer-driven contract test shared with [the upstream team]; a runbook and tool for DLQ inspection and replay.

How to tell it (STAR)

**S:** At [company], our [invoice worker] on Azure Service Bus fell [four hours] behind with a backlog of [300,000] messages, and customers noticed before we did. **T:** As [the senior engineer on the team] I needed to clear it without losing or duplicating invoices. **A:** I compared arrival and processing rates and saw our capacity had halved; the dead-letter queue showed why: an upstream format change made some messages fail ten times each. I shipped a change to dead-letter bad payloads immediately, scaled out within what the database could take, fixed the parsing, and replayed the dead letters safely because our handlers were idempotent. Then I added alerts on message age, capped autoscaling, and a contract test with [the upstream team]. **R:** The backlog drained in about [three] hours with [zero] messages lost, and we've had [no] backlog incidents in [N] months.

More in Production Incidents

Last updated 23 Nov 2026.

๐ŸŒ Sangam's Webring

โช Previous ๐Ÿ  Main Next โฉ
๐Ÿ’ฌ Chat with me