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

📚 Interview question

Your Service Bus queue's active message count keeps climbing, the dead-letter queue has thousands of messages, and logs show the same few messages failing over and over. How do you diagnose what is going on, deal with the poison messages and the backlog, and fix it so it doesn't happen again?

Covers diagnosing a growing Service Bus backlog with poison messages: reading DLQ reasons and properties, distinguishing poison messages from a failing dependency, settlement mistakes that cause loops, safe DLQ resubmission, scaling consumers against the downstream limit, and alerting and testing to prevent recurrence.

Senior Debugging Advanced azure-service-bus dead-letter-queue debugging distributed-systems messaging poison-messages

🎯 Key points

  • First split: poison messages (a few always fail) vs failing dependency (everything fails) vs slow consumers (no failures, just lag)
  • Read DLQ messages: DeadLetterReason, DeadLetterErrorDescription, DeliveryCount, EnqueuedTime, body (Service Bus Explorer, peek)
  • Find the source: match the first bad EnqueuedTime to deployments and talk to the producing team before changing the consumer
  • Loops come from catch-and-abandon forever, MaxDeliveryCount too high, or re-publishing failed messages as new ones
  • Dead-letter permanent failures immediately; let transient ones exhaust MaxDeliveryCount
  • Fix the handler or data, then resubmit from the DLQ in controlled batches with idempotent consumers, following a written runbook with an owner
  • Scale consumers only to the downstream's capacity: check Azure SQL CPU/DTU, waits and throttling (40501) first
  • Alerts: oldest message age, DLQ count > 0 per reason, DeliveryCount > 1 rate; contract tests and a poison-message test in CI

⏱ 30-second 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.

🗣 Full answer (senior)

How I would answer this in an interview

"I start by classifying, because the three causes look similar on a queue-depth graph but need opposite fixes. In the Service Bus metrics I compare incoming, completed, abandoned and dead-lettered messages. If completed has dropped to near zero and abandoned is huge, everything is failing, which usually means a dependency: the database, an API, a credential. If completed is steady and only a few message ids appear repeatedly in errors, those are poison messages. If there are no errors and completed is just lower than incoming, the consumers are too slow or too few. Then I peek the dead-letter queue with Service Bus Explorer in the portal or a small script, and read DeadLetterReason, DeadLetterErrorDescription, DeliveryCount and the body. MaxDeliveryCountExceeded with a JsonException in the logs tells a very different story from MaxDeliveryCountExceeded with SQL timeouts.

For example, at [company] we had [a new producer version that sent amount as a string]. The consumer [caught every exception and called AbandonMessageAsync], so each bad message cycled ten times with a 30-second lock, the processor slots were full of retries, and the backlog grew to [about 400,000] while the DLQ filled with thousands. I [changed the handler to dead-letter deserialisation and validation failures immediately], which unblocked the good traffic within minutes, [fixed the contract with the producer team], then resubmitted the DLQ in batches of [1,000] while watching error rates. [The backlog cleared in about 40 minutes.]

The prevention is boring but works: alerts on oldest-message age and DLQ count above zero, a test that sends a malformed message in CI and asserts it is dead-lettered once, a contract test between producer and consumer, and a runbook for resubmission. The mistake I see is scaling consumers first: if the database is the bottleneck, ten times the consumers just means ten times the timeouts."


Triage table

Symptom Likely cause First action
Few ids fail repeatedly, others complete Poison messages (schema, data, bug) Read DLQ reason and body; dead-letter permanent failures immediately
Almost everything fails Dependency down, credential expired, config Check dependency health, circuit-break, pause consumers
No errors, backlog grows Throughput too low Measure handler time; scale to downstream limit
Same message reappears with new MessageId Handler re-publishes on failure Remove re-publish; use abandon and DLQ
MessageLockLost errors Handlers slower than lock, prefetch too high Lock renewal, smaller prefetch

