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

📚 Interview question

Every weekday your invoice-processing queue on Azure Service Bus starts growing at about 9 am, peaks around 2 pm with a backlog of 400,000 messages, and only drains overnight. Customers complain that invoices take hours to appear. Nothing is failing outright. How do you work out why with throughput maths, decide between scaling consumers and fixing the handler, handle any poison messages hiding in the backlog, and set this up so you'd see it coming?

A production scenario for a queue backlog that grows every business day: arrival rate versus service rate and Little's law, measuring handler throughput, the limits of scaling out (downstream bottlenecks, ordering, locks), fixing the handler with batching and concurrency, poison messages, KEDA autoscaling and backlog-age alerts.

Senior RealWorldScenario Advanced azure-service-bus backlog keda messaging production throughput

🎯 Key points

  • A backlog grows whenever arrival rate exceeds total service rate; measure both (incoming vs completed messages per second) and chart them with handler p95 over weeks
  • Service rate = consumers × concurrency per consumer ÷ handler time; e.g. 4 pods × 8 × (1 / 0.4 s) = 80 msg/s against 120 msg/s arriving
  • Little's law: wait time ≈ backlog ÷ throughput, so 400,000 messages at 80/s is about 83 minutes and growing
  • Find where handler time goes before scaling: traces per message show the slow dependency or the per-message database round trips
  • Scaling out only helps until the bottleneck moves downstream (database DTU, a partner's rate limit) or ordering (sessions) caps parallelism
  • Fix the handler: batch database writes, tune MaxConcurrentCalls and PrefetchCount to handler time and lock duration, remove per-message lookups, make it idempotent
  • Poison messages: dead-letter non-transient failures on the first attempt; retry transient ones with backoff, then abandon
  • Prevent: KEDA azure-servicebus scaler on messageCount per replica with a max from the downstream capacity test, alert on oldest-message age, capacity test at peak

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

🗣 Full answer (senior)

How I would answer this in an interview

"A backlog that grows every business day and drains every night isn't an incident, it's a capacity problem: during the day messages arrive faster than we process them. So I start with two numbers from Service Bus metrics: incoming messages per second and completed messages per second. If incoming peaks at 120 a second and completed is flat at 80, that flat line is our ceiling, and the queue grows by 40 a second, which is about 144,000 an hour. Little's law turns the backlog into what customers feel: 400,000 messages at 80 a second is over 80 minutes of waiting, which matches 'invoices take hours'.

For example, at [company] we had [an invoice pipeline] like this. Our ceiling was four pods, each with MaxConcurrentCalls of 8, and a handler that took about 400 ms: 4 × 8 ÷ 0.4 = 80 per second. The tempting fix was to triple the pods. Before doing that, I looked at traces for single messages: 300 of the 400 ms was five separate database round trips to look up the customer, tax rules and product data, and then a single-row insert. Scaling out would have tripled the load on an Azure SQL database that was already at [70%]. Instead we cached the reference data, batched the inserts, and raised concurrency carefully. The handler dropped to [90 ms], the same four pods handled [over 300] a second, and the backlog stopped forming at all. We also found [about 2,000] poison messages that were retried ten times each before dead-lettering, burning capacity every morning.

The mistake I see is alerting on queue length. A queue of 10,000 might be fine for a batch job and terrible for payments. Alert on the age of the oldest message against the business promise, and scale on queue length with KEDA so capacity follows the arrival rate."


The arithmetic

Quantity Value How
Arrival rate at peak (λ) 120 msg/s Service Bus IncomingMessages per second
Handler time (S) 0.4 s Trace duration per message
Parallelism (consumers × concurrency) 4 × 8 = 32 Deployment replicas, MaxConcurrentCalls
Service rate (μ) 32 ÷ 0.4 = 80 msg/s Should match CompleteMessage rate
Growth during peak 120 − 80 = 40 msg/s ≈ 144,000/hour λ − μ
Wait for a new message at 400,000 backlog 400,000 ÷ 80 ≈ 83 min Little's law (W = L ÷ throughput)
Target with headroom μ ≥ 1.5 × peak λ = 180 msg/s Capacity rule

Scale out, or fix the handler?

Option Helps when Stops helping when
More consumers (pods) Handler is CPU- or latency-bound and downstream has headroom Database or partner hits its limit; sessions cap parallelism
Higher MaxConcurrentCalls Handler waits on I/O Downstream saturates; memory per message
PrefetchCount Many small, fast messages Prefetched messages' locks expire before processing
Faster handler (batching, caching) Per-message round trips dominate Already near the downstream floor
Partition the work One hot partition or session Ordering requirements span partitions

Production example

In a typical case, handler time drops from 400 ms to 90 ms after caching reference data for five minutes and inserting invoice lines with a single batched SaveChanges per message rather than many. The same 32-way parallelism now gives about 355 messages/s, three times the peak arrival rate, so the backlog never forms; database DTU actually falls from 70% to 45% because there are fewer round trips. The dead-letter queue is separated into a daily review, and an alert on oldest-message age above 10 minutes replaces the count alert that had been ignored for months.

🔍 What the interviewer is checking

Checks whether the candidate can reason about queues quantitatively, find the real bottleneck before scaling, understands Service Bus consumer settings and poison messages, and sets up autoscaling and age-based alerting tied to a business promise.

Green flags

  • Compares arrival and service rates and uses Little's law to explain the delay
  • Computes consumer throughput from replicas, concurrency and handler time
  • Profiles the handler before scaling and worries about downstream capacity
  • Handles poison messages explicitly and keeps the handler idempotent
  • Alerts on oldest-message age and scales with KEDA within a downstream cap

Red flags

  • "Add more consumers" with no numbers
  • Alerts on queue length only
  • Ignores duplicates and poison messages

📚 Learn in depth

1. Queues from first principles

A queue is a buffer between an arrival process and a service process. If, over a period, the average arrival rate λ is lower than the service rate μ, the queue stays short and drains. If λ > μ, it grows linearly by (λ − μ) per second and only drains when arrivals fall. That's the daily sawtooth: up from 9 am, down overnight.

messages
   │                  peak backlog
   │              ___/\
   │          ___/     \___
   │      ___/              \___
   │_____/                       \______
   └────┬────────┬─────────┬─────────┬───► time
       9am      2pm       6pm      midnight
        λ > μ             λ < μ

Little's law: average number in the system L = λ × W. Rearranged, the wait W ≈ L ÷ throughput, which converts a backlog count into a customer-facing delay.

2. How a Service Bus consumer's throughput is set

With ServiceBusProcessor:

  • MaxConcurrentCalls: how many messages one processor handles in parallel (default 1).
  • PrefetchCount: how many messages the client fetches ahead (default 0). Prefetched messages are locked; if you don't process them before the lock expires (default lock duration 30 s, up to 5 minutes), they're redelivered and the delivery count goes up.
  • Lock renewal: MaxAutoLockRenewalDuration keeps long handlers from losing their lock.
  • Sessions: with sessions, messages in one session are processed in order by one consumer at a time, so parallelism is capped by the number of active sessions (MaxConcurrentSessions).

Throughput per consumer ≈ MaxConcurrentCalls ÷ handler time, as long as the handler is I/O-bound.

3. Where handler time goes

Per-message traces (with the trace context propagated from the producer) show the breakdown: database calls, partner calls, CPU. The usual finding is many small round trips: N lookups and single-row writes per message. Each round trip to Azure SQL in the same region costs around a millisecond or more in network time plus query time, and they add up quickly.

4. Why scaling out can make it worse

Every extra consumer adds load downstream. If the handler's time is mostly database work, tripling consumers triples database load; once the database saturates, handler time rises and throughput doesn't improve, while every other user of that database slows down. Partner APIs with rate limits behave the same way, but return 429s that then become retries.

5. Poison messages

A message that always fails is delivered up to MaxDeliveryCount times (default 10) before it's dead-lettered. With long handlers and timeouts, ten attempts can cost minutes of consumer time each. A few thousand poison messages every morning quietly eat capacity. Detect them by delivery count and exception type, dead-letter explicitly for non-transient errors (validation, missing data) instead of waiting for ten attempts, and alert on DLQ growth.

6. Autoscaling and alerting

  • KEDA (built into AKS as an add-on and used by Azure Container Apps) scales a deployment on Service Bus queue length or message count per replica, from a minimum to a maximum. Set the maximum from the downstream capacity, not from hope.
  • Alert on oldest-message age (the business promise, e.g. invoices visible within 10 minutes) rather than raw count. Service Bus exposes active message count; age is easiest to compute from an enqueued timestamp you record on processing, or by peeking.

Try it yourself

  1. Run a producer that sends 120 messages/s and a consumer with MaxConcurrentCalls = 8 and a 400 ms handler; watch the queue grow in Service Bus Explorer and compute the rate.
  2. Raise MaxConcurrentCalls to 32 and confirm throughput rises fourfold while the handler is I/O-bound.
  3. Make the handler call a local SQL database with five lookups per message; add consumers until the database saturates and throughput flattens.
  4. Replace the lookups with a cached dictionary and batch the inserts; measure handler time again.
  5. Send some messages that always throw; watch them consume ten deliveries each, then dead-letter them explicitly on the first validation failure.
  6. Deploy the consumer with a KEDA ScaledObject on queue length and watch replicas follow the load.

💻 Code

A consumer tuned for throughput, with explicit dead-lettering for non-transient failures.

namespace Invoicing.Worker;

using Azure.Messaging.ServiceBus;
using System.Diagnostics.Metrics;

public sealed record InvoiceSubmitted(Guid InvoiceId, string CustomerId, IReadOnlyList<InvoiceLine> Lines);
public sealed record InvoiceLine(string Sku, int Quantity, decimal UnitPrice);

public sealed class InvoiceConsumer(
    ServiceBusClient client,
    IServiceScopeFactory scopes,
    ILogger<InvoiceConsumer> log,
    IMeterFactory meters) : BackgroundService
{
    private readonly Histogram<double> _queueAge =
        meters.Create("Invoicing.Worker").CreateHistogram<double>("invoice.queue_age", unit: "s");

    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        await using var processor = client.CreateProcessor("invoices", new ServiceBusProcessorOptions
        {
            MaxConcurrentCalls = 16,                       // I/O-bound handler: parallelism per pod
            PrefetchCount = 32,                            // ~2x concurrency; keeps locks from expiring unprocessed
            AutoCompleteMessages = false,                  // complete only after the work is committed
            MaxAutoLockRenewalDuration = TimeSpan.FromMinutes(5)
        });

        processor.ProcessMessageAsync += HandleAsync;
        processor.ProcessErrorAsync += e =>
        {
            log.LogError(e.Exception, "Service Bus error {Source} on {Entity}", e.ErrorSource, e.EntityPath);
            return Task.CompletedTask;
        };

        await processor.StartProcessingAsync(stoppingToken);
        try { await Task.Delay(Timeout.Infinite, stoppingToken); }
        catch (OperationCanceledException) { }
        await processor.StopProcessingAsync(CancellationToken.None);
    }

    private async Task HandleAsync(ProcessMessageEventArgs args)
    {
        // Queue age is the metric that matches the customer promise.
        _queueAge.Record((DateTimeOffset.UtcNow - args.Message.EnqueuedTime).TotalSeconds);

        InvoiceSubmitted? invoice;
        try { invoice = args.Message.Body.ToObjectFromJson<InvoiceSubmitted>(); }
        catch (System.Text.Json.JsonException ex)
        {
            // Non-transient: retrying 10 times only wastes capacity.
            await args.DeadLetterMessageAsync(args.Message, "InvalidPayload", ex.Message, args.CancellationToken);
            return;
        }

        await using var scope = scopes.CreateAsyncScope();
        var handler = scope.ServiceProvider.GetRequiredService<InvoiceHandler>();
        await handler.HandleAsync(invoice!, args.Message.MessageId, args.CancellationToken); // idempotent on MessageId
        await args.CompleteMessageAsync(args.Message, args.CancellationToken);
    }
}
// The handler: cached reference data and one batched write instead of N round trips.
namespace Invoicing.Worker;

