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

πŸ“š Interview question

You are moving a .NET queue worker that processes payments messages from Azure Service Bus onto Kubernetes (or Azure Container Apps). Walk me through how you would run it in production: graceful shutdown when pods are stopped, making processing idempotent so redelivered messages are safe, and scaling it on queue length with KEDA.

Running a .NET Worker Service queue consumer on Kubernetes or Azure Container Apps: SIGTERM and graceful shutdown timing, peek-lock and at-least-once delivery, idempotency with an inbox or processed-message table, poison messages, KEDA scaling on queue length, concurrency and probes.

Senior RealWorldScenario Advanced aspnet-core azure-service-bus idempotency keda kubernetes worker-service

🎯 Key points

  • SIGTERM → host cancels stoppingToken → stop receiving, finish or abandon in-flight messages within HostOptions.ShutdownTimeout; terminationGracePeriodSeconds must be longer
  • Peek-lock gives at-least-once delivery: a crash or lock expiry redelivers, so handlers must be idempotent
  • Idempotency inside: processed-message (inbox) table with a unique key written in the same transaction as the business change
  • Idempotency outside: always pass a stable idempotency key (the message or payment id) to the payment provider, because its side effect can't join your transaction
  • Poison messages: set MaxDeliveryCount deliberately (e.g. 5–10), dead-letter with a reason, alert on DLQ count and age, and run a documented replay process
  • KEDA ScaledObject (or Container Apps scale rule) on azure-servicebus messageCount, with workload identity; min and max replicas, cooldown
  • Concurrency per pod (MaxConcurrentCalls, PrefetchCount) multiplied by replicas must respect downstream limits
  • Monitor oldest-message age and delivery counts, not just depth; ordering needs sessions

⏱ 30-second answer

Three things make a queue worker safe on Kubernetes or Container Apps. Graceful shutdown: on SIGTERM the host cancels stoppingToken. The worker stops receiving and finishes or abandons in-flight messages within HostOptions.ShutdownTimeout, which must be shorter than terminationGracePeriodSeconds. Idempotency: Service Bus peek-lock is at-least-once. A crash, a lock expiry or a shutdown redelivers the message, so the handler records the message id in a processed-messages table in the same transaction as the business change, and passes idempotency keys to the payment provider. Poison messages go to the dead-letter queue after MaxDeliveryCount. Scaling: a KEDA ScaledObject (or a Container Apps scale rule) on queue length adds pods as the backlog grows and scales to zero or a minimum when idle.

The trade-off: more replicas clear backlogs faster but multiply concurrency against downstream systems and break ordering unless you use sessions.

πŸ—£ Full answer (senior)

How I would answer this in an interview

"I design for the fact that pods die. They are stopped on every deployment, every node upgrade and every scale-in. So the questions are: what happens to the message I'm holding, and what happens if I process it twice?

For example, at [company] we moved a [payments settlement] worker from [a VM Windows service] to [AKS]. First, shutdown. Kubernetes sends SIGTERM, and the .NET host turns that into cancelling stoppingToken. Our ServiceBusProcessor handler stopped accepting new messages, let in-flight ones finish for up to 20 seconds, and abandoned anything left so Service Bus would redeliver it straight away instead of waiting for the lock to expire. We set HostOptions.ShutdownTimeout to 25 seconds and terminationGracePeriodSeconds to 40, so the kubelet never killed us mid-transaction. Second, idempotency. Peek-lock means at-least-once, and we proved that in testing: about [0.3%] of messages were delivered twice during rolling deployments. So each handler opens a transaction, inserts the message id into a ProcessedMessages table with a unique key, applies the settlement, and commits. A duplicate hits the unique key, and we complete it without side effects. For the external payment API we sent the same message id as the idempotency key. Poison messages went to the dead-letter queue after 5 attempts, with an alert. [Duplicate settlements went from X to zero.]

