Diagnosing broken BackgroundService implementations: silent failures and BackgroundServiceExceptionBehavior, start-up blocking (including pre-.NET 10 synchronous ExecuteAsync and slow StartAsync), captive dependencies and IServiceScopeFactory, hangs from ignored cancellation, and health checks and metrics for workers.
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.
"I'd take them one at a time, because the causes are different. Stopped with no alert: first I look at the logs around the last processed message. An exception escaping
ExecuteAsyncends the task. Since .NET 6 the default behaviour isStopHost, which logsBackgroundService failedand shuts the whole app down. That is loud, and in Kubernetes the pod restarts. If someone setBackgroundServiceExceptionBehavior.Ignore, or wrapped the loop in a try/catch that logs and returns, the API keeps serving and health checks stay green while the worker is dead. If there's no exception at all, I suspect a hang: anawaiton something without the stopping token, for example a queue receive with no timeout. I'd takedotnet-dump collectand rundumpasyncorclrstack -allto see where it's stuck.Blocks start-up: hosted services start before Kestrel listens. Slow work in
StartAsync, such as warming a cache or migrating a database, delays readiness. And before .NET 10,BackgroundServicecalledExecuteAsyncdirectly, so a synchronous loop likewhile (true) { Thread.Sleep... }before the first realawaitblocked start-up forever. .NET 10 runs the whole method throughTask.Run, but I still keepStartAsyncquick. Cannot consume scoped service from singleton: hosted services are singletons, and scope validation in Development catches aDbContextinjected into the constructor. The fix isIServiceScopeFactorywithCreateAsyncScope()per message, so each message gets a freshDbContextand change tracker.For example, at [company] our [invoice sync] worker died after a transient SQL timeout, and nobody noticed for [six hours] because the service was configured to ignore exceptions. I changed it to catch per message with a retry and a dead-letter, added a heartbeat timestamp exposed through a health check used by the liveness probe, and added a metric for queue lag. [The next failure paged us within five minutes.] The senior rule is that background work must fail loudly or recover; silently dead is the worst state."
| Symptom | Likely cause | Confirm with | Fix |
|---|---|---|---|
| Worker stopped, app still up, no errors after a point | Exception escaped, behaviour Ignore, or a catch that exits the loop |
Logs around the last message; config for BackgroundServiceExceptionBehavior |
Catch per item inside the loop; keep StopHost for fatal errors |
| App exits shortly after start with "BackgroundService failed" | Exception in ExecuteAsync with StopHost |
Host logs | Fix the bug; add retries for transient errors |
| Worker stopped, no exception, CPU idle | Hung await without timeout or token; deadlock |
dotnet-dump + dumpasync, clrstack -all |
Pass tokens, add timeouts, remove sync-over-async |
| App never becomes ready | Slow StartAsync, or sync code before first await (pre-.NET 10) |
Start-up logs with timestamps; dump during start-up | Move work into ExecuteAsync; upgrade to .NET 10; readiness health check |
Cannot consume scoped service ... from singleton |
Scoped service injected into a hosted service | Exception at start-up (Development) | IServiceScopeFactory and a scope per unit of work |
| Stale data, growing memory | One DbContext reused for hours (captive dependency in Production) |
Memory dump shows a huge change tracker | Scope per message |
| Shutdown takes 30 s then messages are lost | stoppingToken ignored |
Logs on SIGTERM | Honour the token, finish or abandon the current message cleanly |
| Signal | How |
|---|---|
| Liveness | Worker updates a LastHeartbeat timestamp; a health check fails if it is older than N intervals |
| Throughput | Counter<long> for processed and failed through System.Diagnostics.Metrics |
| Lag | Queue depth or oldest message age (Service Bus, Kafka consumer lag) |
| Logs | Structured, with the message id and a scope per message |
| Alerts | Heartbeat stale, failure rate above X%, lag growing for 10 minutes |
After adding a heartbeat health check, per-message error handling and a lag alert to our [invoice sync] worker, a later [database failover] showed up as a page within [5 minutes]. The worker recovered by itself with retries, and the backlog of [12,000] messages cleared in [8 minutes] instead of being discovered the next morning.
Checks whether the candidate can diagnose the common BackgroundService failure modes and design workers that are observable and fail loudly.
Green flags
BackgroundServiceExceptionBehavior and the default StopHostIServiceScopeFactoryRed flags
Ignore or disables scope validation as the fixDbContext directly into the workerExecuteAsync throws
│
▼
Host observes the faulted _executeTask
├─ BackgroundServiceExceptionBehavior.StopHost (default since .NET 6)
│ └─ logs "BackgroundService failed" (critical) → StopApplication() → process exits → orchestrator restarts
└─ BackgroundServiceExceptionBehavior.Ignore
└─ logs the error, the rest of the app keeps running, the worker is gone for good
Before .NET 6 the behaviour was effectively Ignore, and the exception could go unlogged, which is why older codebases often have silent dead workers.
.NET 8/9: StartAsync → ExecuteAsync() called directly
├─ code before first incomplete await runs HERE, on the start-up path
└─ if that is a synchronous loop, start-up never finishes
.NET 10: StartAsync → Task.Run(() => ExecuteAsync())
└─ start-up continues immediately
The .NET 10 change also means exceptions thrown at the very start of ExecuteAsync no longer surface during StartAsync. If you relied on that to fail fast on bad configuration, validate in the constructor or with ValidateOnStart instead.
singleton InvoiceSyncWorker
└─ InvoiceDbContext (scoped) ← captured once, lives for days
├─ change tracker grows with every entity read
├─ stale data, never refreshed
└─ not thread-safe if processing in parallel
In Development, ValidateScopes and ValidateOnBuild are on and throw Cannot consume scoped service 'X' from singleton 'Y'. In Production they are off by default, so the bug ships quietly unless you turn validation on.
dotnet-dump collect -p <pid> (or kubectl debug with a diagnostics sidecar).dotnet-dump analyze → dumpasync shows async state machines and what they await; clrstack -all shows blocked threads.ServiceBusReceiver.ReceiveMessageAsync with no token, .Result or .Wait() calls, or a SemaphoreSlim.WaitAsync that is never released.The worker records DateTimeOffset.UtcNow after each loop iteration (even when the queue is empty). A health check reports Unhealthy if the heartbeat is older than, say, three intervals. Map that check to the liveness endpoint, so Kubernetes restarts a stuck worker, and keep readiness for dependencies.
ExecuteAsync with each BackgroundServiceExceptionBehavior value and watch the host's reaction and logs.await and run it on .NET 8 and on .NET 10; compare whether Kestrel starts.DbContext into a hosted service, run in Development and then in Production, and note that only Development throws. Enable ValidateScopes in Production config.Task.Delay(Timeout.Infinite) without a token, take a dump and find it with dumpasync./healthz/live go unhealthy when you pause the loop.A worker that fails loudly when it must, recovers when it can, and can be monitored.
// Program.cs (.NET 10)
using System.Diagnostics.Metrics;
using Microsoft.Extensions.Diagnostics.HealthChecks;
var builder = WebApplication.CreateBuilder(args);
// Keep the default (StopHost) explicit so nobody "fixes" crashes by hiding them.
builder.Services.Configure<HostOptions>(o =>
o.BackgroundServiceExceptionBehavior = BackgroundServiceExceptionBehavior.StopHost);
// Catch captive dependencies in every environment, not just Development.
builder.Host.UseDefaultServiceProvider(o => { o.ValidateScopes = true; o.ValidateOnBuild = true; });
builder.Services.AddDbContext<InvoiceDb>();
builder.Services.AddSingleton<IInvoiceQueue, InMemoryInvoiceQueue>();
builder.Services.AddSingleton<WorkerHeartbeat>();
builder.Services.AddHostedService<InvoiceSyncWorker>();
builder.Services.AddHealthChecks()
.AddCheck<WorkerHeartbeatCheck>("invoice-worker", tags: ["live"]);
var app = builder.Build();
app.MapHealthChecks("/healthz/live", new() { Predicate = c => c.Tags.Contains("live") });
app.Run();
public sealed class WorkerHeartbeat { public DateTimeOffset Last { get; set; } = DateTimeOffset.UtcNow; }
public sealed class WorkerHeartbeatCheck(WorkerHeartbeat hb) : IHealthCheck
{
public Task<HealthCheckResult> CheckHealthAsync(HealthCheckContext context, CancellationToken ct = default)
{
var age = DateTimeOffset.UtcNow - hb.Last;
return Task.FromResult(age < TimeSpan.FromMinutes(2)
? HealthCheckResult.Healthy($"Last loop {age.TotalSeconds:N0}s ago")
: HealthCheckResult.Unhealthy($"Worker stuck: last loop {age.TotalSeconds:N0}s ago"));
}
}
public sealed class InvoiceSyncWorker(
IServiceScopeFactory scopeFactory, // not InvoiceDb: hosted services are singletons
IInvoiceQueue queue,
WorkerHeartbeat heartbeat,
IMeterFactory meters,
ILogger<InvoiceSyncWorker> logger) : BackgroundService
{
private readonly Counter<long> _processed = meters.Create("Invoices.Worker").CreateCounter<long>("invoices.processed");
private readonly Counter<long> _failed = meters.Create("Invoices.Worker").CreateCounter<long>("invoices.failed");
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
heartbeat.Last = DateTimeOffset.UtcNow; // updated even when the queue is empty
// Bounded wait with the stopping token: never an await that can hang forever.
var message = await queue.ReceiveAsync(TimeSpan.FromSeconds(10), stoppingToken);
if (message is null) continue;
using var _ = logger.BeginScope(new Dictionary<string, object> { ["InvoiceId"] = message.InvoiceId });
try
{
await using var scope = scopeFactory.CreateAsyncScope(); // fresh DbContext per message
var db = scope.ServiceProvider.GetRequiredService<InvoiceDb>();
await db.SyncAsync(message.InvoiceId, stoppingToken);
await queue.CompleteAsync(message, stoppingToken);
_processed.Add(1);
}
catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested)
{
await queue.AbandonAsync(message, CancellationToken.None); // redeliver after restart
break;
}
catch (Exception ex)
{
// Per-message failure: log, count, abandon for retry; the loop keeps running.
_failed.Add(1);
logger.LogError(ex, "Failed to sync invoice");
await queue.AbandonAsync(message, stoppingToken);
}
}
}
}
public sealed record InvoiceMessage(Guid InvoiceId);
public interface IInvoiceQueue
{
Task<InvoiceMessage?> ReceiveAsync(TimeSpan wait, CancellationToken ct);
Task CompleteAsync(InvoiceMessage m, CancellationToken ct);
Task AbandonAsync(InvoiceMessage m, CancellationToken ct);
}
public sealed class InMemoryInvoiceQueue : IInvoiceQueue
{
public async Task<InvoiceMessage?> ReceiveAsync(TimeSpan wait, CancellationToken ct) { await Task.Delay(wait, ct); return null; }
public Task CompleteAsync(InvoiceMessage m, CancellationToken ct) => Task.CompletedTask;
public Task AbandonAsync(InvoiceMessage m, CancellationToken ct) => Task.CompletedTask;
}
public sealed class InvoiceDb : Microsoft.EntityFrameworkCore.DbContext
{
public Task SyncAsync(Guid id, CancellationToken ct) => Task.CompletedTask;
}
BackgroundServiceExceptionBehavior.Ignore to stop the app crashing. Why it is wrong: The crash becomes a silently dead worker while health checks stay green. Instead: Keep StopHost, handle per-item errors inside the loop, and let the orchestrator restart on fatal errors.DbContext lives for days, grows its change tracker, serves stale data and isn't thread-safe. Instead: IServiceScopeFactory.CreateAsyncScope() per message.DbContext concurrency exceptions that are hard to trace back. Instead: Fix the lifetime, and enable ValidateScopes and ValidateOnBuild in every environment.stoppingToken and use bounded waits.StartAsync, or sync loops before the first await on older .NET. Why it is wrong: The app never becomes ready and probes kill it. Instead: Do the work in ExecuteAsync, report readiness through a health check.Task.Run stops it delaying start-up, but a blocking loop still occupies a ThreadPool thread for its lifetime and can contribute to starvation. Instead: Keep the loop truly async.ExecuteAsync. Why it is wrong: With Task.Run, early exceptions no longer surface during StartAsync; they fault the background task instead. Instead: Validate configuration in the constructor or with ValidateOnStart.The design goal for a background service is "work or fail loudly". Silent failure is the worst outcome, because the business discovers it, usually from a customer. That means a clear error policy per item (retry, dead-letter, skip), a process-level policy for fatal errors (StopHost, then the orchestrator restarts), and signals that distinguish "idle" from "stuck".
| Failure | Policy | Mechanism |
|---|---|---|
| Transient (timeout, 503) | Retry with backoff | Polly or the broker's redelivery |
| Poison message | Dead-letter after N attempts | Service Bus MaxDeliveryCount, a DLQ alert |
| Fatal (bad config, lost credentials) | Stop the process | StopHost or StopApplication(), liveness restart |
| Stuck (no progress) | Restart | Heartbeat-based liveness probe |
| Long-running item (minutes) | Per-item timeout plus checkpointing | Linked CancellationTokenSource.CancelAfter, Service Bus lock renewal (MaxAutoLockRenewalDuration), save progress so a restart resumes |
Long or heavy items. Measure the p99 item duration first (a histogram metric). Set the per-item timeout above that, and the heartbeat threshold above the timeout, so a slow item isn't mistaken for a stuck worker. If items take longer than ShutdownTimeout, either make them resumable or move them to a dedicated worker or job platform with a longer grace period.
What to monitor (OpenTelemetry metrics to Azure Monitor or Prometheus): items processed and failed per minute, item duration histogram, queue depth and oldest message age, dead-letter count, and time since last heartbeat. Graph processed per minute next to queue depth: a flat processed line with a rising queue is the alert. Before production, rehearse it in staging: pause the worker, kill the database connection, and confirm the probe restarts the pod and the alerts fire.
In ASP.NET Core, register AddProblemDetails(), one or more IExceptionHandler implementations (.NET 8+) with AddExceptionHandler<T>(), and app.UseExceptionHandler() early in the pipeline. Handlers log once and map known exceptions to the right status code and an RFC 9457 ProblemDetails body, and never leak stack traces in production. For the process as a whole, AppDomain.CurrentDomain.UnhandledException is a last-chance notification: you can log and flush, but the process still terminates. TaskScheduler.UnobservedTaskException fires when a faulted task that nobody awaited is garbage-collected; it does not crash the process by default. In a BackgroundService, an unhandled exception in ExecuteAsync stops the host by default (.NET 6+). async void exceptions go to the synchronisation context and usually crash the process, so avoid async void except for event handlers.
A deadlock is a cycle where each participant waits for something another holds, so nothing progresses and CPU drops to zero. In .NET the common kinds are lock-ordering deadlocks (thread A holds lock 1 and wants lock 2, thread B the reverse), sync-over-async deadlocks on a SynchronizationContext, non-reentrant SemaphoreSlim re-entry, and tasks that are never completed. I diagnose with a memory dump: dotnet-dump collect, then syncblk to see Monitor owners and waiters, clrstack -all or parallelstacks for thread stacks, and dumpasync for stuck async chains. Fixes are a consistent lock order, shorter locks with no callouts, timeouts, and async all the way.
Sync-over-async is synchronously blocking on asynchronous work: .Result, .Wait(), GetAwaiter().GetResult() or Task.WaitAll. It holds a thread for the whole operation, causes ThreadPool starvation on servers and deadlocks under a SynchronizationContext. It sneaks in through constructors, DI factory lambdas, property getters, Dispose, lock blocks, synchronous interfaces (IComparer, old filters), static initialisers and "quick fixes" in legacy code. Remove it by making the call chain async, using async factory methods or lazy async initialisation, IAsyncDisposable, hosted-service warm-up, and async-capable interfaces. Where a sync boundary is unavoidable (for example a legacy interface), keep it at the edge and document it.
How to tell it (STAR)
**S:** We had an invoice sync worker inside our API processing about [20,000] invoices a day, and at [end of month] finance told us nothing had synced since [9:40 am]. **T:** I needed to restore processing quickly and make sure it couldn't fail silently again. **A:** Application Insights showed a SQL timeout at 9:40 and then silence. The code had one try/catch around the whole loop that logged and returned, and the host was set to ignore background exceptions, so the API stayed green while the worker was dead. I restarted it to clear the backlog, then moved error handling to each message with abandon and dead-lettering, added EF Core retries, restored StopHost, and added a heartbeat health check and throughput metrics with alerts. **R:** The backlog of about [11,800] cleared in [15 minutes], and when the next [failover] happened the worker retried on its own and we were alerted within [5 minutes], with no data missed.
Last updated 23 Nov 2026.