using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Caching.Hybrid;

public sealed class InvoiceHandler(InvoicingDbContext db, HybridCache cache)
{
    public async Task HandleAsync(InvoiceSubmitted msg, string messageId, CancellationToken ct)
    {
        if (await db.ProcessedMessages.AnyAsync(p => p.MessageId == messageId, ct)) return; // duplicate delivery

        var taxRules = await cache.GetOrCreateAsync("tax-rules",
            async t => await db.TaxRules.AsNoTracking().ToListAsync(t), cancellationToken: ct); // was a query per message

        var invoice = Invoice.Create(msg, taxRules);
        db.Invoices.Add(invoice);                         // lines added through the aggregate
        db.ProcessedMessages.Add(new ProcessedMessage(messageId, DateTimeOffset.UtcNow));
        await db.SaveChangesAsync(ct);                    // one round trip, batched by EF Core
    }
}
# KEDA: scale on queue length, capped at what the database can take
apiVersion: keda.sh/v1alpha1
kind: ScaledObject
metadata: { name: invoice-worker }
spec:
  scaleTargetRef: { name: invoice-worker }
  minReplicaCount: 2
  maxReplicaCount: 10          # from the downstream capacity test, not a guess
  triggers:
    - type: azure-servicebus
      metadata: { queueName: invoices, messageCount: "500" }
      authenticationRef: { name: servicebus-workload-identity }

