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.
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.
"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
MaxConcurrentCallsof 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."
| 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 |
| 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 |
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.
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
Red flags
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.
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.MaxAutoLockRenewalDuration keeps long handlers from losing their lock.MaxConcurrentSessions).Throughput per consumer ≈ MaxConcurrentCalls ÷ handler time, as long as the handler is I/O-bound.
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.
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.
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.
MaxConcurrentCalls = 8 and a 400 ms handler; watch the queue grow in Service Bus Explorer and compute the rate.MaxConcurrentCalls to 32 and confirm throughput rises fourfold while the handler is I/O-bound.ScaledObject on queue length and watch replicas follow the load.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 }
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.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.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.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 |
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 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.
I host a ServiceBusProcessor in a BackgroundService, with ServiceBusClient as a singleton using DefaultAzureCredential. I set AutoCompleteMessages = false and settle explicitly:
DeliveryCount rises and the broker redelivers; after MaxDeliveryCount it dead-letters automatically.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.
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.
Last updated 23 Nov 2026.