Diagnosis flow

queue depth rising
   |
   +-- dead-lettered rate > 0? --yes--> peek DLQ: reason, description, body
   |                                     |-- JsonException / validation -> poison
   |                                     |-- SqlException / 503 -> dependency
   +-- abandoned >> completed? --yes--> dependency or handler bug for all messages
   +-- no errors?  -------------------> throughput: handler p95, concurrency, DB DTU

Resubmitting safely

  1. Fix the cause first (deploy the handler fix or correct the data).
  2. Confirm consumers are idempotent (inbox or version check), since some DLQ messages may have partly succeeded.
  3. Resubmit in batches (Service Bus Explorer re-send, or a tool that receives from $DeadLetterQueue, clones and sends, then completes the DLQ copy).
  4. Watch error and DLQ rates per batch; stop at the first rise.
  5. For messages that can never succeed, archive the body to blob storage with the reason, then complete them; don't leave them to expire silently.

Production example

A schema change from one producer sent 6,200 malformed messages in an hour. With catch-and-abandon handlers and MaxDeliveryCount = 10, about 62,000 failed deliveries blocked processor slots and good-message latency went from 2 seconds to 25 minutes. Dead-lettering deserialisation errors on first sight restored normal latency in under 5 minutes.

🔍 What the interviewer is checking

Checks the candidate can diagnose a messaging incident methodically and fix it without losing or duplicating data.

Green flags

  • Separates poison messages, dependency failure and throughput problems
  • Reads DLQ reasons and properties rather than guessing
  • Knows the catch-and-abandon and re-publish loops
  • Fixes the cause before resubmitting, in batches, with idempotent consumers
  • Prevents recurrence with age-based alerts, tests and a runbook

Red flags

  • Purges the DLQ to make the alert go away
  • Scales consumers without checking the downstream
  • Doesn't know messages in the DLQ never expire

📚 Learn in depth

1. How a poison message loops

Broker                       Consumer
  |--m (DeliveryCount=1)----->| JsonException -> catch -> Abandon
  |--m (DeliveryCount=2)----->| JsonException -> catch -> Abandon
  ...                          (each cycle holds a slot; lock may run 30 s if handler hangs)
  |--m (DeliveryCount=10)---->| fail
  |-- move to $DeadLetterQueue (MaxDeliveryCountExceeded)

The worse versions: re-publishing a failed message as a new message resets DeliveryCount to 1, so it loops forever; setting MaxDeliveryCount = 2000 'for resilience' has the same effect.

2. The dead-letter queue

Every queue and subscription has a sub-queue at <entity>/$DeadLetterQueue. Messages land there by:

  • MaxDeliveryCountExceeded (automatic);
  • TTLExpiredException if dead-lettering on expiry is enabled;
  • Explicit DeadLetterMessageAsync with your reason and description;
  • Subscription filter evaluation exceptions, or session-id missing on a session entity.

DLQ messages never expire on their own and count towards the entity's size quota, so a neglected DLQ can eventually stop the entity accepting messages.

3. Reading it

  • Portal: Service Bus Explorer, select the DLQ, peek, view properties.
  • Code: client.CreateReceiver("orders", new ServiceBusReceiverOptions { SubQueue = SubQueue.DeadLetter }) and PeekMessagesAsync.
  • Key fields: DeadLetterReason, DeadLetterErrorDescription, DeliveryCount, EnqueuedTime, ApplicationProperties (your correlation id, schema version), and the original MessageId.

4. Poison versus transient

Classify exceptions in the handler:

Exception Category Action
JsonException, ValidationException, unknown message type Permanent Dead-letter now
SqlException 1205 (deadlock), -2 (timeout), 40501/40613 (Azure SQL throttling/unavailable) Transient Throw: redelivery
HttpRequestException 5xx/429 Transient Throw, maybe with delay (scheduled resend or ServiceBusRetryOptions)
Business rule that will never pass Permanent Dead-letter, or publish a rejection event

