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

📚 Interview question

What are hosted services in .NET? Explain IHostedService, BackgroundService and the Worker Service template, the lifecycle (StartAsync, ExecuteAsync, StopAsync), what happens at start-up and shutdown, and when you would use a worker instead of running the work inside your web API.

Explains IHostedService and BackgroundService in .NET 10: registration with AddHostedService, the start-up and shutdown order, ExecuteAsync and its stopping token, the .NET 10 change that runs all of ExecuteAsync in the background, IHostedLifecycleService, the Worker Service template, and in-process versus separate workers.

Junior Theory Intermediate aspnet-core background-service generic-host hosted-services worker-service

🎯 Key points

  • IHostedService has StartAsync and StopAsync; AddHostedService<T>() always registers it as a singleton, and the host starts services in registration order
  • BackgroundService implements IHostedService and gives you one long-running ExecuteAsync(CancellationToken stoppingToken)
  • .NET 10 (documented breaking change): BackgroundService starts ExecuteAsync with Task.Run, so code before the first await no longer delays start-up; blocking calls inside it still tie up a ThreadPool thread
  • IHostedLifecycleService (.NET 8+) extends IHostedService with StartingAsync, StartedAsync, StoppingAsync and StoppedAsync for precise lifecycle hooks such as warm-up
  • In ASP.NET Core, hosted services start before the server starts accepting requests; StartAsync must be quick
  • stoppingToken is cancelled on shutdown (SIGTERM, Ctrl+C); StopAsync waits up to HostOptions.ShutdownTimeout (30 s default)
  • Hosted services are singletons: create a scope with IServiceScopeFactory to use scoped services such as DbContext
  • Worker Service template = Generic Host without Kestrel; choose a separate worker, Quartz.NET/Hangfire or Azure Functions when work needs its own scaling, schedules, persistence or scale to zero

⏱ 30-second answer

A hosted service is a class the .NET Generic Host starts and stops with the application. IHostedService gives you StartAsync and StopAsync. BackgroundService is the base class most people use: you override one method, ExecuteAsync(CancellationToken stoppingToken), and loop until the token is cancelled at shutdown. You register it with AddHostedService<T>(), as a singleton, so you use IServiceScopeFactory to get scoped services like a DbContext. In .NET 10 the whole of ExecuteAsync runs on a background task, so it doesn't delay start-up. On shutdown the host cancels the token and waits up to HostOptions.ShutdownTimeout (30 seconds by default). The Worker Service template is the same host without a web server, for queue consumers and scheduled jobs.

The trade-off: running inside your API is simple, but a separate worker scales and fails independently.

🗣 Full answer (senior)

How I would answer this in an interview

"A hosted service is anything that should run for the lifetime of the app, not per request: consuming a queue, refreshing a cache, sending scheduled emails. The contract is IHostedService with StartAsync and StopAsync. The host calls StartAsync on each one in registration order during start-up, and StopAsync in reverse order on shutdown. In practice I derive from BackgroundService, which implements that interface for me. I override ExecuteAsync(CancellationToken stoppingToken) and write a loop that runs until the token is cancelled.

There are a few lifecycle details that matter. In ASP.NET Core, hosted services start before Kestrel starts accepting requests, so a slow StartAsync delays your app becoming ready. Before .NET 10, the synchronous part of ExecuteAsync, everything before the first await, ran on the start-up path and could block the whole app. In .NET 10 the host runs all of ExecuteAsync as a background task, so that trap is gone. If you genuinely need code to run during start-up, you put it in StartAsync or use IHostedLifecycleService, which adds StartingAsync, StartedAsync, StoppingAsync and StoppedAsync hooks. On shutdown, when Kubernetes sends SIGTERM for example, the host cancels stoppingToken and waits up to HostOptions.ShutdownTimeout, 30 seconds by default, for every service to finish.

Hosted services are registered as singletons, so I never inject a DbContext directly. I inject IServiceScopeFactory and create a scope per unit of work. The Worker Service template, dotnet new worker, is the same Generic Host without Kestrel, which I use when the background work should scale or fail separately from the API. The mistake I see is fire-and-forget Task.Run in a controller instead of a proper hosted service with a queue."


The pieces

