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

📚 Interview question

Your BackgroundService has problems in production: it stopped processing messages hours ago with no alert, a new version blocks the app from starting, and it throws 'Cannot consume scoped service from singleton'. How do you diagnose and fix each one, and how do you make background services observable?

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.

Mid-Level Debugging Intermediate aspnet-core background-service debugging dependency-injection health-checks hosted-services

🎯 Key points

  • An unhandled exception ends ExecuteAsync: StopHost (default since .NET 6, configurable) stops the app, Ignore leaves it running with the worker silently dead
  • Catch and log inside the loop; let only fatal errors escape; on fatal errors call IHostApplicationLifetime.StopApplication so the orchestrator restarts the pod
  • Start-up blocking: slow StartAsync, or (before .NET 10) synchronous code before the first await in ExecuteAsync; .NET 10 starts ExecuteAsync with Task.Run, but blocking code still holds a ThreadPool thread
  • 'Cannot consume scoped service from singleton' = captive dependency; inject IServiceScopeFactory and CreateAsyncScope per message
  • A hang (no exception) usually means an await without the stopping token, a blocking call, or a deadlock: capture a dump with dotnet-dump and look at the stacks
  • Observability: heartbeat timestamp behind a health check, OpenTelemetry metrics (processed, failed, duration, queue lag) exported to Azure Monitor or Prometheus, structured logs with the message id
  • Liveness probe based on the worker heartbeat lets Kubernetes restart a stuck worker; test the probe and alerts in staging by pausing the worker
  • Long-running items need a per-item timeout (linked CancellationTokenSource) and lock renewal or checkpointing

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

🗣 Full answer (senior)

How I would answer this in an interview

"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 ExecuteAsync ends the task. Since .NET 6 the default behaviour is StopHost, which logs BackgroundService failed and shuts the whole app down. That is loud, and in Kubernetes the pod restarts. If someone set BackgroundServiceExceptionBehavior.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: an await on something without the stopping token, for example a queue receive with no timeout. I'd take dotnet-dump collect and run dumpasync or clrstack -all to 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, BackgroundService called ExecuteAsync directly, so a synchronous loop like while (true) { Thread.Sleep... } before the first real await blocked start-up forever. .NET 10 runs the whole method through Task.Run, but I still keep StartAsync quick. Cannot consume scoped service from singleton: hosted services are singletons, and scope validation in Development catches a DbContext injected into the constructor. The fix is IServiceScopeFactory with CreateAsyncScope() per message, so each message gets a fresh DbContext and 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 to cause

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

Making it observable

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

Production example

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.

🔍 What the interviewer is checking

Checks whether the candidate can diagnose the common BackgroundService failure modes and design workers that are observable and fail loudly.

Green flags

  • Knows BackgroundServiceExceptionBehavior and the default StopHost
  • Puts error handling per item inside the loop
  • Explains captive dependencies and uses IServiceScopeFactory
  • Knows the start-up blocking issue and the .NET 10 change
  • Adds heartbeat health checks, metrics and lag alerts; uses dotnet-dump for hangs

Red flags

  • Sets Ignore or disables scope validation as the fix
  • Injects DbContext directly into the worker
  • No way to tell whether the worker is alive

📚 Learn in depth

1. What happens when ExecuteAsync throws

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

2. Start-up blocking, before and after .NET 10

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

3. Captive dependencies

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.

4. Finding a hang

  1. dotnet-dump collect -p <pid> (or kubectl debug with a diagnostics sidecar).
  2. dotnet-dump analyze → dumpasync shows async state machines and what they await; clrstack -all shows blocked threads.
  3. Look for ServiceBusReceiver.ReceiveMessageAsync with no token, .Result or .Wait() calls, or a SemaphoreSlim.WaitAsync that is never released.

5. A heartbeat health check

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.