⚠ Common mistakes

  • Mistake: Scaling consumers without checking downstream capacity. Why it is wrong: The bottleneck moves to the database or partner, throughput flattens and other users suffer. Instead: Find where handler time goes and set the scaling maximum from a downstream capacity test.
  • Mistake: Alerting on queue length alone. Why it is wrong: The right count depends on throughput; 10,000 might be two minutes or two hours. Instead: Alert on oldest-message age against the business promise, and chart arrival rate, completion rate and handler p95 side by side so you see the gap opening weeks before it hurts.
  • Mistake: Leaving MaxConcurrentCalls at 1 for an I/O-bound handler. Why it is wrong: Each consumer processes one message at a time while waiting on I/O. Instead: Raise it and measure, watching downstream load.
  • Mistake: Choosing PrefetchCount without reference to handler time. Why it is wrong: Prefetched messages are locked from the moment they arrive; if the client holds more than it can process within the lock duration, locks expire, messages are redelivered and delivery counts climb. Instead: Tune it to the handler: for fast handlers (a few milliseconds) a larger prefetch, for example 10–20× concurrency, cuts round trips; for slow handlers (hundreds of milliseconds) keep it near 1–2× concurrency, and check that prefetch × handler time ÷ concurrency stays well under the lock duration.
  • Mistake: Letting non-transient failures retry MaxDeliveryCount times. Why it is wrong: Poison messages consume ten attempts of capacity each. Instead: Dead-letter explicitly for validation and payload errors; for transient errors (timeouts, 429s, SQL transient faults) retry with backoff in the handler a couple of times, then abandon so Service Bus redelivers later.
  • Mistake: Making the handler non-idempotent. Why it is wrong: At-least-once delivery means duplicates during redeliveries and scale events. Instead: Deduplicate on message id or a business key in the same transaction as the write.
  • Mistake: Treating the daily backlog as normal because it drains overnight. Why it is wrong: Customers wait hours, and any growth in volume turns it into a backlog that never drains. Instead: Provision μ at about 1.5× peak λ and track it.

