Delivery & OperationsComplete guide

Background & Hosted Services

Background processing lets an application do meaningful work—emails, media pipelines, cleanup, retries—without blocking a request or depending on a client staying connected.

Overview

The .NET Generic Host starts registered IHostedService instances, coordinates BackgroundService execution, propagates cancellation, and gives each service a bounded graceful-shutdown window. In-process workers suit lifecycle-bound loops, polling, telemetry, and best-effort local queues; they do not make accepted work durable. A bounded Channel can separate producers and consumers while applying backpressure, but pending items disappear when the process fails. Durable schedulers, databases, or brokers are required for work that must survive restart, coordinate replicas, run once according to a business schedule, or support operator replay. Hosted services are singletons, so each item creates and disposes its own dependency-injection scope. Production loops avoid overlapping timers, propagate cancellation, isolate item failures, bound retries and concurrency, make effects idempotent, expose progress and oldest-work age, stop admission before drain, and checkpoint unfinished durable work before the shutdown deadline.

Official resources

What you will learn

  • Understand host lifecycle and BackgroundService exceptions.
  • Build cancellable loops and periodic work.
  • Use bounded Channels for backpressure.
  • Create scoped dependencies per item.
  • Choose local or durable storage.
  • Operate retries, health, drain, and shutdown.

Prerequisites

  • Generic Host, DI, async C#, cancellation, and logging.
  • Queue, retry, idempotency, health, and deployment basics.
  • A durability requirement.

When to use Background & Hosted Services

Good fit

  • Work belongs to the app lifecycle.
  • Local work tolerates process loss.
  • A worker consumes a durable queue.

Choose another approach when

  • Requests start fire-and-forget work.
  • Local work must survive restart.
  • Independent scaling needs another deployment.

Key concepts

Host lifecycle

Hosted services participate in startup and shutdown.

BackgroundService

ExecuteAsync owns a cancellable loop.

Bounded queues

Channels create backpressure.

Dependency scopes

Singleton workers create scopes per item.

Periodic work

PeriodicTimer avoids overlap.

Durability

Local queues lose work on crash.

Idempotency

Repeated work must not duplicate effects.

Health and drain

Progress, cancellation, and checkpointing define safe operation.

Architecture

A producer enqueues durable job records; one or more workers claim and process them, writing results back to the same store they were claimed from.

Producer
Durable job store
Worker process
Result / next step

Conceptual architecture · Adapt to your system context

Implementation walkthrough

The sample uses a bounded Channel, cancellation, graceful completion, and failure isolation.

  1. 01
    Define durability

    Decide loss and retry semantics.

  2. 02
    Choose lifecycle

    Select service, timer, or scheduler.

  3. 03
    Bound admission

    Apply capacity and backpressure.

  4. 04
    Create scopes

    Resolve scoped services per item.

  5. 05
    Handle failure

    Retry and isolate poison work.

  6. 06
    Shut down

    Stop admission and drain or checkpoint.

  7. 07
    Observe

    Measure depth, age, duration, and progress.

Code example

Register a recurring job alongside its dependencies so scheduling and business logic stay in one discoverable place.

ExportModule.cs
public static class ExportModule
{
    public static IServiceCollection AddExportJobs(this IServiceCollection services)
    {
        services.AddScoped<IReportExporter, ReportExporter>();
        return services;
    }

    public static void MapExportJobs(this IRecurringJobManager jobs)
    {
        jobs.AddOrUpdate<IReportExporter>(
            "nightly-export",
            exporter => exporter.ExportAsync(CancellationToken.None),
            Cron.Daily(hour: 2));
    }
}

Testing strategy

Test lifecycle and failure behavior.

  • Test bounded admission.
  • Cancel idle and active work.
  • Isolate item failures.
  • Verify scope disposal.
  • Test drain timeout.
  • Restart durable work idempotently.

Security considerations

Workers execute with service privilege.

  • Use least privilege.
  • Validate tenant and size.
  • Do not capture request credentials.
  • Redact payloads.
  • Protect replay controls.

Performance and scalability

Concurrency matches dependency capacity.

  • Bound queues.
  • Tune consumers.
  • Avoid tight polling.
  • Batch carefully.
  • Track oldest age.

Deployment and operations

Workers stop and resume predictably.

  • Set shutdown grace.
  • Stop readiness before drain.
  • Coordinate singleton schedules.
  • Checkpoint progress.
  • Test backlog recovery.

Common problems and fixes

Worker stops.

Likely cause: Unhandled exception.

Fix: Isolate failures.

Memory grows.

Likely cause: Unbounded queue.

Fix: Bound capacity.

Scoped errors.

Likely cause: A scoped service was captured.

Fix: Create per-item scopes.

Jobs overlap.

Likely cause: Timer reentry.

Fix: Use a sequential loop.

Deploy loses work.

Likely cause: Queue is local.

Fix: Use durable storage.

Shutdown hangs.

Likely cause: Cancellation is ignored.

Fix: Propagate tokens and cap drain.

Best practices

  • Use cancellable loops.
  • Use bounded Channels.
  • Create scopes per item.
  • Use PeriodicTimer.
  • Use durable storage when required.
  • Make effects idempotent.
  • Bound retries.
  • Measure age and shutdown.

Production checklist

  • Durability is explicit.
  • Admission and concurrency are bounded.
  • Cancellation propagates.
  • Scopes are per item.
  • Effects are idempotent.
  • Poison work is isolated.
  • Age and progress alert.
  • Shutdown and recovery are rehearsed.

Common interview questions

IHostedService versus BackgroundService?

BackgroundService wraps an ExecuteAsync loop.

Why bounded Channel?

To apply backpressure.

How use scoped services?

Create a scope per item.

Unhandled exception?

The task stops and host policy applies.

When durable queue?

When work must survive restart.

Avoid overlapping schedules?

Use sequential PeriodicTimer or coordination.

Graceful shutdown?

Stop admission and drain or checkpoint within grace.

Dedicated GitHub sample

Clone, run, test, and modify the focused implementation created for this guide.

Verified sample

Hosted Work Queue

A .NET 10 bounded Channel work queue demonstrating backpressure, cancellation, graceful drain, and per-item failure isolation.

.NET 10BackgroundService SemanticsChannelsxUnit
dedicated-samplebounded-queuebackpressuregraceful-shutdown
Run
dotnet run --project src/HostedWorkQueue
Test
dotnet test HostedWorkQueue.slnx