Try it yourself

  1. Throw from ExecuteAsync with each BackgroundServiceExceptionBehavior value and watch the host's reaction and logs.
  2. Write a synchronous loop before the first await and run it on .NET 8 and on .NET 10; compare whether Kestrel starts.
  3. Inject a DbContext into a hosted service, run in Development and then in Production, and note that only Development throws. Enable ValidateScopes in Production config.
  4. Make the loop await Task.Delay(Timeout.Infinite) without a token, take a dump and find it with dumpasync.
  5. Add the heartbeat health check from the code example and watch /healthz/live go unhealthy when you pause the loop.

💻 Code

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

⚠ Common mistakes

  • Mistake: Setting 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.
  • Mistake: A try/catch around the whole loop that logs and returns. Why it is wrong: One transient error ends processing for good. Instead: Put the try/catch inside the loop, around each item.
  • Mistake: Injecting scoped services into the worker's constructor. Why it is wrong: A captive DbContext lives for days, grows its change tracker, serves stale data and isn't thread-safe. Instead: IServiceScopeFactory.CreateAsyncScope() per message.
  • Mistake: Turning scope validation off to get past the start-up error. Why it is wrong: Validation is only on by default in Development. Turning it off there means the captive dependency ships to Production unnoticed, where it shows up weeks later as memory growth, stale reads or DbContext concurrency exceptions that are hard to trace back. Instead: Fix the lifetime, and enable ValidateScopes and ValidateOnBuild in every environment.
  • Mistake: Awaiting receives or HTTP calls without a token or timeout. Why it is wrong: The worker can hang forever with no exception and no log. Instead: Pass stoppingToken and use bounded waits.
  • Mistake: Slow work in 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.
  • Mistake: Assuming .NET 10 makes blocking code harmless. Why it is wrong: 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.
  • Mistake: Having no health or metrics for the worker. Why it is wrong: You find out from users hours later. Instead: Heartbeat health check, processed and failed counters, queue lag alerts.
  • Mistake: Relying on .NET 10 to surface start-up exceptions from 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.

🏛 Senior insight: trade-offs

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.

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions unhandled exceptions in background services. Why: Checks the wider global exception-handling strategy across the app.
    How to answer

    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.

  2. When: Candidate mentions the worker hanging without an exception. Why: Checks deadlock diagnosis with dumps.
    How to answer

    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.

  3. When: Candidate mentions .Result or .Wait() inside the worker. Why: Checks sync-over-async knowledge.
    How to answer

    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.

🛠 Real-world problems: how you handle them

Invoice sync worker silently dead for six hours after a SQL failover
Situation
An ASP.NET Core API on [Azure App Service] hosted a `BackgroundService` that synced invoices from a Service Bus queue to [the finance system], about [20,000] invoices a day. End-of-month billing depended on it.
Signals
Finance reported that invoices created after [9:40 am] were missing. The API was healthy, all health checks were green, and there were no alerts. The Service Bus queue showed [11,800] active messages and growing. The last log line from the worker was a `SqlException` timeout at 9:40.
Investigation
Searched Application Insights traces for the worker category and found the exception followed by no further logs. Read the code: the whole loop was wrapped in one try/catch that logged and returned. Startup config also set `BackgroundServiceExceptionBehavior.Ignore` from an earlier incident. Checked Azure SQL activity and confirmed a planned failover at 9:40 that caused a few seconds of timeouts.
Resolution
Immediate: restarted the App Service instance, so the worker started again and cleared the backlog in [about 15 minutes]. Real fix: moved the try/catch inside the loop around each message with Service Bus abandon and `MaxDeliveryCount` dead-lettering, added EF Core `EnableRetryOnFailure`, restored `StopHost`, used a scope per message, and added a heartbeat health check plus processed and failed counters.
Prevention
Alerts on queue depth growth and on the worker's processed-per-minute dropping to zero during business hours. The heartbeat health check wired to the platform health probe so a stuck worker is restarted. A team code-review checklist item for hosted services (per-item error handling, scopes, token use). A chaos test in staging that triggers a SQL failover.

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.

↩ Usually asked after

More in Real-Time and Special APIs

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me