Type What you implement Use it for
IHostedService StartAsync, StopAsync Short start-up/shutdown work, or full control
BackgroundService ExecuteAsync(stoppingToken) Long-running loops: queue consumers, polling, timers
IHostedLifecycleService (.NET 8+) Adds StartingAsync, StartedAsync, StoppingAsync, StoppedAsync Work that must run at a precise lifecycle stage, such as a warm-up
Worker Service template Program.cs with Host.CreateApplicationBuilder and a Worker : BackgroundService A process with no HTTP server

Lifecycle order (ASP.NET Core, .NET 10)

Phase What happens
app.Run() Host starts
Start Each hosted service's StartAsync in registration order; BackgroundService starts ExecuteAsync as a background task
Server Kestrel starts listening; IHostApplicationLifetime.ApplicationStarted fires
Shutdown signal SIGTERM, Ctrl+C or StopApplication(); ApplicationStopping fires
Stop Kestrel stops accepting new requests and drains; StopAsync on services in reverse order cancels stoppingToken
Timeout After ShutdownTimeout (30 s) the host stops waiting

In-process or separate worker?

In the web API Separate Worker Service
Small, quick jobs (cache refresh, cleanup) Heavy or long jobs (imports, PDF generation)
Same scaling as the API is fine Needs its own scaling, for example on queue length with KEDA
A crash should take the API down anyway Failures must not affect request handling

Production example

In a [booking] API we had a BackgroundService that expired unpaid reservations every minute: [about 40 lines], using a PeriodicTimer and a scope per run. When we added PDF ticket generation, which used [up to 1 GB] of memory per batch, we moved it to a separate Worker Service consuming a queue, so a spike in PDF work could no longer slow down API requests.

🔍 What the interviewer is checking

Checks that the candidate knows how hosted services fit into the Generic Host lifecycle and can write a safe BackgroundService.

Green flags

  • Explains StartAsync/ExecuteAsync/StopAsync and the start-up and shutdown order
  • Uses IServiceScopeFactory for scoped services
  • Honours stoppingToken and knows ShutdownTimeout
  • Knows what happens when ExecuteAsync throws
  • Can say when to move work to a separate worker

Red flags

  • Injects DbContext directly into a hosted service
  • Uses fire-and-forget Task.Run for background work
  • Unaware that every replica runs the hosted service

📚 Learn in depth

1. How the host runs hosted services

Host.StartAsync
  ├─ IHostedLifecycleService.StartingAsync   (all)
  ├─ IHostedService.StartAsync              (in registration order, or concurrently if HostOptions.ServicesStartConcurrently)
  │     └─ BackgroundService.StartAsync: _executeTask = Task.Run(() => ExecuteAsync(stoppingToken))   (.NET 10)
  ├─ IHostedLifecycleService.StartedAsync    (all)
  └─ GenericWebHostService starts Kestrel  →  ApplicationStarted

SIGTERM
  ├─ ApplicationStopping
  ├─ Kestrel stops accepting, drains in-flight requests
  ├─ StopAsync in reverse order  →  BackgroundService cancels stoppingToken, awaits _executeTask (or the timeout)
  └─ ApplicationStopped

In ASP.NET Core the web server itself is a hosted service registered last, which is why your services start before the server and stop after it.

2. What BackgroundService looks like inside

Simplified:

public abstract class BackgroundService : IHostedService, IDisposable
{
    private Task? _executeTask;
    private CancellationTokenSource? _stoppingCts;

    protected abstract Task ExecuteAsync(CancellationToken stoppingToken);

    public virtual Task StartAsync(CancellationToken cancellationToken)
    {
        _stoppingCts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
        _executeTask = Task.Run(() => ExecuteAsync(_stoppingCts.Token), _stoppingCts.Token); // .NET 10
        return Task.CompletedTask;
    }

    public virtual async Task StopAsync(CancellationToken cancellationToken)
    {
        if (_executeTask is null) return;
        _stoppingCts!.Cancel();
        await _executeTask.WaitAsync(cancellationToken).ConfigureAwait(ConfigureAwaitOptions.SuppressThrowing);
    }
    // ...
}

Before .NET 10, StartAsync called ExecuteAsync directly, so everything up to the first incomplete await ran synchronously on the start-up path.

3. Shutdown timing

HostOptions.ShutdownTimeout defaults to 30 seconds (it was 5 seconds before .NET 6). In Kubernetes, terminationGracePeriodSeconds also defaults to 30 seconds, and the pod is killed when it expires. If your timeout equals the grace period, there is no margin, so set the grace period a little longer than the host timeout.

