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.
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.
"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. OurServiceBusProcessorhandler 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 setHostOptions.ShutdownTimeoutto 25 seconds andterminationGracePeriodSecondsto 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 aProcessedMessagestable 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-servicebusscaler: 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 timesMaxConcurrentCallsof 8 is 160 concurrent calls to the payment provider, which had a limit of [100 requests per second]. So we cappedmaxReplicaCountfrom that budget, not from the queue."
| 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) |
| 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 |
| 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 |
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.
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
stoppingToken β drain β abandon, with timeout orderingRed flags
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).
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.
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.
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.
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.
kubectl delete pod, and check in the logs that in-flight messages complete or are abandoned before exit.kubectl get hpa -w.MaxDeliveryCount.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)
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.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.ENTRYPOINT ["dotnet", "Worker.dll"].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.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.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.
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.
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.
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.
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.
Last updated 23 Nov 2026.