Covers recovering from a 2-million-message backlog after an outage: assessing message types and staleness, throttled draining sized to the downstream, prioritising new traffic, ordering and idempotency during catch-up, discarding or archiving expired messages, monitoring progress and communicating ETAs to stakeholders.
I don't just scale consumers to the maximum. The recovered system is fragile and a stampede will knock it over again. My plan:
The trade-off is speed of recovery against the risk of a second outage.
"The first thing I'd say is that the backlog is not the emergency any more; the messages are durable. The emergency is not causing a second outage. So I start by assessing. I peek a sample to see the mix of message types, check the oldest
EnqueuedTime, the TTL on the entity, and ask the business which messages lose their value with age. A four-hour-old 'send one-time code' or 'price quote valid for 15 minutes' should be archived, not sent. A payment confirmation must be processed, however late.For example, at [company] after [a four-hour outage of the core banking API], we had [about 2 million] messages on the [payments-status subscription] and [about 150] new per second still arriving. The recovered API could safely take [about 600] requests per second. So I [kept live traffic flowing through a new 'fast lane' subscription filtered on enqueued time, set the backlog consumer to start at 100 per second and stepped it up every 10 minutes while watching the API's p95 and error rate], and [paused the step-up twice when p95 went above 400 ms]. Handlers were already idempotent through an inbox table, which mattered because the outage had left [tens of thousands] of messages that had partly succeeded. Ordering was per account via sessions, so catch-up couldn't apply an old status over a newer one, and the projections also had version checks. [The backlog cleared in about 95 minutes with no second outage.]
The other half is communication. I compute the net drain rate (drained minus arriving), turn it into an ETA, and post it on the incident channel and status page every 30 minutes, with which customer-visible effects remain. The mistake I see is scaling consumers to 50 pods immediately: the recovered dependency falls over, the messages abandon, and the backlog grows again."
| Step | Action | Tooling |
|---|---|---|
| 1. Stabilise | Confirm the downstream is healthy; keep the consumer paused or at low concurrency | Health endpoints, dependency dashboards |
| 2. Assess | Message types, oldest age, TTL, stale categories | Service Bus Explorer peek, a small script grouping by Subject |
| 3. Decide | Which to process, which to archive, priority order | Business owner sign-off |
| 4. Protect live traffic | Fast lane: new subscription or entity for fresh messages | Subscription filters, producer config switch |
| 5. Drain | Stepwise concurrency, watch downstream | KEDA max replicas, MaxConcurrentCalls, dashboards |
| 6. Verify | Reconcile counts, sample outcomes | SQL reconciliation queries, Application Insights |
| 7. Communicate | ETA and impact every 30 minutes | Incident channel, status page |
| 8. Learn | Post-incident review | Drain-time objective, load tests |
backlog = 2,000,000
live arrival = 150/s
downstream = 600/s safe
net drain = 600 - 150 = 450/s
ETA = 2,000,000 / 450 = ~74 min (plus step-up time)
| Type | Example | Action |
|---|---|---|
| Must process, order matters | Account status changes | Sessions or version check, process all |
| Must process, order irrelevant | Invoice generation | Process at max safe rate |
| Superseded | Ten StockLevelChanged for one SKU |
Process (version check makes old ones no-ops) or collapse |
| Time-sensitive, now worthless | OTP, short-lived quotes | Archive to blob with reason, complete; notify users if needed |
During a 4-hour core-system outage, 2.1 million messages accumulated. A previous incident had tried a full-speed drain at 2,000 messages per second, which knocked the recovered API over within 6 minutes. The stepwise drain capped at 600 per second cleared the backlog in 95 minutes, kept live-message latency under 5 seconds via a fast-lane subscription, and archived 38,000 expired OTP messages instead of sending them.
Checks the candidate can lead a recovery that is safe for the system, correct for the data, and clear for the business.
Green flags
Red flags
During the outage, consumers abandon each message until MaxDeliveryCount, so some messages dead-letter, and some partly succeed (DB committed, external call timed out). After recovery you have three populations: the active backlog, the DLQ, and messages that half-happened.
outage starts outage ends
|------- 4 h --------|-------- recovery ---------|
active: grows 150/s 2.16 M peak drains at net 450/s
DLQ: grows (MaxDeliveryCount exceeded early on)
half-done: unknown must be idempotent on replay
The better pattern for the future: circuit-break and stop the processor when the dependency is down, so messages wait in the active queue instead of burning delivery counts.
Options in Service Bus:
sys.EnqueuedTimeUtc > '2026-11-21T04:00:00' (system properties are available in filters) and point a separate consumer at it; the old subscription keeps draining the backlog. Remember both subscriptions receive new messages, so the backlog consumer should skip messages that are newer than the cut-over.Kafka equivalent: a separate consumer group starting at the latest offset for live processing, with the original group catching up; both must be idempotent.
MaxConcurrentCalls.System.Threading.RateLimiting.TokenBucketRateLimiter) gives a precise cap regardless of pod count, if partitioned per pod.EnqueuedTime to a per-type max age; archive expired ones (blob storage with the body and reason) so you can audit or replay.Set a drain-time objective ("recover a 4-hour backlog within 2 hours"), load-test the catch-up path, add alerts on oldest message age, and make the circuit-breaker-pauses-consumer behaviour standard.
TokenBucketRateLimiter to the handler and confirm a steady rate regardless of concurrency.sys.EnqueuedTimeUtc and verify only new messages arrive there.ActiveMessageCount from ServiceBusAdministrationClient every minute.A throttled backlog drainer: a token bucket caps the rate, stale messages are archived, and progress feeds an ETA.
// BacklogHandler.cs
using System.Threading.RateLimiting;
using Azure.Messaging.ServiceBus;
using Azure.Storage.Blobs;
namespace Recovery;
public sealed record PaymentStatusChanged(Guid PaymentId, string Status, long Version);
public sealed class BacklogHandler(
IPaymentStatusStore store,
BlobContainerClient archive,
RateLimiter limiter, // shared per pod, e.g. 150/s x 4 pods = 600/s
TimeProvider time,
ILogger<BacklogHandler> logger)
{
private static readonly TimeSpan MaxAge = TimeSpan.FromHours(24);
public async Task HandleAsync(ProcessSessionMessageEventArgs args)
{
using RateLimitLease lease = await limiter.AcquireAsync(1, args.CancellationToken);
if (!lease.IsAcquired)
{
throw new InvalidOperationException("Rate limiter queue full"); // abandon; retry later
}
ServiceBusReceivedMessage msg = args.Message;
if (time.GetUtcNow() - msg.EnqueuedTime > MaxAge)
{
// Never silently drop: archive with the reason, then complete.
await archive.UploadBlobAsync($"expired/{msg.MessageId}.json", msg.Body, args.CancellationToken);
await args.CompleteMessageAsync(msg, args.CancellationToken);
return;
}
var evt = msg.Body.ToObjectFromJson<PaymentStatusChanged>()!;
// Idempotent and order-safe: applies only if newer than what we have.
bool applied = await store.ApplyIfNewerAsync(evt, args.CancellationToken);
if (!applied) logger.LogDebug("Stale or duplicate {MessageId}", msg.MessageId);
await args.CompleteMessageAsync(msg, args.CancellationToken);
}
}
public interface IPaymentStatusStore
{
Task<bool> ApplyIfNewerAsync(PaymentStatusChanged evt, CancellationToken ct);
}
// Program.cs (relevant registrations) and an ETA reporter
using System.Threading.RateLimiting;
using Azure.Messaging.ServiceBus.Administration;
builder.Services.AddSingleton<RateLimiter>(_ => new TokenBucketRateLimiter(new TokenBucketRateLimiterOptions
{
TokenLimit = 150,
TokensPerPeriod = 150, // raise stepwise from config during recovery
ReplenishmentPeriod = TimeSpan.FromSeconds(1),
QueueLimit = 500,
QueueProcessingOrder = QueueProcessingOrder.OldestFirst
}));
public static class EtaReporter
{
public static async Task ReportAsync(ServiceBusAdministrationClient admin, CancellationToken ct)
{
long previous = (await admin.GetSubscriptionRuntimePropertiesAsync("payments", "status", ct)).Value.ActiveMessageCount;
while (!ct.IsCancellationRequested)
{
await Task.Delay(TimeSpan.FromMinutes(1), ct);
long now = (await admin.GetSubscriptionRuntimePropertiesAsync("payments", "status", ct)).Value.ActiveMessageCount;
double netPerSecond = (previous - now) / 60.0; // drained minus arriving
string eta = netPerSecond > 0 ? TimeSpan.FromSeconds(now / netPerSecond).ToString(@"hh\:mm") : "not draining";
Console.WriteLine($"backlog {now:N0}, net {netPerSecond:F0}/s, ETA {eta}");
previous = now;
}
}
}
MaxDeliveryCount and flood the DLQ. Instead: pause the processor when the circuit breaker opens.Backlog recovery is capacity planning under pressure. The senior instinct is to protect the recovering system and the live customers first, and treat the backlog as durable work that can wait an hour. The decisions that need business input (which messages are worthless after four hours) should be in the runbook before the incident, not invented at 2 am.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
| Stepwise drain on one entity | Simple, order mostly irrelevant | Live traffic waits behind backlog | Customer-facing latency matters |
| Fast lane + background drain | Live traffic must stay fast | Two consumers, cut-over logic | Strict global per-key order across lanes (use version checks) |
| Archive stale + process rest | Time-sensitive message types | Business sign-off, user comms | Financial or legal records |
| Replay from source of truth instead | Backlog is derivable (projections) | Rebuild job | Messages carry unique intent (commands) |
Measure: net drain rate, downstream saturation, live-message latency and the count archived per reason. Set a drain-time objective and load-test it each quarter.
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.
Global ordering means one consumer processing one message at a time, which kills throughput, so real systems guarantee order per key: per order, customer or account.
SessionId; a ServiceBusSessionProcessor locks a session to one receiver and processes it in order, while different sessions run in parallel.MessageGroupId works like a session.Order breaks with competing consumers, retries, dead-lettering and rebalances. Better still, design so order doesn't matter: version numbers with "ignore older", events that carry full state, or commutative updates. The trade-off is that per-key order lets one stuck message block every later message for that key.
Unrelated requests failing means the slow API exhausted a shared resource: usually database connections held while waiting, sockets, or thread-pool threads (from sync-over-async).
Diagnose: Application Insights dependency durations, then dotnet-counters for the thread pool, SqlClient pool and HTTP connections, then dotnet-dump to see what requests are waiting on. Look for the 100 s HttpClient default timeout multiplied by retries.
Mitigate: a feature flag that switches to a fallback (flat-rate shipping).
Fix:
The trade-off is a slightly degraded feature against a whole service going down.
How to tell it (STAR)
**S:** After a [4-hour] core banking outage [at company], we had [about 2.1 million] payment messages queued and new ones still arriving. **T:** As [incident lead for the payments platform], I had to recover without knocking the core system over again and keep stakeholders informed. **A:** I sampled the backlog, agreed with product which messages were stale, set up a fast lane for new traffic, and drained the backlog with a rate limiter, stepping up every 10 minutes while watching the core API's latency. I archived expired OTPs instead of sending them and posted ETAs every 30 minutes. **R:** The backlog cleared in [95] minutes with no second outage, live payments stayed under [5 seconds] throughout, and pausing consumers on circuit-open became our standard.
Last updated 23 Nov 2026.