Third, scaling. We used KEDA with the azure-servicebus scaler: target 50 messages per replica, minimum 1, maximum 20, authenticated with workload identity. On Container Apps the same thing is a scale rule. The detail people miss is the downstream limit: 20 pods times MaxConcurrentCalls of 8 is 160 concurrent calls to the payment provider, which had a limit of [100 requests per second]. So we capped maxReplicaCount from that budget, not from the queue."


The shutdown timeline

Time Kubernetes .NET worker
0 s Pod marked Terminating, SIGTERM sent ApplicationStopping, stoppingToken cancelled
0–20 s Waiting StopProcessingAsync: no new messages; in-flight handlers finish and complete
20 s Waiting Unfinished messages abandoned (redelivered at once)
25 s Waiting ShutdownTimeout reached; host exits
40 s SIGKILL if still running (never reached)

Delivery guarantees and what they mean

Guarantee When you get it What you must do
At-most-once ReceiveAndDelete mode Accept lost messages; never for payments
At-least-once Peek-lock (default) Idempotent handlers, dead-letter handling
Effectively once At-least-once plus deduplication Inbox table in the same transaction; idempotency keys downstream

Scaling knobs

Knob Where Guidance
messageCount target KEDA trigger metadata Messages a pod can clear in roughly one polling interval
minReplicaCount / maxReplicaCount ScaledObject Max from the downstream budget; min 0 only if cold start is acceptable
MaxConcurrentCalls, PrefetchCount ServiceBusProcessorOptions Start low (4–16); prefetch only with short handlers, or locks expire in the buffer
cooldownPeriod ScaledObject Avoid flapping: 300 s is the default

Production example

After the move, the [settlement] backlog at [month-end] peaked at [180,000] messages and KEDA scaled from [2 to 20] pods, clearing it in [35 minutes] instead of [about 4 hours] on the old VM. Rolling deployments during business hours caused zero duplicate settlements because the inbox table absorbed redeliveries.

πŸ” What the interviewer is checking

Checks whether the candidate can run a message consumer safely on a container platform: graceful shutdown, at-least-once semantics, idempotency and sensible autoscaling.

Green flags

  • Walks through SIGTERM β†’ stoppingToken β†’ drain β†’ abandon, with timeout ordering
  • States that peek-lock is at-least-once and designs idempotency with an inbox in the same transaction
  • Mentions dead-lettering, alerting and replay
  • Configures KEDA on queue length and caps replicas by downstream limits
  • Knows ordering needs sessions

Red flags

  • Assumes exactly-once delivery or relies on duplicate detection
  • No idea what happens to in-flight messages when a pod stops
  • Scales to 100 pods without considering the database or payment provider

πŸ“š Learn in depth

1. From SIGTERM to cancelled token

kubelet ──SIGTERM──▢ dotnet process
                     ConsoleLifetime / systemd-style handler (PosixSignalRegistration)
                       └─ IHostApplicationLifetime.StopApplication()
                            └─ Host.StopAsync(timeout = HostOptions.ShutdownTimeout)
                                 └─ BackgroundService.StopAsync β†’ cancels stoppingToken
                                      └─ your ExecuteAsync: await processor.StopProcessingAsync()
kubelet waits terminationGracePeriodSeconds ── then SIGKILL

If the container's entrypoint is a shell script that doesn't exec dotnet, SIGTERM goes to the shell and never reaches .NET. Use ENTRYPOINT ["dotnet", "Worker.dll"] (exec form).

2. Peek-lock and why duplicates happen

receive (lock 60 s) ── process ── complete βœ”
                    └─ crash / shutdown / lock expired before complete
                         └─ message becomes visible again β†’ redelivered (DeliveryCount + 1)

The gap between "database committed" and "complete acknowledged" can never be closed completely: a pod killed between the two always causes a redelivery. That's why idempotency must live in your handler, not in the broker. Service Bus duplicate detection only deduplicates messages the sender sends twice within a window. It does nothing for redelivery to consumers.

3. The inbox pattern

CREATE TABLE dbo.ProcessedMessages (
    MessageId   nvarchar(128) NOT NULL PRIMARY KEY,
    ProcessedAt datetime2     NOT NULL DEFAULT sysutcdatetime()
);