For transient failures with long outages, ten quick redeliveries burn out in a few minutes. Options: circuit-break and stop the processor while the dependency is down; or schedule a resend with backoff (ScheduledEnqueueTime) and complete the original, accepting a new MessageId only if your dedup key is a business id.

5. Draining the backlog

Throughput = consumers x concurrency / handler time, capped by the downstream. Check Azure SQL avg_cpu_percent and sys.dm_exec_requests waits before scaling. KEDA can scale pods on queue length, but set a maxReplicaCount that respects the database. Prioritise: if new traffic matters more than the backlog, consider routing new messages to a fresh entity while the old one drains.

6. Observability that would have caught it

  • Azure Monitor metrics: ActiveMessages, DeadletteredMessages, AbandonedMessages (via diagnostic logs), IncomingMessages vs CompletedMessages.
  • Alert on oldest message age (computed from EnqueuedTime of the first peeked message) rather than raw depth, which is noisy at peak.
  • Application Insights: failures grouped by exception type and messaging.destination.name.

Try it yourself

  1. Build a consumer that catches and abandons; send a malformed message and count deliveries until it dead-letters.
  2. Change it to dead-letter JsonException immediately and compare good-message latency under 1,000 bad messages.
  3. Write a small CLI that peeks the DLQ, groups by DeadLetterReason, and prints counts.
  4. Implement a batch resubmitter that clones DLQ messages to the main entity and completes the DLQ copy; run it twice and check idempotency.
  5. Create an Azure Monitor alert on DeadletteredMessages > 0 for a test namespace.

💻 Code

Classifying failures in the handler, and a small, idempotent DLQ resubmitter.

// Handler: dead-letter permanent failures at once; let transient ones redeliver.
using System.ComponentModel.DataAnnotations;
using System.Text.Json;
using Azure.Messaging.ServiceBus;

namespace Billing;

public sealed record ChargeRequested(Guid ChargeId, string CustomerId, decimal Amount);

public sealed class ChargeMessageHandler(IChargeService charges, ILogger<ChargeMessageHandler> logger)
{
    public async Task HandleAsync(ProcessMessageEventArgs args)
    {
        ChargeRequested request;
        try
        {
            request = args.Message.Body.ToObjectFromJson<ChargeRequested>()
                      ?? throw new ValidationException("Empty body");
            if (request.Amount <= 0) throw new ValidationException($"Invalid amount {request.Amount}");
        }
        catch (Exception ex) when (ex is JsonException or ValidationException)
        {
            logger.LogWarning(ex, "Poison message {MessageId}", args.Message.MessageId);
            await args.DeadLetterMessageAsync(args.Message,
                deadLetterReason: ex.GetType().Name,
                deadLetterErrorDescription: ex.Message[..Math.Min(ex.Message.Length, 1024)],
                cancellationToken: args.CancellationToken);
            return;
        }

        // Transient exceptions propagate: abandon, DeliveryCount++, DLQ after MaxDeliveryCount.
        await charges.ChargeAsync(request, idempotencyKey: request.ChargeId.ToString(), args.CancellationToken);
        await args.CompleteMessageAsync(args.Message, args.CancellationToken);
    }
}

public interface IChargeService
{
    Task ChargeAsync(ChargeRequested request, string idempotencyKey, CancellationToken ct);
}
// DlqResubmitter.cs: run after the fix is deployed. Keeps MessageId so consumer dedup still works.
using Azure.Messaging.ServiceBus;

namespace Ops;