4. Exceptions

If ExecuteAsync throws, the default BackgroundServiceExceptionBehavior.StopHost (since .NET 6) logs the error and stops the whole host. Ignore restores the old behaviour, where the service just stops silently and the app keeps running without it. Either way, a single exception ends your loop unless you catch inside it.

5. Choosing a pattern for periodic work

Pattern Notes
PeriodicTimer in a loop Async, no overlapping runs, honours cancellation; the modern default
Task.Delay loop Fine, but drifts by the run time
System.Threading.Timer Callbacks can overlap; avoid for async work
Quartz.NET, Hangfire Cron schedules, persistence, clustering, retries, dashboards

Try it yourself

  1. dotnet new worker, add Thread.Sleep(10000) before the first await in ExecuteAsync, and compare start-up time on .NET 8 and .NET 10.
  2. Log in every lifecycle hook of an IHostedLifecycleService and in IHostApplicationLifetime events, then press Ctrl+C and read the order.
  3. Throw inside ExecuteAsync and watch the host stop; switch to BackgroundServiceExceptionBehavior.Ignore and see the difference.
  4. Inject a DbContext directly into a BackgroundService and read the scope-validation error in Development.
  5. Run the worker in Docker, send docker stop, and confirm your loop exits within the timeout.

💻 Code

A periodic BackgroundService that uses a scope per run, honours shutdown and survives transient failures.

// Program.cs (.NET 10). The same code works in a web API or in a Worker Service.
var builder = Host.CreateApplicationBuilder(args); // WebApplication.CreateBuilder(args) in an API

builder.Services.AddDbContext<BookingDb>();
builder.Services.AddHostedService<ExpireReservationsService>();
builder.Services.Configure<HostOptions>(o => o.ShutdownTimeout = TimeSpan.FromSeconds(25));

builder.Build().Run();

public sealed class ExpireReservationsService(
    IServiceScopeFactory scopeFactory,
    ILogger<ExpireReservationsService> logger) : BackgroundService
{
    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        // PeriodicTimer: no overlapping runs, and WaitForNextTickAsync honours the stopping token.
        using var timer = new PeriodicTimer(TimeSpan.FromMinutes(1));
        do
        {
            try
            {
                // Hosted services are singletons: create a scope for scoped services like DbContext.
                await using var scope = scopeFactory.CreateAsyncScope();
                var db = scope.ServiceProvider.GetRequiredService<BookingDb>();
                var expired = await db.ExpireUnpaidAsync(DateTimeOffset.UtcNow, stoppingToken);
                logger.LogInformation("Expired {Count} unpaid reservations", expired);
            }
            catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested)
            {
                break; // normal shutdown
            }
            catch (Exception ex)
            {
                // Without this catch, one transient SQL error would end the loop (and stop the host by default).
                logger.LogError(ex, "Expiring reservations failed; will retry on the next tick");
            }
        }
        while (await timer.WaitForNextTickAsync(stoppingToken));
    }
}

public sealed class BookingDb : Microsoft.EntityFrameworkCore.DbContext
{
    public Task<int> ExpireUnpaidAsync(DateTimeOffset now, CancellationToken ct) => Task.FromResult(0); // EF Core ExecuteUpdateAsync in real code
}
dotnet new worker -n Booking.Worker   # Generic Host + BackgroundService, no Kestrel

⚠ Common mistakes

  • Mistake: Injecting a DbContext or another scoped service into a hosted service's constructor. Why it is wrong: Hosted services are singletons, so the scoped service becomes a captive dependency shared for the app's lifetime (and scope validation throws in Development). Instead: Inject IServiceScopeFactory and create a scope per unit of work.
  • Mistake: Doing slow initialisation in StartAsync. Why it is wrong: Hosted services start before Kestrel listens, so readiness and the first requests wait. Instead: Keep StartAsync quick and do slow work in ExecuteAsync, or report readiness through a health check.
  • Mistake: Ignoring stoppingToken. Why it is wrong: The loop keeps running after shutdown starts, and the host waits until ShutdownTimeout and then abandons it mid-work. Instead: Pass the token to every async call and check it in loops.
  • Mistake: Letting an exception escape ExecuteAsync. Why it is wrong: The loop ends; by default the whole host stops (StopHost), or with Ignore the work silently stops forever. Instead: Catch, log and continue inside the loop, and let only truly fatal errors escape.
  • Mistake: Using fire-and-forget Task.Run in a controller for background work. Why it is wrong: No scope, no shutdown handling, lost exceptions, and work dies with the request's services. Instead: Queue the work (a Channel<T> or a message broker) and process it in a BackgroundService.
  • Mistake: Using System.Threading.Timer with an async callback. Why it is wrong: Callbacks can overlap and exceptions are lost. Instead: Use PeriodicTimer in ExecuteAsync.
  • Mistake: Assuming each instance should run the job. Why it is wrong: With three API replicas, a scheduled job runs three times. Instead: Use a distributed lock, a single worker deployment, or a scheduler such as Quartz.NET with clustering.

