Designing BackgroundService in ASP.NET Core: Queues, Scopes, and Graceful Shutdown

Designing BackgroundService in ASP.NET Core: Queues, Scopes, and Graceful Shutdown

Work that does not need to run inside an HTTP request—such as sending email, processing files, generating reports, or synchronizing data—should not always be coupled to request latency. ASP.NET Core provides BackgroundService and IHostedService for running long-lived work as part of the application host.

Moving work to the background is not simply a matter of calling Task.Run. A reliable design must define how work is queued, how scoped dependencies are created, what happens when the queue is full, and how the process behaves during shutdown.

When should you use BackgroundService?

BackgroundService is a base implementation of IHostedService intended for long-running operations. It starts with the host and is asked to stop when the host shuts down. Common uses include:

  • Periodic maintenance or cleanup tasks
  • Consumers that process queued work items
  • Scheduled synchronization with an external system
  • Local file, image, or document processing

An in-memory queue can be suitable for best-effort work that may be lost during a process restart. It is not sufficient for business-critical work that must survive crashes or deployments. Those workloads generally need a durable broker, a database-backed queue, or another persistent coordination mechanism.

A basic BackgroundService implementation

Long-running work belongs in ExecuteAsync. The stopping token should be passed to timers and downstream operations:

public sealed class CleanupWorker : BackgroundService
{
    private readonly ILogger<CleanupWorker> _logger;

    public CleanupWorker(ILogger<CleanupWorker> logger)
    {
        _logger = logger;
    }

    protected override async Task ExecuteAsync(
        CancellationToken stoppingToken)
    {
        using var timer = new PeriodicTimer(
            TimeSpan.FromMinutes(10));

        while (await timer.WaitForNextTickAsync(stoppingToken))
        {
            _logger.LogInformation("Cleanup started");
            await CleanupAsync(stoppingToken);
        }
    }

    private static Task CleanupAsync(
        CancellationToken cancellationToken)
    {
        return Task.CompletedTask;
    }
}

ExecuteAsync represents the lifetime of the background operation. Avoid lengthy synchronous initialization in startup methods or before the first asynchronous wait. A worker should become responsive to cancellation and should not block the host from starting other services.

Using scoped dependencies correctly

Hosted services commonly have a singleton-like lifetime. Consequently, a worker should not capture a scoped dependency such as an Entity Framework Core DbContext through constructor injection and keep it for the lifetime of the worker. Create an explicit scope for each unit of work instead.

public sealed class ImportWorker : BackgroundService
{
    private readonly IServiceScopeFactory _scopeFactory;
    private readonly ILogger<ImportWorker> _logger;

    public ImportWorker(
        IServiceScopeFactory scopeFactory,
        ILogger<ImportWorker> logger)
    {
        _scopeFactory = scopeFactory;
        _logger = logger;
    }

    protected override async Task ExecuteAsync(
        CancellationToken stoppingToken)
    {
        while (!stoppingToken.IsCancellationRequested)
        {
            await using var scope =
                _scopeFactory.CreateAsyncScope();

            var importer = scope.ServiceProvider
                .GetRequiredService<IImportService>();

            await importer.RunAsync(stoppingToken);
            await Task.Delay(TimeSpan.FromMinutes(1), stoppingToken);
        }
    }
}

Creating a scope inside the loop prevents scoped state from leaking between iterations. This is particularly important for database contexts and other services that track state or hold disposable resources.

Bounded queues and backpressure

If an API accepts work for later processing, avoid untracked fire-and-forget tasks. The process may stop, exceptions may go unnoticed, and an unlimited in-memory queue may consume all available memory. A bounded Channel provides a simple in-process queue with an explicit capacity.

public interface IWorkQueue
{
    ValueTask EnqueueAsync(
        Func<CancellationToken, ValueTask> work,
        CancellationToken cancellationToken = default);

    ValueTask<Func<CancellationToken, ValueTask>> DequeueAsync(
        CancellationToken cancellationToken);
}

public sealed class WorkQueue : IWorkQueue
{
    private readonly Channel<Func<CancellationToken, ValueTask>> _channel;

    public WorkQueue(int capacity)
    {
        _channel = Channel.CreateBounded<
            Func<CancellationToken, ValueTask>>(
            new BoundedChannelOptions(capacity)
            {
                FullMode = BoundedChannelFullMode.Wait,
                SingleReader = true,
                SingleWriter = false
            });
    }

    public ValueTask EnqueueAsync(
        Func<CancellationToken, ValueTask> work,
        CancellationToken cancellationToken = default)
        => _channel.Writer.WriteAsync(work, cancellationToken);

    public ValueTask<Func<CancellationToken, ValueTask>> DequeueAsync(
        CancellationToken cancellationToken)
        => _channel.Reader.ReadAsync(cancellationToken);
}

A bounded queue creates backpressure when producers are faster than consumers. When capacity is reached, the producer can wait, reject the request, or hand the work to a durable system. The correct choice depends on whether losing the work is acceptable.

Consuming the queue in a worker

public sealed class QueueWorker : BackgroundService
{
    private readonly IWorkQueue _queue;
    private readonly ILogger<QueueWorker> _logger;

    public QueueWorker(
        IWorkQueue queue,
        ILogger<QueueWorker> logger)
    {
        _queue = queue;
        _logger = logger;
    }

    protected override async Task ExecuteAsync(
        CancellationToken stoppingToken)
    {
        while (!stoppingToken.IsCancellationRequested)
        {
            var work = await _queue.DequeueAsync(stoppingToken);

            try
            {
                await work(stoppingToken);
            }
            catch (OperationCanceledException)
                when (stoppingToken.IsCancellationRequested)
            {
                break;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Background work failed");
            }
        }
    }
}

Handle each work item independently if one failure should not terminate the entire consumer loop. For serious infrastructure failures, stopping the worker and allowing the hosting platform to restart it may be safer. Do not silently swallow exceptions; record enough context to diagnose the failure.

Cancellation and graceful shutdown

During an orderly shutdown, the host signals hosted services to stop. Downstream database calls, HTTP requests, delays, and channel reads should use the same cancellation token so that the worker can finish promptly.

  • Treat OperationCanceledException as expected only when the application is actually stopping.
  • Stop accepting new work when shutdown begins.
  • Measure how long outstanding work takes to finish.
  • Use a durable queue when completing in-memory work within the shutdown window is not realistic.

A process crash does not guarantee that shutdown callbacks will run. This is why critical business operations should not depend exclusively on an in-memory queue or on cleanup code executed during shutdown.

Observability and operational limits

A production worker should expose or record at least the following signals:

  • Current queue depth
  • Processing duration and failure rate
  • Retry count
  • Time from enqueue to completion
  • Timestamp of the last successful execution

Use structured fields such as work ID, attempt number, and entity ID. Avoid logging secrets or sensitive payloads. If multiple application instances run concurrently, design for duplicate delivery by using idempotent handlers, distributed coordination, or a message broker with appropriate consumer semantics.

Registering the services

builder.Services.AddSingleton<IWorkQueue>(_ =>
    new WorkQueue(capacity: 100));
builder.Services.AddHostedService<QueueWorker>();
builder.Services.AddScoped<IImportService, ImportService>();

BackgroundService is a useful way to separate long-running work from request processing, but reliability comes from the surrounding design. Explicit scopes, bounded capacity, cancellation support, visible errors, and a clear durability strategy should be considered together.

Sources

//

0 Comments

Write Comment

E-Mail address will not be published