🏛 Senior insight: trade-offs

This is a capacity planning question disguised as an incident. The senior approach is to model it: measure λ and μ, compute the gap and the delay with Little's law, then decide where to add capacity. Usually the cheapest capacity is in the handler, because per-message round trips are the dominant cost, and fixing them reduces downstream load instead of increasing it.

The second senior point is defining the promise. 'Invoices visible within 10 minutes' gives you an SLO, an alert (oldest message age), and a scaling target. Without it, a backlog is just a number that people learn to ignore.

Option When it fits Cost When not to
Scale out with KEDA Handler is efficient, downstream has headroom More pods; downstream load rises When the database or partner is the bottleneck
Optimise the handler Per-message round trips dominate Engineering time When handler time is already near the downstream floor
Partition or more sessions Ordering per key, not global Redesign of keys When strict global ordering is required
Shift non-urgent work off-peak Some messages aren't time-critical Separate queue, scheduled processing When everything has the same promise

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions poison messages or the dead-letter queue Why: Checks diagnosing and handling poison messages and the DLQ
    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 talks about draining a large backlog Why: Checks recovering from a huge backlog without overwhelming downstream systems
    How to 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.

  3. When: Candidate mentions MaxConcurrentCalls, prefetch or lock renewal Why: Checks hands-on ServiceBusProcessor configuration
    How to answer

    I host a ServiceBusProcessor in a BackgroundService, with ServiceBusClient as a singleton using DefaultAzureCredential. I set AutoCompleteMessages = false and settle explicitly:

    • Complete after the database commit, which gives at-least-once delivery.
    • Abandon (or just throw) on transient errors so DeliveryCount rises and the broker redelivers; after MaxDeliveryCount it dead-letters automatically.
    • Dead-letter immediately on permanent errors such as an unparseable body, with a reason.

    MaxConcurrentCalls is sized to the downstream, PrefetchCount is kept small, and MaxAutoLockRenewalDuration is longer than the slowest handler. On shutdown I call StopProcessingAsync and honour args.CancellationToken. Because duplicates still happen, the handler is idempotent on MessageId. The trade-off: more concurrency means more throughput but more pressure on the database.