public sealed class DlqResubmitter(ServiceBusClient client)
{
    public async Task<int> ResubmitAsync(string queue, int batchSize, string? onlyReason, CancellationToken ct)
    {
        await using ServiceBusReceiver dlq = client.CreateReceiver(queue,
            new ServiceBusReceiverOptions { SubQueue = SubQueue.DeadLetter });
        await using ServiceBusSender sender = client.CreateSender(queue);

        IReadOnlyList<ServiceBusReceivedMessage> batch =
            await dlq.ReceiveMessagesAsync(batchSize, TimeSpan.FromSeconds(5), ct);
        int resent = 0;
        foreach (ServiceBusReceivedMessage msg in batch)
        {
            if (onlyReason is not null && msg.DeadLetterReason != onlyReason)
            {
                await dlq.AbandonMessageAsync(msg, cancellationToken: ct);   // leave others in the DLQ
                continue;
            }
            var clone = new ServiceBusMessage(msg);                       // copies body, MessageId, properties
            clone.ApplicationProperties["ResubmittedFromDlq"] = DateTimeOffset.UtcNow.ToString("O");
            await sender.SendMessageAsync(clone, ct);
            await dlq.CompleteMessageAsync(msg, ct);                       // send first, then complete: at-least-once
            resent++;
        }
        return resent;
    }
}

⚠ Common mistakes

  • Mistake: Catching every exception and abandoning. Why it is wrong: permanent failures cycle up to MaxDeliveryCount times, occupying slots and delaying good messages. Instead: dead-letter permanent failures immediately.
  • Mistake: Re-publishing failed messages as new messages. Why it is wrong: DeliveryCount resets and the message loops forever. Instead: use abandon, scheduled resend with a cap, or dead-letter.
  • Mistake: Scaling consumers before checking the downstream. Why it is wrong: more consumers against a saturated database means more timeouts and more abandons. Instead: measure database CPU and waits, then scale to its limit.
  • Mistake: Ignoring the DLQ. Why it is wrong: it never expires, hides lost business data and counts against the entity's size quota. Instead: alert on DLQ count > 0 and give it an owner and a runbook.
  • Mistake: Bulk resubmitting the whole DLQ before fixing the cause. Why it is wrong: it all fails again and doubles the load. Instead: fix, then resubmit in small batches while watching error rates.
  • Mistake: Resubmitting with new MessageIds. Why it is wrong: consumer dedup can't recognise messages that partly succeeded. Instead: preserve the original id.
  • Mistake: Alerting on raw queue depth. Why it is wrong: it fires at every peak and is ignored. Instead: alert on oldest message age and DLQ growth.

🏛 Senior insight: trade-offs

Most backlog incidents are not the broker's fault: they are settlement policy bugs, a dependency limit or a contract break. A senior engineer makes the failure policy explicit per message type (which exceptions are permanent, how many attempts, who owns the DLQ, how resubmission works) and writes it down before the incident.

Option When it fits Cost When not to
Dead-letter immediately Schema or validation errors, unknown types Needs DLQ ownership and tooling Transient faults
Redeliver up to MaxDeliveryCount (3-10) Short transient faults Quick bursts of retries Outages longer than a few minutes
Stop processor on circuit open Dependency outage Backlog grows (that is fine, it is durable) Only some message types affected; use separate consumers
Scheduled resend with backoff Rate limits, slow recovery New message id; need business-key dedup Strict ordering per session

Measure: oldest message age, DLQ rate per reason, DeliveryCount > 1 share, and time to drain. A good target is a written drain-time objective, such as backlog cleared within 1 hour of recovery.

