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

📚 Interview question

After a four-hour outage of a downstream system, your Service Bus subscription has a backlog of about 2 million messages, and new messages are still arriving. Walk me through your recovery plan: how you drain it without overwhelming the recovered system, what you do about ordering, duplicates and stale messages, and how you keep the business informed.

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.

Senior RealWorldScenario Advanced azure-service-bus backlog-recovery distributed-systems idempotency incident-response messaging

🎯 Key points

  • Assess first with Service Bus Explorer and ServiceBusAdministrationClient: message types, oldest age, TTL, which messages are now stale or superseded
  • Drain rate = downstream's safe capacity minus live traffic; raise concurrency stepwise while watching its CPU, latency and errors
  • Watch it live: Azure Monitor metrics (ActiveMessages, Completed vs Incoming, DeadletteredMessages, throttled requests) and Application Insights dependency p95 and failure rate
  • Protect new traffic: separate fast lane or priority entity so fresh orders aren't stuck behind four-hour-old ones
  • Ordering: sessions keep per-key order; otherwise version checks so old messages don't overwrite newer state
  • Duplicates are likely after an outage: idempotent handlers (inbox, upserts, provider idempotency keys)
  • Stale messages: archive (e.g. 'send OTP' after 4 hours) based on EnqueuedTime and business rules, never silently drop
  • Publish an ETA from net drain rate on a fixed cadence; afterwards make consumers pause when the circuit breaker opens and set a drain-time objective

⏱ 30-second answer

I don't just scale consumers to the maximum. The recovered system is fragile and a stampede will knock it over again. My plan:

  1. Assess: which message types are in the backlog, how old the oldest is, and which are now stale (a four-hour-old "send login code") or superseded.
  2. Drain at a controlled rate: the downstream's safe capacity minus live traffic, raising concurrency stepwise while watching its CPU, latency and error rate.
  3. Protect new traffic with a separate fast lane, so fresh orders aren't stuck behind old ones.
  4. Correctness: per-key order through sessions or version checks, idempotent handlers for the duplicates an outage creates, and stale messages archived, not silently dropped.
  5. Communicate an ETA from the net drain rate, updated on a fixed cadence.

The trade-off is speed of recovery against the risk of a second outage.

🗣 Full answer (senior)

How I would answer this in an interview

"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."


Recovery runbook

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

Drain maths

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)

What to do with each message type

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

Production example

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.

🔍 What the interviewer is checking

Checks the candidate can lead a recovery that is safe for the system, correct for the data, and clear for the business.

Green flags

  • Protects the recovering dependency with a controlled drain rate
  • Separates live traffic from backlog
  • Addresses ordering, duplicates and staleness explicitly
  • Communicates ETAs from real numbers
  • Plans prevention: pause on circuit open, drain-time objective

Red flags

  • "Scale to 50 pods and let it rip"
  • Purges messages to make the graph look better
  • Ignores duplicates or out-of-order application

📚 Learn in depth

1. Why outages create backlogs and duplicates

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.

2. Fast lane for live traffic

Options in Service Bus:

  • Create a new subscription with a SQL filter like 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.
  • Or switch the producer to a new topic and drain the old one separately.

Kafka equivalent: a separate consumer group starting at the latest offset for live processing, with the original group catching up; both must be idempotent.

3. Controlling the drain rate

  • Concurrency is the throttle: pods x MaxConcurrentCalls.
  • A rate limiter in the handler (System.Threading.RateLimiting.TokenBucketRateLimiter) gives a precise cap regardless of pod count, if partitioned per pod.
  • Watch the downstream's saturation signals, not your own: DB CPU and waits, API p95, 429s. Back off at the first sign of degradation (AIMD: add slowly, cut quickly).

4. Correctness during catch-up

  • Ordering: sessions preserve per-key order even under high concurrency. Without sessions, version-checked updates make old messages no-ops.
  • Idempotency: inbox table, upserts, provider idempotency keys. After an outage, assume every message may have partially succeeded.
  • Staleness: compare EnqueuedTime to a per-type max age; archive expired ones (blob storage with the body and reason) so you can audit or replay.
  • DLQ: once the backlog is healthy, resubmit dead-lettered messages in batches after confirming the cause was the outage.

5. Communication

  • One incident commander, one channel. Update on a fixed cadence (for example every 30 minutes) even if nothing changed.
  • State: what is affected for customers, current backlog and net drain rate, ETA, decisions taken (for example "expired login codes will not be sent; users can request a new one").
  • If personal information was affected (for example messages delivered to the wrong place), assess the Notifiable Data Breaches scheme obligations; a delay alone usually isn't a breach.