🛠 Real-world problems: how you handle them

Invoice backlog that grew every business day
Situation
An invoice-processing worker on [AKS, four pods] consuming an Azure Service Bus [Premium] queue, writing to Azure SQL. Peak arrival during business hours was [about 120 messages/s]; customers expected invoices within [minutes].
Signals
Queue active message count rose from 9 am to [400,000] by 2 pm and drained overnight. Support tickets about missing invoices every afternoon. Completed messages per second were flat at [about 80] all day. Dead-letter queue grew by [about 2,000] a day. No error alerts fired.
Investigation
Compared Service Bus `IncomingMessages` and `CompleteMessage` metrics: arrivals exceeded the flat completion rate from 9 am. Computed μ = 4 × 8 ÷ 0.4 s = 80/s. Application Insights traces per message showed 300 of 400 ms spent in five lookup queries and single-row inserts; Azure SQL was at [70%] DTU. Dead-lettered messages were mostly invalid payloads from [one upstream system], each retried ten times.
Resolution
Immediate: temporarily scaled to six pods (database headroom allowed it) and paused a non-urgent reporting job that shared the database. Real fix: cached tax and product reference data with HybridCache, batched writes into one `SaveChanges`, raised `MaxConcurrentCalls` to 16, added explicit dead-lettering for invalid payloads and fixed the upstream producer.
Prevention
KEDA scaling on queue length with a maximum set from a database capacity test, an alert on oldest-message age above 10 minutes, a daily DLQ review with an alert on growth, and a quarterly capacity test at 1.5× peak arrival rate.

How to tell it (STAR)

**S:** At [company], our invoice queue grew every business day to around 400,000 messages and only drained overnight, so customers waited hours for invoices. **T:** I was asked to fix it, and the obvious suggestion was to triple the consumers. **A:** I measured arrivals against completions and worked out our ceiling: four pods, eight concurrent, 400 ms each, so 80 a second against 120 arriving. Traces showed most of the 400 ms was five database round trips per message, so scaling out would have overloaded the database. We cached the reference data, batched the writes, raised concurrency, and dead-lettered invalid payloads on the first attempt. **R:** Handler time dropped to [90 ms], throughput rose to [over 300 a second] on the same four pods, the daily backlog disappeared, database load fell from [70% to 45%], and we now alert on message age instead of count.

↩ Usually asked after

More in Debugging Production Issues

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me