🏛 Senior insight: trade-offs

Hosted services make background work look trivially easy, which is exactly the danger. Ask three questions before writing one. What happens if the process dies mid-job? Is the work durable (a queue or a database row) or only in memory? What happens with three replicas? If the answers are "lost", "in memory" and "it runs three times", you need a queue, idempotency or a scheduler, not just a loop.

Option When it fits Cost When not to
BackgroundService in the API Light, idempotent, per-instance work (cache refresh, local cleanup) Almost none Heavy CPU or memory work, exactly-once jobs
Separate Worker Service Queue consumers, heavy jobs, separate scaling (KEDA on queue length) Another deployable Tiny jobs that don't justify it
Quartz.NET or Hangfire Cron schedules, persistence, retries, one run per cluster, a dashboard for support staff A library and a job store (SQL Server, Redis) A simple interval loop on one instance
Azure Functions or Container Apps jobs Event-driven or scheduled jobs with scale to zero, e.g. a nightly export Platform lock-in, cold starts, execution time limits on some plans Long-running stateful loops, sub-second latency
IHostedService vs IHostedLifecycleService Use when
IHostedService You only need start and stop
IHostedLifecycleService Something must happen before every service starts (StartingAsync), after all have started (StartedAsync, e.g. mark ready), or before stop begins (StoppingAsync, e.g. stop pulling from a queue)

In .NET 10 the start-up blocking trap is gone, but the other traps remain: the singleton lifetime, exception behaviour and shutdown timing. Also note that a synchronous, CPU-bound or blocking loop still holds a ThreadPool thread for its whole life, so keep loops truly async.

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions running background work from a controller. Why: Checks the risks of fire-and-forget tasks and the safe alternatives.
    How to answer

    Fire-and-forget means starting a task and not awaiting it, such as _ = SendEmailAsync(). The risks are: exceptions are never observed, scoped services like DbContext are disposed when the request ends (giving ObjectDisposedException), work is lost on shutdown or crash, there is no limit on how much work piles up, and HttpContext may be used after the request is gone. In ASP.NET Core, hand the work to a queue (Channel<T>) processed by a BackgroundService that creates its own scope, logs failures and drains on shutdown. If the work must not be lost, use a durable queue or an outbox table.

  2. When: Candidate mentions the Generic Host or application lifetime events. Why: Checks how the host wires up services, configuration and graceful shutdown.
    How to answer

    The Generic Host (IHost) is the common runtime shell for every modern .NET app, web or worker: it owns configuration, logging, dependency injection and the application lifetime. WebApplication.CreateBuilder(args) creates one with sensible defaults: appsettings.json, appsettings.{Environment}.json, user secrets in Development, environment variables and command-line args; console, debug and EventSource logging; and Kestrel. Build() freezes the service collection and builds the IServiceProvider. Run() starts hosted services, then the web server, and blocks until shutdown. On SIGTERM or Ctrl+C the host fires ApplicationStopping, stops accepting requests, lets in-flight ones finish, stops hosted services and exits within HostOptions.ShutdownTimeout (30 seconds by default). The trade-off: the defaults are great, but you must understand them to override them deliberately.

  3. When: Candidate mentions threads used by background work or shutdown. Why: Checks foreground versus background thread behaviour at process exit.
    How to answer

    A foreground thread keeps the process alive: the runtime waits for every foreground thread to finish before the process exits. A background thread does not: when the last foreground thread ends, background threads are stopped immediately and their finally blocks do not run. New Thread objects are foreground by default; ThreadPool threads (and therefore Task.Run work) are always background. So background work needs an explicit graceful shutdown, or it is cut off mid-operation.

↩ Usually asked after

More in Real-Time and Special APIs

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me