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

📚 Interview question

Write an Azure Service Bus consumer as a .NET 10 hosted service using ServiceBusProcessor. Show how you complete, abandon and dead-letter messages, set concurrency and prefetch, handle lock renewal and cancellation on shutdown, and tell me what delivery guarantee your consumer gives and how it handles duplicates.

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.

Mid-Level Coding Intermediate azure-service-bus background-service dead-letter-queue distributed-systems dotnet messaging

🎯 Key points

  • ServiceBusProcessor in a BackgroundService; ServiceBusClient registered as a singleton (AddAzureClients, DefaultAzureCredential)
  • AutoCompleteMessages = false; complete only after the work is committed (at-least-once)
  • Transient failure: throw or abandon so DeliveryCount increments and the broker redelivers
  • Permanent failure (bad schema, validation): DeadLetterMessageAsync with reason and description
  • MaxConcurrentCalls sized to the downstream; PrefetchCount small to avoid locks expiring in the buffer
  • MaxAutoLockRenewalDuration set above the p99.9 handler time; entity LockDuration 30-60 s so a crashed pod's messages return quickly
  • ProcessErrorAsync logs ErrorSource, entity and exception for observability; it is not a retry hook
  • StopProcessingAsync on shutdown; args.CancellationToken into all I/O; handler idempotent on MessageId

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

🗣 Full answer (senior)

How I would answer this in an interview

"I register a singleton ServiceBusClient through AddAzureClients with DefaultAzureCredential, so there are no connection strings and the AMQP connection is shared. The consumer is a BackgroundService that creates a ServiceBusProcessor for the queue or subscription, wires ProcessMessageAsync and ProcessErrorAsync, and calls StartProcessingAsync. 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 once DeliveryCount passes MaxDeliveryCount, ten by default.

Then the knobs. MaxConcurrentCalls is 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. PrefetchCount I 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. MaxAutoLockRenewalDuration must exceed the slowest realistic handler, or the lock expires and another pod gets the same message. On shutdown, the host's stopping token triggers StopProcessingAsync; in-flight handlers see args.CancellationToken cancelled, 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 MessageId in the same transaction. The mistake I see is AutoCompleteMessages = true with a try/catch that swallows exceptions; the processor then completes failed messages and you lose them silently."


Settlement decisions

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

The knobs that matter

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

Shutdown sequence

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.

Production example

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

🔍 What the interviewer is checking

Checks the candidate can write a consumer that neither loses nor silently duplicates messages, and that shuts down cleanly.

Green flags

  • Disables auto-complete and completes after the commit
  • Separates transient (abandon/throw) from permanent (dead-letter) failures
  • Understands prefetch and lock renewal interactions
  • Uses a scope per message and a singleton client

Red flags

  • Swallows exceptions and completes anyway
  • New ServiceBusClient per message
  • No mention of duplicates or idempotency

📚 Learn in depth

1. What ServiceBusProcessor does for you

The 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

2. Peek-lock internals

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.

3. Prefetch and lock expiry

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.

4. Sessions

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.

5. Errors versus outcomes

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.

6. Scaling out

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.

7. Observability

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.

Try it yourself

  1. Run the code below against the Service Bus emulator; send 1,000 messages and measure throughput at concurrency 1, 8 and 32.
  2. Set PrefetchCount = 500 with a 2 s handler and count MessageLockLost errors.
  3. Throw JsonException and confirm the message lands in the DLQ with your reason; throw TimeoutException and watch DeliveryCount climb to 10.
  4. Press Ctrl+C mid-batch and check that in-flight messages are redelivered and none are lost.
  5. Add dotnet-counters monitor on the process and watch ThreadPool queue length as you raise concurrency.

💻 Code

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

⚠ Common mistakes

  • Mistake: Leaving 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.
  • Mistake: Large 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.
  • Mistake: 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.
  • Mistake: An empty 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.
  • Mistake: Creating a 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.
  • Mistake: Injecting a scoped 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.
  • Mistake: Retrying permanent failures. Why it is wrong: a bad message burns 10 deliveries and delays others. Instead: dead-letter immediately with a reason and description.
  • Mistake: Ignoring 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.
  • Mistake: Setting 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.

🏛 Senior insight: trade-offs

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.

🔗 Follow-ups the interviewer may ask

  1. When: Candidate says the consumer is at-least-once Why: Checks they understand where duplicates come from and why exactly-once is a myth
    How to answer

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

    • Kafka transactions give exactly-once only for read-process-write within Kafka.
    • Service Bus duplicate detection and SQS FIFO dedup only drop producer resends within a window.

    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.

  2. When: Candidate says the handler is idempotent on MessageId Why: Checks they can implement the inbox table correctly
    How to answer

    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:

    1. Insert the inbox row first.
    2. Apply the business change.
    3. Commit, then complete the Service Bus message.

    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.

  3. When: Candidate sizes MaxConcurrentCalls against the database Why: Checks they understand bulkheads and protecting downstream resources
    How to answer

    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.

    • Outbound: a concurrency limiter per dependency. Use Polly's AddConcurrencyLimiter, or the standard handler's limiter (1,000 permits, queue 0 by default). Give each dependency a separate named HttpClient with MaxConnectionsPerServer.
    • Inbound: ASP.NET Core AddRateLimiter concurrency policies per endpoint group.
    • Messaging: separate queues and consumers with their own 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.

🛠 Real-world problems: how you handle them

Duplicate invoices from an oversized prefetch buffer
Situation
An invoicing worker on [AKS in Australia East] consumes `OrderPlaced` from a Service Bus subscription, generating a PDF and an invoice row per order, about [40,000] orders a day. A developer raised `PrefetchCount` to 500 to 'speed things up'.
Signals
Finance reports duplicate invoice numbers for the same order; logs show `MessageLockLost` exceptions on complete; Application Insights shows the same `MessageId` handled on two pods minutes apart; `DeliveryCount` of 2-3 on many messages despite no handler errors.
Investigation
Compared deployment history with the start of duplicates; checked processor options in config; calculated buffer wait (500 messages / 4 concurrent / 2 s each = ~250 s against a 30 s lock); reproduced against the Service Bus emulator with the same settings.
Resolution
Immediate: reverted `PrefetchCount` to 8 and voided the duplicate invoices. Real fix: added an inbox table keyed on (MessageId, Consumer) in the invoice transaction and a unique index on Invoices(OrderId) as a second guard.
Prevention
Config validation that fails startup if `PrefetchCount > 2 * MaxConcurrentCalls`; alert on lock-lost errors; integration test that delivers a message twice; ADR documenting consumer settings.

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.

↩ Usually asked after

More in Messaging

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me