In one transaction: insert the message id, then apply the business change. On a duplicate, the insert fails with a key violation (error 2627), and you complete the message without doing anything. For external side effects (a payment API, an email), pass a stable idempotency key derived from the message id, because you can't enlist them in your transaction. Purge rows older than the maximum redelivery window.

4. How KEDA scales

KEDA operator ──polls Service Bus every pollingInterval (30 s)──▢ messageCount = 1,200
   └─ feeds an external metric to the HPA: desired = ceil(1,200 / 50) = 24 β†’ capped at maxReplicaCount 20
   └─ at 0 messages for cooldownPeriod β†’ scale to minReplicaCount (0 allowed: KEDA handles 0↔1)

Azure Container Apps uses KEDA underneath: a custom scale rule of type azure-servicebus with the same metadata, and managed identity for auth.

5. Ordering and sessions

With competing consumers, messages are processed in parallel and out of order. If order matters per entity (all events for account 42 in sequence), use Service Bus sessions with SessionId = accountId and a ServiceBusSessionProcessor. Each session is locked to one consumer at a time, and scaling spreads sessions across pods.

Try it yourself

  1. Run the worker in kind with a 10-second handler, kubectl delete pod, and check in the logs that in-flight messages complete or are abandoned before exit.
  2. Change the Dockerfile to a shell-form entrypoint and repeat: note that the pod takes the full grace period and gets SIGKILLed.
  3. Send 1,000 messages, kill pods randomly during processing, and count duplicates with and without the inbox table.
  4. Install KEDA, apply the ScaledObject, push 5,000 messages and watch kubectl get hpa -w.
  5. Send a message that always throws and watch it reach the dead-letter queue after MaxDeliveryCount.

πŸ’» Code

A Service Bus worker with graceful shutdown and an idempotent handler, plus the KEDA scaler.

// Program.cs (.NET 10 Worker Service)
using Azure.Identity;
using Azure.Messaging.ServiceBus;
using Microsoft.Data.SqlClient;
using Microsoft.EntityFrameworkCore;

var builder = Host.CreateApplicationBuilder(args);

builder.Services.Configure<HostOptions>(o => o.ShutdownTimeout = TimeSpan.FromSeconds(25)); // < terminationGracePeriodSeconds
builder.Services.AddSingleton(_ => new ServiceBusClient(
    builder.Configuration["ServiceBus:Namespace"], new DefaultAzureCredential())); // workload identity, no keys
builder.Services.AddDbContext<PaymentsDb>(o =>
    o.UseSqlServer(builder.Configuration.GetConnectionString("Payments"), s => s.EnableRetryOnFailure()));
builder.Services.AddHostedService<SettlementWorker>();

builder.Build().Run();

