During deployments, ASP.NET Core Background Workers May Be Safely Stopped
ASP.NET Core applications frequently employ background workers to process queued messages, issue notifications, create reports, synchronise data, and carry out planned tasks.
When the program is active, these workers frequently operate nonstop.
When the application needs to quit, the issue arises.
An application instance is replaced by a deployment. A Pod is terminated by a container platform. A service is restarted by an administrator. In every scenario, a shutdown signal may be sent to the application while a background worker is handling a crucial task.
If the worker does not handle shutdown correctly, it may leave work incomplete, lose messages, hold database connections, or create duplicate processing when another instance picks up the same job.
Consider a background worker that processes payment notifications.
It reads a message from a queue, calls an external payment provider, updates the database, and acknowledges the message.
If the application stops between the database update and message acknowledgement, the message may be delivered again.
If the application acknowledges the message before completing the database update, the operation may be lost.
The solution is not simply to stop the worker as quickly as possible. The worker needs a controlled shutdown process that stops accepting new work, allows safe operations to finish when possible, releases resources, and preserves unfinished work for recovery.
ASP.NET Core provides IHostedService and BackgroundService for implementing background workloads. Understanding their lifecycle and cancellation behavior is essential for building reliable workers.
Understand the ASP.NET Core Hosted Service Lifecycle
ASP.NET Core uses the hosting infrastructure to manage application startup and shutdown.
A background service can be implemented using IHostedService or by inheriting from BackgroundService.
IHostedService defines two important methods:
- StartAsync starts the hosted service.
- StopAsync requests the hosted service to stop.
BackgroundService provides an implementation of the hosted service lifecycle and allows developers to place long-running work inside ExecuteAsync.
A basic background service looks like this:
public class NotificationWorker : BackgroundService
{
private readonly ILogger<NotificationWorker> _logger;
public NotificationWorker(
ILogger<NotificationWorker> logger)
{
_logger = logger;
}
protected override async Task ExecuteAsync(
CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
_logger.LogInformation(
"Notification worker is running.");
await Task.Delay(
TimeSpan.FromSeconds(5),
stoppingToken);
}
}
}
Register the worker:
builder.Services.AddHostedService<NotificationWorker>();
The host starts the worker when the application starts and signals it to stop when the application shuts down gracefully.
The cancellation token passed to ExecuteAsync is important.
It is cancelled when the host requests the background service to stop.
The worker should observe this token and finish its ongoing work within the available shutdown time.
Ignoring the token can cause the application to exceed its graceful shutdown period.
Understand What Happens During Application Shutdown
Application shutdown is not always immediate.
When the host begins a graceful shutdown, it signals hosted services to stop.
The host waits for their background operations to finish, subject to the configured shutdown timeout.
For the Generic Host, the default shutdown timeout is 30 seconds.
This does not mean every background operation automatically receives 30 seconds to finish. The time is shared across the shutdown process and can be affected by other hosted services and shutdown configuration.
If the application does not finish shutting down within the available period, the hosting environment may eventually terminate the process.
There is another important detail: graceful shutdown cannot be guaranteed in every situation.
If the process crashes, the machine loses power, or the container is terminated forcefully, StopAsync may never complete or may not be called at all.
Therefore, a background worker should never depend on StopAsync as its only mechanism for preserving important work.
Important operations must be recoverable even when the application stops unexpectedly.
Stop Accepting New Work Before Finishing Existing Work
A reliable shutdown process should separate two responsibilities:
- Stop accepting new work.
- Complete or safely abandon work that is already in progress.
Suppose a worker continuously reads messages from a queue.
When shutdown begins, it should stop requesting additional messages. However, if it is already processing a message, it may be able to complete that operation before exiting.
A simplified worker can follow this structure:
protected override async Task ExecuteAsync(
CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
try
{
var message = await ReadNextMessageAsync(
stoppingToken);
if (message is null)
{
continue;
}
await ProcessMessageAsync(
message,
stoppingToken);
}
catch (OperationCanceledException)
when (stoppingToken.IsCancellationRequested)
{
break;
}
}
_logger.LogInformation(
"Background worker is stopping.");
}
The example assumes that ReadNextMessageAsync and ProcessMessageAsync correctly support cancellation.
However, cancellation behavior must be designed carefully.
If ProcessMessageAsync is cancelled after performing an external side effect but before recording completion, the same message may be processed again.
That is why stopping safely also requires idempotent processing and durable message acknowledgement.
Use Cancellation Tokens Throughout the Operation
A common mistake is observing cancellation only in the main worker loop.
For example:
while (!stoppingToken.IsCancellationRequested)
{
await ProcessBatchAsync();
}
If ProcessBatchAsync takes several minutes and does not accept a cancellation token, the worker cannot respond promptly to shutdown.
Pass the token through the complete operation:
private async Task ProcessBatchAsync(
CancellationToken cancellationToken)
{
await LoadPendingItemsAsync(cancellationToken);
await CallExternalServiceAsync(cancellationToken);
await SaveResultsAsync(cancellationToken);
}
The same principle applies to database queries, HTTP requests, delays, and queue operations.
For example:
await httpClient.GetAsync(
"https://api.example.com/status",
cancellationToken);
For Entity Framework Core:
var items = await dbContext.Orders
.Where(x => x.Status == "Pending")
.ToListAsync(cancellationToken);
Passing the cancellation token allows supported operations to stop when shutdown begins.
However, cancellation is cooperative. A method that ignores the token may continue running.
Also, cancellation does not automatically undo an operation that has already been committed by a database or external service.
The application must define what happens when shutdown occurs between individual processing steps.
Use a Scoped Dependency Injection Scope for Each Batch
Hosted services are registered as long-lived services.
They are not automatically created with a new dependency injection scope for every processing operation.
This becomes important when a background worker depends on scoped services such as DbContext or other request-scoped components.
Injecting a scoped service directly into a singleton hosted service can create lifetime problems.
A common solution is to inject IServiceScopeFactory and create a scope for each batch.
public class OrderWorker : BackgroundService
{
private readonly IServiceScopeFactory _scopeFactory;
private readonly ILogger<OrderWorker> _logger;
public OrderWorker(
IServiceScopeFactory scopeFactory,
ILogger<OrderWorker> logger)
{
_scopeFactory = scopeFactory;
_logger = logger;
}
protected override async Task ExecuteAsync(
CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
try
{
await using var scope =
_scopeFactory.CreateAsyncScope();
var processor = scope.ServiceProvider
.GetRequiredService<OrderProcessor>();
await processor.ProcessPendingOrdersAsync(
stoppingToken);
}
catch (OperationCanceledException)
when (stoppingToken.IsCancellationRequested)
{
break;
}
catch (Exception ex)
{
_logger.LogError(
ex,
"Error processing pending orders.");
}
await Task.Delay(
TimeSpan.FromSeconds(10),
stoppingToken);
}
}
}
Register the dependencies:
builder.Services.AddScoped<OrderProcessor>();
builder.Services.AddHostedService<OrderWorker>();
Each iteration creates a new scope. The scoped dependencies are disposed when the iteration finishes.
This prevents a long-running worker from keeping a DbContext alive indefinitely.
It also makes it easier to release database resources before the next batch begins.
Understand the Difference Between Cancellation and Completion
Cancellation does not mean that the current operation has successfully completed.
Suppose a worker performs these steps:
Read message
|
v
Call payment provider
|
v
Update database
|
v
Acknowledge message
The application may receive a shutdown signal after the payment provider has completed the operation but before the database update is committed.
If the message is delivered again, the worker might attempt the payment operation a second time.
A reliable design must account for this possibility.
Use an idempotency key or unique business operation identifier so repeated processing does not create duplicate effects.
For database-backed work, use transactions where appropriate.
For queue-based systems, acknowledge messages only after the required processing has completed successfully.
The exact acknowledgement and visibility-timeout behavior depends on the messaging platform.
For example, some queues make an unacknowledged message visible again after a visibility timeout. Others use explicit message locks that must be renewed while processing.
The worker should follow the delivery guarantees and acknowledgement rules of the actual messaging system.
Configure the Shutdown Timeout Carefully
The Generic Host allows applications to configure the shutdown timeout.
For example:
builder.Services.Configure<HostOptions>(options =>
{
options.ShutdownTimeout =
TimeSpan.FromSeconds(60);
});
This increases the host’s configured graceful shutdown window.
However, increasing the timeout does not fix a worker that never observes cancellation.
A worker might still be blocked on an external API call, an unbounded database operation, or a synchronous operation that cannot be interrupted.
Use timeouts at the individual operation level as well.
For example, an external API request should have an appropriate timeout so that it cannot hold the worker indefinitely.
The shutdown timeout should be selected according to the expected duration of normal processing and the termination limits of the hosting environment.
Coordinate ASP.NET Core Shutdown With Kubernetes
The shutdown behavior becomes especially important when ASP.NET Core applications run inside Kubernetes.
During a Pod termination, Kubernetes normally sends a termination signal to the container’s main process and begins the termination grace period.
The application host receives the shutdown signal and begins its graceful shutdown process.
Kubernetes eventually sends a forceful termination signal when the grace period expires.
The Pod’s termination grace period must therefore be long enough for the application to perform its shutdown work.
For example:
spec:
terminationGracePeriodSeconds: 60
containers:
- name: order-worker
image: registry.example.com/order-worker:v1
The application host’s shutdown timeout and Kubernetes termination grace period should be configured together.
The application needs enough time to stop accepting new work, complete safe in-progress operations, and release resources before Kubernetes forcefully terminates the container.
Do not assume that configuring a 60-second host timeout automatically guarantees 60 seconds of processing time. The container platform and other shutdown steps also consume time.
For queue consumers, it is particularly important to stop receiving new messages as early as possible.
This reduces the number of operations that are interrupted during deployment.
Implement a Graceful Shutdown With Explicit Cleanup
Some workers need to perform cleanup after their main processing loop ends.
For example, a worker may need to release a message subscription, close a connection, or flush buffered data.
The main ExecuteAsync method should handle the cancellation signal and allow cleanup to run.
protected override async Task ExecuteAsync(
CancellationToken stoppingToken)
{
try
{
await ProcessMessagesAsync(stoppingToken);
}
catch (OperationCanceledException)
when (stoppingToken.IsCancellationRequested)
{
_logger.LogInformation(
"Shutdown requested.");
}
finally
{
_logger.LogInformation(
"Releasing worker resources.");
await ReleaseResourcesAsync();
}
}
The cleanup method should be bounded and should not wait indefinitely.
It should also be designed so that cleanup failures do not hide the original processing failure.
If cleanup itself requires a timeout, use a separately controlled cancellation token.
Do not use an already-cancelled stopping token for cleanup that must still run after shutdown begins.
At the same time, avoid treating cleanup as a guaranteed recovery mechanism. Process crashes and forced termination can prevent it from completing.
Important business state should be persisted before the worker acknowledges successful processing.
Avoid Common Background Worker Shutdown Mistakes
Several implementation mistakes can cause unreliable shutdown behavior.
Ignoring the stopping token
A worker that never checks cancellation may continue running until the hosting environment terminates the process.
Using Thread.Sleep in an asynchronous worker
Thread.Sleep blocks a thread and cannot respond to cancellation. Use Task.Delay with a cancellation token.
Keeping database connections open for the lifetime of the worker
Use short-lived database operations and scoped dependencies. Release resources after each batch.
Acknowledging messages before processing completes
A message acknowledged too early may be lost if the application stops before the operation finishes.
Assuming StopAsync always runs
Unexpected process termination can prevent graceful cleanup. Make processing recoverable independently of shutdown callbacks.
Increasing the shutdown timeout without fixing blocking operations
A longer timeout only gives the worker more time. It does not make an unresponsive operation cancellable.
Starting new work while the application is stopping
Stop fetching new messages or accepting new jobs as soon as shutdown begins.
Running multiple copies of a worker without coordination
If several application instances process the same workload, use queue ownership, database claiming, leases, or another concurrency-control mechanism to prevent conflicting processing.
Monitor Background Worker Shutdown
A production worker should provide enough information to understand its shutdown behavior.
Useful events and metrics include:
- When shutdown begins.
- How many jobs are currently being processed.
- How long each job takes to finish.
- How many jobs are cancelled.
- How many messages are retried.
- How many messages fail permanently.
- Whether cleanup completed successfully.
- Whether the process exceeded its expected shutdown duration.
Structured logs make it easier to correlate a deployment with interrupted background work.
For example:
_logger.LogInformation(
"Worker shutdown started. ActiveJobs: {ActiveJobs}",
activeJobs);
Avoid logging sensitive message payloads or credentials.
For important workloads, monitor queue depth and the age of the oldest pending message as well. A worker can shut down cleanly while the queue continues growing because replacement workers are not starting or cannot process messages.
Production Checklist
Before deploying an ASP.NET Core application that contains background workers, verify the following:
- The worker observes its stopping token.
- Cancellation is passed to database, HTTP, and queue operations.
- New work stops being accepted during shutdown.
- In-progress work has a defined completion or recovery strategy.
- Message acknowledgement happens only after successful processing.
- Processing is idempotent where duplicate delivery is possible.
- Scoped services are created and disposed correctly.
- External operations have appropriate timeouts.
- Host shutdown timeout is compatible with the deployment environment.
- Kubernetes termination grace period allows sufficient time for graceful shutdown.
- Logs and metrics make interrupted processing visible.
These practices help reduce incomplete operations and unexpected behavior during application deployments.
Summary
Graceful shutdown is an important part of building reliable ASP.NET Core background workers.
A worker should not simply stop when the application receives a termination signal. It should stop accepting new work, respond to cancellation, complete safe in-progress operations when possible, release resources, and leave unfinished work in a state that can be recovered.
BackgroundService provides a convenient lifecycle for long-running operations, while cancellation tokens allow the host to communicate shutdown requests.
However, cancellation alone does not guarantee that business operations are completed or rolled back. Reliable workers also need idempotent processing, correct message acknowledgement, short-lived database scopes, and durable recovery mechanisms.
When deploying to containers or Kubernetes, coordinate the host shutdown timeout with the platform’s termination grace period.
The most important principle is to design background work so that it can recover from interruption. Graceful shutdown reduces disruption, but durable processing and idempotency protect the application when graceful shutdown is not possible.
ASP.NET Core 11.0 Hosting Recommendation
HostForLIFE.eu
HostForLIFE.eu is a popular recommendation that offers various hosting choices. Starting from shared hosting to dedicated servers, you will find options fit for beginners and popular websites. It offers various hosting choices if you want to scale up. Also, you get flexible billing plans where you can choose to purchase a subscription even for one or six months.
