Covers building a production Service Bus consumer with ServiceBusProcessor in a BackgroundService: settlement (complete, abandon, dead-letter), MaxConcurrentCalls and PrefetchCount, auto lock renewal, graceful shutdown with cancellation, error handling, DI with Microsoft.Extensions.Azure and idempotent processing.
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.
"I register a singleton
ServiceBusClientthroughAddAzureClientswithDefaultAzureCredential, so there are no connection strings and the AMQP connection is shared. The consumer is aBackgroundServicethat creates aServiceBusProcessorfor the queue or subscription, wiresProcessMessageAsyncandProcessErrorAsync, and callsStartProcessingAsync. I turn off auto-complete because I want the settlement to be a deliberate decision: complete after my database transaction commits, dead-letter straight away when the message can never succeed, and let transient failures throw so the processor abandons the message and the broker redelivers it. Service Bus moves it to the dead-letter queue itself onceDeliveryCountpassesMaxDeliveryCount, ten by default.Then the knobs.
MaxConcurrentCallsis per process, so with three pods and 8 calls each I have 24 concurrent handlers, and I size that against the database's connection pool and DTUs, not against the queue length.PrefetchCountI keep at zero or a small multiple of concurrency, because prefetched messages are already locked and their lock clock is ticking while they sit in memory.MaxAutoLockRenewalDurationmust exceed the slowest realistic handler, or the lock expires and another pod gets the same message. On shutdown, the host's stopping token triggersStopProcessingAsync; in-flight handlers seeargs.CancellationTokencancelled, and anything not completed is simply redelivered later.The delivery guarantee is at-least-once, so the handler is idempotent: an inbox row keyed on
MessageIdin the same transaction. The mistake I see isAutoCompleteMessages = truewith a try/catch that swallows exceptions; the processor then completes failed messages and you lose them silently."
| Outcome | Call | Effect |
|---|---|---|
| Success | CompleteMessageAsync |
Removed from the entity |
| Transient failure (SQL timeout, 503) | throw, or AbandonMessageAsync |
Lock released, DeliveryCount++, redelivered |
| Permanent failure (bad JSON, unknown type, failed validation) | DeadLetterMessageAsync(msg, reason, description) |
Moved to $DeadLetterQueue with properties |
| Need to wait for something | DeferMessageAsync (store sequence number) |
Hidden until received by sequence number |
| Too many attempts | (automatic) | Dead-lettered with reason MaxDeliveryCountExceeded |
| Option | Default | Guidance |
|---|---|---|
MaxConcurrentCalls |
1 | Size to the downstream; start at 4-16 per pod |
PrefetchCount |
0 | 0 or up to ~2x concurrency; never so large that locks expire in the buffer |
AutoCompleteMessages |
true | Set false and settle explicitly |
MaxAutoLockRenewalDuration |
5 min | Longer than the p99.9 handler time |
Entity LockDuration |
30 s (max 5 min) | Renewal handles longer work |
Entity MaxDeliveryCount |
10 | Lower (3-5) for expensive handlers |
SIGTERM -> host cancels stoppingToken
-> StopProcessingAsync(): stop receiving, wait for in-flight handlers
-> handlers see args.CancellationToken cancelled -> throw OperationCanceledException
-> uncompleted messages are abandoned or their locks expire -> redelivered later
-> DisposeAsync processor, client
Kubernetes gives 30 seconds by default (terminationGracePeriodSeconds); make sure HostOptions.ShutdownTimeout fits inside it.
An invoicing consumer ran with PrefetchCount = 500, MaxConcurrentCalls = 4 and handlers of about 2 s each. Messages sat in the prefetch buffer for minutes, their 30-second locks expired, and around 8% were processed twice. Dropping prefetch to 8 and adding an inbox table brought duplicates to zero with no loss of throughput (about 120 messages per minute per pod).
Checks the candidate can write a consumer that neither loses nor silently duplicates messages, and that shuts down cleanly.
Green flags
Red flags
ServiceBusClient per messageThe processor runs a receive loop per concurrency slot over one AMQP link. For each message it: invokes your handler with a CancellationToken; renews the lock in the background until the handler returns or MaxAutoLockRenewalDuration passes; if the handler throws, calls AbandonMessageAsync (when auto-complete is on, or when you haven't settled); then reports the exception to ProcessErrorAsync.
receive loop (x MaxConcurrentCalls)
|-- ReceiveMessagesAsync (uses prefetch buffer if enabled)
|-- start lock renewal timer
|-- await ProcessMessageAsync(args)
| success -> you Complete (or auto-complete)
| throw -> Abandon + ProcessErrorAsync
|-- stop renewal
The broker marks the message invisible and returns a lock token. Settlement is an operation on that link with that token. If the link drops (network blip, pod restart), the token is invalid; completing then fails with MessageLockLost and the message will be redelivered. That is why settlement must come after the work and the work must be idempotent.
Prefetched messages are locked when they arrive in the client buffer, not when your handler starts. With prefetch 500, concurrency 4 and 2 s handlers, the last message waits 250 s, far beyond a 30 s lock. The processor does not renew locks on buffered messages. Rule of thumb: PrefetchCount <= MaxConcurrentCalls * LockDuration / handlerTime, and much lower in practice.
For session-enabled entities use ServiceBusSessionProcessor with MaxConcurrentSessions and MaxConcurrentCallsPerSession (keep 1 for strict order). Session locks work like message locks but cover the whole session.
ProcessErrorAsync is for observability, not recovery: it receives exceptions from your handler and from the receive loop (for example ServiceBusFailureReason.ServiceCommunicationProblem). Log them with ErrorSource and the entity path; the processor keeps running and the SDK's retry policy (ServiceBusRetryOptions, exponential by default) handles transient connection problems.
Throughput is roughly pods x MaxConcurrentCalls / handlerSeconds. KEDA's azure-servicebus scaler can scale pods on active message count. Watch the downstream: doubling consumers against a saturated database only increases lock-lost errors and retries.
The SDK emits Azure.Messaging.ServiceBus activities; with OpenTelemetry (AddSource("Azure.Messaging.ServiceBus.*")) or Application Insights you get a span per message linked to the producer's trace. Add MessageId, DeliveryCount and EnqueuedTime to log scopes.
PrefetchCount = 500 with a 2 s handler and count MessageLockLost errors.JsonException and confirm the message lands in the DLQ with your reason; throw TimeoutException and watch DeliveryCount climb to 10.dotnet-counters monitor on the process and watch ThreadPool queue length as you raise concurrency.A production-shaped consumer: explicit settlement, sensible limits, graceful shutdown and DI registration.
// Program.cs
using Azure.Identity;
using Microsoft.Extensions.Azure;
var builder = Host.CreateApplicationBuilder(args);
builder.Services.AddAzureClients(clients =>
{
clients.AddServiceBusClientWithNamespace(builder.Configuration["ServiceBus:Namespace"]!);
clients.UseCredential(new DefaultAzureCredential()); // managed identity in Azure, dev login locally
});
builder.Services.AddScoped<InvoiceHandler>();
builder.Services.AddHostedService<InvoiceConsumer>();
builder.Services.Configure<HostOptions>(o => o.ShutdownTimeout = TimeSpan.FromSeconds(25)); // < k8s 30 s grace
await builder.Build().RunAsync();
// InvoiceConsumer.cs
using System.Text.Json;
using Azure.Messaging.ServiceBus;
namespace Invoicing;
public sealed record OrderPlaced(Guid OrderId, string CustomerId, decimal Total);
public sealed class InvoiceConsumer(
ServiceBusClient client,
IServiceScopeFactory scopes,
ILogger<InvoiceConsumer> logger) : BackgroundService
{
private ServiceBusProcessor? _processor;
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
_processor = client.CreateProcessor("orders", "invoicing", new ServiceBusProcessorOptions
{
AutoCompleteMessages = false, // settle deliberately
MaxConcurrentCalls = 8, // sized to the SQL pool, not the backlog
PrefetchCount = 8, // small: buffered messages' locks are ticking
MaxAutoLockRenewalDuration = TimeSpan.FromMinutes(5) // > slowest handler
});
_processor.ProcessMessageAsync += HandleAsync;
_processor.ProcessErrorAsync += args =>
{
logger.LogError(args.Exception, "Service Bus error from {Source} on {Entity}",
args.ErrorSource, args.EntityPath);
return Task.CompletedTask;
};
await _processor.StartProcessingAsync(stoppingToken);
await Task.Delay(Timeout.Infinite, stoppingToken).ContinueWith(_ => { }, TaskScheduler.Default);
}
private async Task HandleAsync(ProcessMessageEventArgs args)
{
ServiceBusReceivedMessage msg = args.Message;
using var _ = logger.BeginScope(new Dictionary<string, object>
{
["MessageId"] = msg.MessageId,
["DeliveryCount"] = msg.DeliveryCount
});
OrderPlaced? evt;
try
{
evt = msg.Body.ToObjectFromJson<OrderPlaced>();
}
catch (JsonException ex)
{
// Permanent: retrying will never fix a malformed body.
await args.DeadLetterMessageAsync(msg, "InvalidJson", ex.Message, args.CancellationToken);
return;
}
if (evt is null || evt.Total < 0)
{
await args.DeadLetterMessageAsync(msg, "ValidationFailed", "Missing body or negative total",
args.CancellationToken);
return;
}
await using var scope = scopes.CreateAsyncScope(); // scoped DbContext per message
var handler = scope.ServiceProvider.GetRequiredService<InvoiceHandler>();
// Transient exceptions (SqlException, HttpRequestException) propagate: the processor abandons
// the message, DeliveryCount increments, and the broker dead-letters after MaxDeliveryCount.
await handler.CreateInvoiceAsync(msg.MessageId, evt, args.CancellationToken); // idempotent on MessageId
await args.CompleteMessageAsync(msg, args.CancellationToken); // only after the commit
}
public override async Task StopAsync(CancellationToken cancellationToken)
{
if (_processor is not null)
{
await _processor.StopProcessingAsync(cancellationToken); // drain in-flight handlers
await _processor.DisposeAsync();
}
await base.StopAsync(cancellationToken);
}
}
AutoCompleteMessages = true and catching all exceptions in the handler. Why it is wrong: the handler returns normally, so failed messages are completed and lost. Instead: disable auto-complete or let exceptions propagate.PrefetchCount with slow handlers. Why it is wrong: buffered messages' locks expire before processing, causing duplicates and lock-lost errors. Instead: keep prefetch at 0 or close to MaxConcurrentCalls.MaxAutoLockRenewalDuration shorter than the slowest handler (or zero). Why it is wrong: the lock expires mid-handler and another pod processes the same message concurrently. Instead: measure handler p99.9 and set renewal above it; move genuinely long work elsewhere.ProcessErrorAsync, or trying to retry from it. Why it is wrong: receive-loop and handler failures disappear from logs, and the handler has already finished, so a retry there does nothing. Instead: log ErrorSource, EntityPath and the exception with structured properties, and let settlement drive retries.ServiceBusClient per message or per request. Why it is wrong: each opens an AMQP connection, exhausting sockets and adding latency. Instead: register one singleton client.DbContext into the hosted service. Why it is wrong: it becomes a captive dependency shared by concurrent handlers, which is not thread-safe. Instead: create a scope per message with IServiceScopeFactory.args.CancellationToken. Why it is wrong: shutdown hangs until the pod is killed, and work is cut mid-transaction. Instead: pass the token to every async call.MaxConcurrentCalls to match the backlog. Why it is wrong: the database saturates and everything slows. Instead: size to the downstream and scale pods with KEDA if needed.A consumer is a small distributed system: lock leases, retries, a dead-letter path, a shutdown protocol and a dedup store. The SDK handles the plumbing, but the settlement policy and idempotency are yours, and they are what interviewers probe.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
Raw ServiceBusProcessor |
One or two consumers, full control | You write retries, DLQ policy, inbox | Many message types and sagas |
| Azure Functions Service Bus trigger | Event-driven, scale-to-zero | Less control over concurrency and settlement (configurable in host.json) | Long-running handlers, strict VNet needs on Consumption plan |
| MassTransit / NServiceBus / Wolverine | Many consumers, outbox, sagas, retries out of the box | Licence (MassTransit v9, NServiceBus are commercial), abstraction to learn | Simple single-queue workers |
Observability is part of the design, not an add-on. I enable OpenTelemetry tracing for the Azure.Messaging.ServiceBus source so each message span links to the producer's trace, add MessageId and DeliveryCount to log scopes, and build one dashboard per consumer: completed per second, handler duration p95/p99, DeliveryCount > 1 rate, lock-lost errors, DLQ count and oldest message age. If lock-lost errors rise with concurrency, you've found the downstream's limit.
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.
With at-least-once delivery, duplicates are normal: outbox resends, peek-lock redelivery after a crash or lock expiry, and publisher retries. An idempotent consumer makes processing a message twice have the same effect as once.
The inbox is an InboxMessages table with a primary key on (MessageId, Consumer). For each message, in one EF Core transaction:
If the insert fails with SQL error 2627/2601, the message was already processed, so complete it. A concurrent duplicate blocks on the key lock until the first commits, then fails the insert. If the first rolls back, the duplicate goes ahead.
Purge old rows past the redelivery window. The trade-off is an extra write and table per consumer against correct exactly-once processing.
A bulkhead partitions shared resources so one failing dependency can only exhaust its own share, like the watertight compartments in a ship. In .NET the shared resources are thread-pool threads, sockets, database connection-pool slots, memory and request slots.
AddConcurrencyLimiter, or the standard handler's limiter (1,000 permits, queue 0 by default). Give each dependency a separate named HttpClient with MaxConnectionsPerServer.AddRateLimiter concurrency policies per endpoint group.MaxConcurrentCalls.A bulkhead limits concurrent work. Rate limiting limits requests per time window. Size limits with Little's Law (concurrency = rate x latency) plus headroom, and pair them with timeouts. The trade-off is containment against rejecting work when a compartment is full.
How to tell it (STAR)
**S:** After a config change, our invoicing worker [at company] started issuing duplicate invoices. **T:** I needed to stop it quickly and make sure it couldn't recur. **A:** I noticed lock-lost errors and the same message id on two pods, worked out that a 500-message prefetch buffer meant messages waited about four minutes against a 30-second lock, and reproduced it on the emulator. I reverted prefetch, then added an inbox table and a unique index on order id, and a startup check on the settings. **R:** Duplicates went from [about 8% of invoices] to zero, and the startup validation has caught the same mistake [once] since.
Last updated 23 Nov 2026.