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.
First I work out which problem I have:
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.
"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,DeliveryCountand the body.MaxDeliveryCountExceededwith aJsonExceptionin the logs tells a very different story fromMaxDeliveryCountExceededwith SQL timeouts.For example, at [company] we had [a new producer version that sent
amountas a string]. The consumer [caught every exception and calledAbandonMessageAsync], 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."
| 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 |
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
$DeadLetterQueue, clones and sends, then completes the DLQ copy).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.
Checks the candidate can diagnose a messaging incident methodically and fix it without losing or duplicating data.
Green flags
Red flags
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.
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;DeadLetterMessageAsync with your reason and description;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.
client.CreateReceiver("orders", new ServiceBusReceiverOptions { SubQueue = SubQueue.DeadLetter }) and PeekMessagesAsync.DeadLetterReason, DeadLetterErrorDescription, DeliveryCount, EnqueuedTime, ApplicationProperties (your correlation id, schema version), and the original MessageId.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.
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.
ActiveMessages, DeadletteredMessages, AbandonedMessages (via diagnostic logs), IncomingMessages vs CompletedMessages.EnqueuedTime of the first peeked message) rather than raw depth, which is noisy at peak.messaging.destination.name.JsonException immediately and compare good-message latency under 1,000 bad messages.DeadLetterReason, and prints counts.DeadletteredMessages > 0 for a test namespace.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;
}
}
MaxDeliveryCount times, occupying slots and delaying good messages. Instead: dead-letter permanent failures immediately.DeliveryCount resets and the message loops forever. Instead: use abandon, scheduled resend with a cap, or dead-letter.MessageIds. Why it is wrong: consumer dedup can't recognise messages that partly succeeded. Instead: preserve the original id.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.
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".
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.
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.
A circuit breaker stops calling a dependency that is clearly failing, so you fail fast instead of wasting threads and sockets on timeouts.
BrokenCircuitException for the break duration.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.
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.
Last updated 23 Nov 2026.