🔗 Follow-ups the interviewer may ask

  1. When: Candidate resubmits DLQ messages that may have partly succeeded Why: Checks they understand duplicates and effectively-once processing
    How to answer

    At-most-once means settle first, then process: a crash loses the message. At-least-once means process first, then settle: a crash or lock expiry redelivers, so you get duplicates. Almost every real system chooses at-least-once.

    Exactly-once delivery is a myth because the acknowledgement itself can be lost after the work is done; the broker can't tell "not processed" from "processed but ack lost".

    • Kafka transactions give exactly-once only for read-process-write within Kafka.
    • Service Bus duplicate detection and SQS FIFO dedup only drop producer resends within a window.

    What you build is effectively-once processing: at-least-once delivery plus an idempotent consumer, using a natural idempotent write or an inbox row committed in the same transaction. The trade-off is extra storage and a unique-key check per message.

  2. When: Candidate identifies a producer schema change as the root cause Why: Checks they know how to version message schemas safely
    How to answer

    Make changes additive where possible, so one schema serves both. When a breaking change is unavoidable, give the event a version (in the type name or a schemaVersion field), have consumers accept both (or upcast old to new on read) before producers switch, and keep old-version support until no old messages remain in queues, dead-letter queues or replayable logs. A schema registry with BACKWARD or FULL compatibility can enforce this at publish time.

  3. When: Candidate suggests pausing consumers while a dependency is down Why: Checks they can apply a circuit breaker to a message consumer
    How to answer

    A circuit breaker stops calling a dependency that is clearly failing, so you fail fast instead of wasting threads and sockets on timeouts.

    • Closed: calls flow and outcomes are sampled.
    • Open: when failures pass a threshold, calls are rejected straight away with BrokenCircuitException for the break duration.
    • Half-open: a trial call decides whether to close the circuit or open it again.

    In Polly v8 it opens when the failure ratio (default 10%) is exceeded over a 30 s sampling window with at least 100 calls, and it breaks for 5 s. AddStandardResilienceHandler puts it inside the retry (each attempt counts, and an open circuit stops retries) and outside the 10 s attempt timeout (a hung call counts as a failure).

    Pair it with a fallback and alert when it opens. The trade-off is protection and fast failure against rejecting some calls that would have succeeded.

🛠 Real-world problems: how you handle them

A producer schema change floods the DLQ and stalls a billing queue
Situation
A billing consumer on [AKS, Australia East] processes `ChargeRequested` from a Service Bus queue, normally [50] messages per second with a 2-second end-to-end latency. A [checkout team] deployed a change sending `amount` as a string.
Signals
Azure Monitor alert: oldest message age > 15 minutes; `ActiveMessages` climbing past [400,000]; `DeadletteredMessages` in the thousands; Application Insights failures dominated by `JsonException`; completed rate down 80% though the database looked healthy.
Investigation
Compared completed vs abandoned metrics (abandoned dominated); peeked the DLQ with Service Bus Explorer: reason `MaxDeliveryCountExceeded`, bodies with `"amount":"129.95"`; reviewed the handler: `catch (Exception) { await AbandonMessageAsync(...) }`; matched the first bad message's `EnqueuedTime` to the checkout deployment.
Resolution
Immediate: hotfix to dead-letter `JsonException` on first delivery, which freed processor slots and restored good-message flow within 5 minutes; checkout team rolled back. Then: added a tolerant converter for the string form, deployed, and resubmitted the DLQ in batches of [1,000] while watching error rates; backlog cleared in about [40] minutes.
Prevention
Consumer-driven contract test (PactNet message pact) in the checkout pipeline; CI test sending a malformed message and asserting a single dead-letter; alert on DLQ count > 0 per reason; DLQ resubmission runbook with an owner.

How to tell it (STAR)

**S:** One afternoon our billing queue [at company] backed up to [400,000] messages and charges were delayed by [25] minutes. **T:** As [on-call engineer], I had to restore billing and recover the failed messages safely. **A:** The metrics showed abandons dominating while the database was fine, and the DLQ showed `amount` arriving as a string from a checkout release. Our handler abandoned every exception, so bad messages looped ten times each. I shipped a hotfix to dead-letter deserialisation errors immediately, got checkout to roll back, then added a tolerant converter and resubmitted the DLQ in batches. **R:** Normal latency was back in [5] minutes, the backlog cleared in [about 40], no charge was lost or duplicated, and we added a message contract test so the change would have failed in CI.

↩ Usually asked after

More in Messaging

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me