How to Handle Graceful Shutdown in ASP.NET Core Background Services
This guide covers how ASP.NET Core background services can stop cleanly during shutdown without losing or duplicating work. It walks through cancellation tokens, scoped dependencies, queue acknowledgement order and host shutdown timeouts, with a test checklist for production readiness.
Key points
- Pass stoppingToken to database and HTTP calls, and check it between units of work.
- Create a new IServiceScopeFactory scope per unit of work instead of holding scoped services like DbContext in a long-lived worker.
- Acknowledge queue messages only after the business operation is committed.
- Use idempotency keys or unique constraints so redelivered messages do not repeat side effects.
- Set HostOptions.ShutdownTimeout and keep the container termination grace period at least as long.
- Test shutdown while work is active and verify broker redelivery in an integration environment, not only with mocks.
A .NET application that shuts down in the middle of background work can leave an operation half-finished, process a queue message twice, or break business consistency. This article looks at how BackgroundService workers should react to a shutdown signal and how to design them so that interruptions are recoverable.
The main guidance is to pass the cancellation token into every cancellation-aware call, run each unit of work in its own dependency injection scope, and acknowledge queue messages only after the business change is committed. The author also explains that the host shutdown timeout is only a wait period and that container or service-manager deadlines may be shorter. Idempotency, checkpoints and reconciliation are presented as the real safety net, and the article closes with a test matrix covering interrupted work, failed cleanup and restarts.
Real-world use
- An order-queue worker that resumes half-finished orders safely after a container redeploy.
- A report-generation service in Kubernetes that checkpoints progress and resumes after a pod restart.
- An email or payment background job that must not repeat a side effect when a message is redelivered.
Why it matters
Interrupted background work can duplicate charges or leave orders half-saved, and a cancellation token alone does not prevent that. Reviewing your workers against these patterns and the test matrix is a concrete step before the next deployment.