public sealed class SettlementWorker(
    ServiceBusClient client, IServiceScopeFactory scopes, ILogger<SettlementWorker> logger) : BackgroundService
{
    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        await using var processor = client.CreateProcessor("settlements", new ServiceBusProcessorOptions
        {
            MaxConcurrentCalls = 8,          // per pod; replicas x 8 must fit the downstream budget
            PrefetchCount = 0,               // avoid locks expiring in a local buffer
            AutoCompleteMessages = false,
            MaxAutoLockRenewalDuration = TimeSpan.FromMinutes(5)
        });

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

        await processor.StartProcessingAsync(stoppingToken);
        try { await Task.Delay(Timeout.Infinite, stoppingToken); }
        catch (OperationCanceledException) { /* SIGTERM */ }

        // Stop taking new messages; in-flight handlers get their CancellationToken signalled.
        logger.LogInformation("Stopping: draining in-flight messages");
        await processor.StopProcessingAsync(CancellationToken.None);
    }

    private async Task HandleAsync(ProcessMessageEventArgs args)
    {
        var msg = args.Message;
        var ct = args.CancellationToken; // cancelled when the processor stops
        await using var scope = scopes.CreateAsyncScope();
        var db = scope.ServiceProvider.GetRequiredService<PaymentsDb>();
        var strategy = db.Database.CreateExecutionStrategy(); // required with EnableRetryOnFailure + transactions
        try
        {
            await strategy.ExecuteAsync(async () =>
            {
                db.ChangeTracker.Clear(); // a clean state on every retry attempt
                await using var tx = await db.Database.BeginTransactionAsync(ct);
                // Inbox: the unique key on MessageId makes redelivery a no-op.
                db.ProcessedMessages.Add(new ProcessedMessage(msg.MessageId, DateTime.UtcNow));
                var settlement = msg.Body.ToObjectFromJson<Settlement>()!;
                db.Settlements.Add(settlement);
                await db.SaveChangesAsync(ct);
                await tx.CommitAsync(ct);
            });
            await args.CompleteMessageAsync(msg, ct);
        }
        catch (DbUpdateException ex) when (ex.InnerException is SqlException { Number: 2627 or 2601 })
        {
            logger.LogInformation("Duplicate message {MessageId}; already processed", msg.MessageId);
            await args.CompleteMessageAsync(msg, CancellationToken.None);
        }
        catch (OperationCanceledException) when (ct.IsCancellationRequested)
        {
            await args.AbandonMessageAsync(msg, cancellationToken: CancellationToken.None); // redeliver now, not after lock expiry
        }
        // Any other exception: the processor abandons; after MaxDeliveryCount the message is dead-lettered.
    }
}

public sealed record ProcessedMessage(string MessageId, DateTime ProcessedAt);
public sealed record Settlement(Guid Id, string AccountId, decimal Amount);

public sealed class PaymentsDb(DbContextOptions<PaymentsDb> options) : DbContext(options)
{
    public DbSet<ProcessedMessage> ProcessedMessages => Set<ProcessedMessage>();
    public DbSet<Settlement> Settlements => Set<Settlement>();
    protected override void OnModelCreating(ModelBuilder b) => b.Entity<ProcessedMessage>().HasKey(p => p.MessageId);
}
# KEDA: scale on queue length, authenticated with workload identity
apiVersion: keda.sh/v1alpha1
kind: TriggerAuthentication
metadata: { name: servicebus-wi }
spec:
  podIdentity: { provider: azure-workload }
---
apiVersion: keda.sh/v1alpha1
kind: ScaledObject
metadata: { name: settlement-worker }
spec:
  scaleTargetRef: { name: settlement-worker }
  minReplicaCount: 1
  maxReplicaCount: 12          # from the downstream budget: 12 pods x 8 concurrent calls
  cooldownPeriod: 300
  triggers:
    - type: azure-servicebus
      metadata:
        namespace: payments-prod
        queueName: settlements
        messageCount: "50"     # target backlog per replica
      authenticationRef: { name: servicebus-wi }
---
# In the Deployment's pod spec:
# terminationGracePeriodSeconds: 40   (longer than HostOptions.ShutdownTimeout)

