Compare background services, queues, and scheduled jobs for long-running work in ASP.NET Core.
Flipkart · Full Stack Developer · 3-4-years · technical
Published
Year not specified · .NET, Messaging, ASP.NET Core
Community answers
Posted by wasAsked editorial collection
Use BackgroundService for process-local recurring or queue-consuming work, a durable broker for reliable cross-service work, and a job scheduler when you need persisted schedules, retries, dashboards, or distributed coordination.
Example:
protected override async Task ExecuteAsync(CancellationToken stoppingToken) {
await foreach (var job in queue.ReadAllAsync(stoppingToken)) {
using var scope = scopeFactory.CreateScope();
await scope.ServiceProvider.GetRequiredService<IJobHandler>()
.HandleAsync(job, stoppingToken);
}
}
Bound queues for backpressure, create scopes per item, make handlers idempotent, persist important jobs before acknowledging, and use exponential retry plus a dead-letter path. Do not capture request services or fire-and-forget tasks. Record attempts, duration, correlation, and final outcome.
Backbencher Developer · · 0 likes
ASP.NET Core requests should finish quickly, so long-running work is moved out of the request. The three common options solve different problems.
1. Hosted / background services (IHostedService, BackgroundService)
- Run inside the web process for its whole lifetime.
- Good for continuous in-process work: polling, consuming a queue, cache warming.
- Limitation: work is lost if the process restarts or is scaled down, and every instance runs its own copy unless you coordinate.
2. Queues (Azure Service Bus, RabbitMQ, Amazon SQS, Kafka)
- The API writes a message and returns 202 Accepted with a status URL; one or more workers process messages independently.
- Gives durability, retries, dead-letter queues and horizontal scaling of workers.
- Handlers must be idempotent because messages can be delivered more than once.
- Use the outbox pattern so the database change and the message are not lost or duplicated when one of them fails.
3. Scheduled jobs (Hangfire, Quartz.NET, Azure Functions timer triggers, cron)
- Run at a time or interval: nightly reports, cleanup, billing runs.
- Need persistence and distributed locking so a job does not run twice across instances.
Choosing:
- User-triggered work that may take seconds or minutes (export, video processing, email blast): queue plus worker.
- Recurring time-based work: a scheduler with persistent storage.
- Light in-process background loops: BackgroundService, usually reading from a Channel<T> or a durable queue.
Practical details interviewers like to hear: pass CancellationToken and honour shutdown; never capture scoped services (like DbContext) in a singleton — create a scope per message; add retries with backoff, poison-message handling and monitoring of queue length; expose job status to the UI instead of keeping an HTTP request open.