6. After the incident

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.

Try it yourself

  1. Fill an emulator queue with 200,000 messages; drain with concurrency 4, 16 and 64 against a local SQL Server and chart its CPU.
  2. Add a TokenBucketRateLimiter to the handler and confirm a steady rate regardless of concurrency.
  3. Create a subscription filter on sys.EnqueuedTimeUtc and verify only new messages arrive there.
  4. Add a max-age rule per message type and archive expired messages to a local folder.
  5. Write the ETA calculation as a small script reading ActiveMessageCount from ServiceBusAdministrationClient every minute.

💻 Code

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;
        }
    }
}

⚠ Common mistakes

  • Mistake: Scaling consumers to the maximum the moment the dependency recovers. Why it is wrong: the thundering herd knocks the dependency over again and the backlog grows. Instead: drain stepwise against its measured capacity.
  • Mistake: Letting new traffic queue behind the backlog. Why it is wrong: every new customer action waits hours, extending the impact. Instead: give live traffic a fast lane.
  • Mistake: Processing time-sensitive messages hours late. Why it is wrong: customers get expired codes and wrong prices. Instead: archive messages past their useful age with a reason and tell users.
  • Mistake: Silently purging the backlog. Why it is wrong: business data is lost with no audit trail. Instead: archive anything you don't process.
  • Mistake: Assuming no duplicates because the consumer was down. Why it is wrong: partial successes and abandons during the outage cause redelivery. Instead: rely on idempotent handlers and reconcile afterwards.
  • Mistake: Not stopping consumers during the outage. Why it is wrong: messages burn through MaxDeliveryCount and flood the DLQ. Instead: pause the processor when the circuit breaker opens.
  • Mistake: Giving vague updates. Why it is wrong: stakeholders can't plan and escalate. Instead: publish backlog, net drain rate and ETA on a fixed cadence.

🏛 Senior insight: trade-offs

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.

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions the dead-letter queue filling during the outage Why: Checks they can diagnose and resubmit poison or dead-lettered messages safely
    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 mentions sessions or version checks during catch-up Why: Checks depth on message ordering
    How to answer

    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.

    • Service Bus: set SessionId; a ServiceBusSessionProcessor locks a session to one receiver and processes it in order, while different sessions run in parallel.
    • Kafka: the message key picks the partition, and order holds within it. Adding partitions remaps keys.
    • SQS FIFO: the 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.

  3. When: Candidate says consumers should pause while the dependency is down Why: Checks they can apply circuit breakers and bulkheads to prevent cascades
    How to answer

    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:

    • Timeouts: 2 s per attempt, 5 s total.
    • One jittered retry, outside a circuit breaker tuned to the traffic.
    • A bulkhead: a concurrency limit on the shipping client.
    • No external calls inside DB transactions.
    • Liveness checks that don't include the third party.

    The trade-off is a slightly degraded feature against a whole service going down.

🛠 Real-world problems: how you handle them

Draining 2 million payment-status messages after a core banking outage
Situation
A payments platform for an [Australian lender] in [Azure Australia East] consumes payment-status events from a Service Bus topic and calls a core banking API. The core system was down for [4] hours; [about 2.1 million] messages accumulated while [150] per second kept arriving.
Signals
Oldest message age alert at 15 minutes and rising; DLQ growth early in the outage; customer-facing payment status stuck at 'processing'; core API recovering with reduced capacity of [about 600] requests per second.
Investigation
Peeked samples and grouped by `Subject`: [92%] status updates, [6%] statement requests, [2%] OTP notifications; checked oldest `EnqueuedTime` and entity TTL; confirmed with the core banking team their safe request rate; reviewed handler idempotency (inbox table present) and ordering (sessions per account).
Resolution
Created a fast-lane subscription filtered on enqueued time for live traffic; drained the backlog with a token-bucket limit starting at [100/s], stepping up every 10 minutes to [450/s] while the core API p95 stayed under 400 ms; archived [38,000] expired OTPs to blob storage; resubmitted the DLQ afterwards; reconciled payment statuses with the core system.
Prevention
Consumers now stop processing when the circuit breaker opens; drain-time objective of 2 hours for a 4-hour backlog, load-tested quarterly; per-type max-age rules in the runbook signed off by product; alert on oldest message age per subscription.

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.

↩ Usually asked after

More in Messaging

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me