⚠ Common mistakes

  • Mistake: Assuming each message is delivered exactly once. Why it is wrong: Peek-lock is at-least-once; crashes, shutdowns and lock expiry all redeliver. Instead: Make handlers idempotent with an inbox table in the same transaction and idempotency keys downstream.
  • Mistake: Deduplicating only in your own database. Why it is wrong: If the pod dies after calling the payment provider but before committing, the retry charges again. Instead: Send the same idempotency key (derived from the message or payment id) on every attempt so the provider deduplicates too.
  • Mistake: Relying on Service Bus duplicate detection to stop double processing. Why it is wrong: It only removes duplicate sends within a time window; it doesn't stop redelivery to consumers. Instead: Deduplicate in the consumer.
  • Mistake: Leaving MaxDeliveryCount at a value nobody chose, or setting it very high. Why it is wrong: Too low dead-letters messages during a short outage; too high keeps a poison message retrying for hours and burning capacity. Instead: Choose it from your retry policy (for example 5–10 with exponential backoff), and alert when anything is dead-lettered.
  • Mistake: Ignoring the dead-letter queue. Why it is wrong: Poison messages pile up unseen, and for payments that means unsettled money. Instead: Alert on DLQ count and age, record the dead-letter reason, and keep a documented, tested replay process.
  • Mistake: Watching only queue depth. Why it is wrong: A few stuck or repeatedly abandoned messages hide in a small queue while a merchant waits days to be paid. Instead: Monitor oldest-message age and delivery counts, and alert when a message is older than your settlement SLA.
  • Mistake: ShutdownTimeout equal to or longer than terminationGracePeriodSeconds. Why it is wrong: The kubelet sends SIGKILL mid-transaction. Instead: Keep the grace period comfortably longer than the host timeout.
  • Mistake: A shell-form Docker entrypoint. Why it is wrong: SIGTERM goes to the shell and .NET never starts shutting down, so every stop takes the full grace period and ends in SIGKILL. Instead: Use exec form, ENTRYPOINT ["dotnet", "Worker.dll"].
  • Mistake: Setting maxReplicaCount from the queue size alone. Why it is wrong: Replicas times concurrency can overwhelm the database or a rate-limited payment API. Instead: Derive the maximum from the downstream budget.
  • Mistake: A large PrefetchCount with slow handlers. Why it is wrong: Prefetched messages' locks expire while they wait in the buffer, causing redelivery and inflated delivery counts. Instead: Prefetch 0 or a small number for slow handlers.
  • Mistake: Scaling out a consumer that relies on ordering. Why it is wrong: Competing consumers process messages out of order. Instead: Use sessions keyed by the entity that needs order.

πŸ› Senior insight: trade-offs

A queue worker on Kubernetes is a distributed system even when it's one small service. The platform will stop it at the worst moment, the broker will redeliver, and autoscaling will multiply your concurrency. The senior design accepts all three and makes them harmless: shutdown that drains, handlers that are idempotent, and scaling capped by what downstream systems can take.

Option When it fits Cost When not to
AKS + KEDA You already run AKS, need fine control Cluster operations, KEDA install Small teams without Kubernetes skills
Azure Container Apps scale rules Managed, scale to zero, built-in KEDA Less control over the platform Special networking or node requirements
Azure Functions Service Bus trigger Simple handlers, consumption billing Execution limits, less control over shutdown Long transactions, complex hosting
A single always-on VM worker Very low volume, strict ordering No elasticity, manual patching Spiky workloads like month-end

Measure: queue depth and oldest message age, processed and failed per minute, duplicate rate (inbox key violations), DLQ count, and replicas over time. For payments in Australia, also keep an audit trail of each settlement and its message id, because reconciliation and AUSTRAC or scheme audits will ask what happened to every message.

πŸ”— Follow-ups the interviewer may ask

  1. When: Candidate mentions the worker crashing or stopping silently. Why: Checks BackgroundService failure handling and observability.
    How to answer

    These are three different failures. Stopped silently: an exception escaped ExecuteAsync, which ends the loop. With BackgroundServiceExceptionBehavior.Ignore, or a catch that swallows and exits, the app keeps serving while the worker is dead. If nothing throws at all, an await without a token may be hung. Blocks start-up: slow work in StartAsync, or before .NET 10 synchronous code before the first await in ExecuteAsync, which ran on the start-up path. Scoped from singleton: hosted services are singletons, so inject IServiceScopeFactory and create a scope per message instead of injecting a DbContext. Then make the worker observable: a heartbeat behind a health check, metrics for processed, failed and lag, and alerts on all three.

    The principle: a background service must either work or fail loudly.

  2. When: Candidate mentions SIGTERM and termination grace periods. Why: Checks graceful shutdown for HTTP APIs as well as workers.
    How to answer

    A burst of 502s on every rollout is almost always a shutdown or start-up race, not a code bug. On termination, Kubernetes sends SIGTERM to the container and removes the pod from the Service endpoints at the same time, so the ingress keeps sending requests for a few seconds to a process that is closing. I fix it in layers, with numbers that must add up: a preStop sleep (about 10 s) so routing updates first; HostOptions.ShutdownTimeout sized from the measured p99.9 request duration (say 15 s) so in-flight requests drain; and terminationGracePeriodSeconds larger than both together (35 s). Then readiness probes that only pass when the app is warm and fail once ApplicationStopping fires, separate from liveness, plus maxUnavailable: 0. I also check keep-alive timeouts: if Kestrel closes idle connections before the proxy does, the proxy reuses a dead connection and returns 502. The trade-off is slightly slower deployments for zero dropped requests.

  3. When: Candidate mentions limiting concurrency against downstream systems. Why: Checks backpressure design across the system.
    How to answer

    Backpressure is a way for a slow consumer to make producers slow down, instead of letting work pile up until something breaks. The four strategies are block (producer waits), bounded buffer, drop (shed lower-value work) and reject (tell the caller to retry later). In .NET: bounded Channel<T> with WriteAsync (block), BoundedChannelFullMode.DropOldest (drop), TryWrite plus HTTP 429/503 with Retry-After (reject), pull-based IAsyncEnumerable<T>, and broker settings such as prefetch count and max concurrent calls so consumers only take what they can process. Every boundary needs a chosen strategy and metrics for queue depth and age.

πŸ›  Real-world problems: how you handle them

Duplicate payment settlements during rolling deployments of a queue worker
Situation
A [payments settlement] worker was moved from [a Windows service on a VM] to [AKS], consuming Azure Service Bus at about [60,000] messages a day, with spikes to [180,000] at month-end. Each message created a settlement and called [the payment provider's] API.
Signals
Finance reconciliation found [14] duplicate settlements in the first week, all at times matching deployments. Pods took the full 30 seconds to terminate and logs showed no shutdown messages. During month-end the provider returned HTTP 429s once the pod count passed [15].
Investigation
Matched duplicate settlements' message ids to Service Bus `DeliveryCount` values of 2, confirming redelivery. Found the Dockerfile used a shell-form `ENTRYPOINT`, so SIGTERM never reached .NET and pods were SIGKILLed mid-processing. Reviewed the handler: no idempotency check, and no idempotency key sent to the provider. For the 429s, multiplied max replicas (30) by `MaxConcurrentCalls` (16) = 480 concurrent calls against a provider limit of [100 per second].
Resolution
Immediate: paused deployments during business hours and manually reversed the duplicates. Real fix: exec-form entrypoint, `ShutdownTimeout` 25 s with `terminationGracePeriodSeconds` 40 s, `StopProcessingAsync` on shutdown with abandon for unfinished messages. Added an inbox table written in the same transaction as the settlement, and sent the message id as the provider's idempotency key. Reduced `MaxConcurrentCalls` to 8 and capped KEDA `maxReplicaCount` at 12.
Prevention
An integration test that kills the pod mid-message and asserts exactly one settlement. A daily reconciliation job comparing settlements with message ids. Alerts on DLQ count, inbox key violations (the duplicate rate) and provider 429s. A container checklist item: exec-form entrypoint and the shutdown timeout ordering.

How to tell it (STAR)

**S:** We moved our [payments settlement] worker from [a VM] to [AKS], and in the first week finance found [14] duplicate settlements, all during deployments. **T:** I owned the fix, because duplicates meant [paying merchants twice] and a reconciliation headache. **A:** I matched the duplicates to Service Bus delivery counts of 2 and found pods were being SIGKILLed mid-message: our shell-form Dockerfile entrypoint swallowed SIGTERM. I fixed the entrypoint and the shutdown timeouts, drained and abandoned messages on shutdown, and made the handler idempotent with an inbox table in the same transaction plus idempotency keys to the provider. I also capped KEDA replicas from the provider's rate limit after month-end 429s. **R:** Duplicates went to zero over [the next six months], month-end backlogs cleared in [35 minutes] instead of [4 hours], and we could deploy during business hours again.

↩ Usually asked after

More in Real-Time and Special APIs

Last updated 23 Nov 2026.

🌐 Sangam's Webring

βͺ Previous 🏠 Main Next ⏩
πŸ’¬ Chat with me