In ASP.NET, background services are helpful. core apps for activities that ought to go on beyond the typical lifespan of an HTTP request. Typical examples include queue processing, scheduled jobs, notice delivery, cleaning chores, report production, and message consumption.
The issue arises when a background service performs excessive work, operates synchronously, generates infinite concurrency, or uses shared resources that HTTP requests require.
An application can then appear healthy from the outside while its background workers quietly consume database connections, CPU, memory, thread-pool capacity, or external API limits.
The result is often slow API responses, request timeouts, failed health checks, and unpredictable behavior under load.
The goal is not to avoid background services. The goal is to make their workload controlled and isolated enough that background processing cannot take down the request-processing side of the application.
How Background Services Run in ASP.NET Core
ASP.NET Core provides BackgroundService as a convenient base class for long-running background work.
A simple worker might look like this:
public class OrderWorker : BackgroundService
{
private readonly ILogger<OrderWorker> _logger;
public OrderWorker(ILogger<OrderWorker> logger)
{
_logger = logger;
}
protected override async Task ExecuteAsync(
CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
await ProcessOrdersAsync(stoppingToken);
await Task.Delay(
TimeSpan.FromSeconds(10),
stoppingToken);
}
}
private async Task ProcessOrdersAsync(
CancellationToken cancellationToken)
{
// Process pending orders
}
}
The worker runs inside the same ASP.NET Core process as the web application.
That detail matters.
If the worker consumes too many resources, it competes with HTTP requests for the same application resources.
ASP.NET Core Process
|
+-- HTTP Requests
|
+-- Background Services
|
+-- Database Connections
|
+-- Thread Pool
|
+-- Memory
|
+-- CPU
There is no automatic wall between these workloads.
The Most Common Problem With Background Services
A common mistake is to write a background worker as if it were an independent application.
For example:
protected override async Task ExecuteAsync(
CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
var jobs = await LoadJobsAsync(stoppingToken);
foreach (var job in jobs)
{
await ProcessJobAsync(job, stoppingToken);
}
}
}
This has several problems.
There may be no delay between iterations, the query might return a large number of records, and processing may continue indefinitely.
If LoadJobsAsync() returns 10,000 jobs, the worker may spend a long time processing them while continuing to consume application resources.
A better design limits the amount of work processed in each iteration.
var jobs = await LoadJobsAsync(
batchSize: 50,
cancellationToken);
foreach (var job in jobs)
{
await ProcessJobAsync(job, cancellationToken);
}
The worker should have a defined workload boundary.
Avoid Blocking Calls Inside Background Services
The word background does not mean that synchronous code becomes harmless.
This is still blocking:
var result = SomeDatabaseCallAsync().Result;
And this is also blocking:
SomeDatabaseCallAsync().GetAwaiter().GetResult();
These calls can tie up thread-pool threads and create unnecessary contention.
Use asynchronous APIs throughout the worker:
var result = await SomeDatabaseCallAsync(
stoppingToken);
For I/O-bound work, asynchronous execution allows the thread to return to the pool while the database, HTTP service, or message broker is doing its work.
Be Careful With CPU-Heavy Work
Async code does not automatically make CPU-intensive work cheap.
Consider:
protected override async Task ExecuteAsync(
CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
GenerateLargeReport();
await Task.Delay(
TimeSpan.FromMinutes(1),
stoppingToken);
}
}
If GenerateLargeReport() consumes a CPU core for several seconds, HTTP requests in the same process may experience increased latency.
For CPU-heavy workloads, consider moving the processing to a separate worker process or job service.
The important distinction is:
I/O-bound work
|
v
Async BackgroundService can work well
CPU-heavy work
|
v
May need separate compute capacity
Do Not Start Unlimited Tasks
One of the easiest ways to overload an ASP.NET Core application is to create a task for every available item.
For example:
var tasks = jobs.Select(
job => ProcessJobAsync(job, cancellationToken));
await Task.WhenAll(tasks);
If jobs contains 20,000 records, this can create a huge amount of concurrent work.
The database, external APIs, connection pool, memory, and CPU can all become bottlenecks.
A bounded concurrency approach is safer.
For example:
using var semaphore = new SemaphoreSlim(10);
var tasks = jobs.Select(async job =>
{
await semaphore.WaitAsync(cancellationToken);
try
{
await ProcessJobAsync(
job,
cancellationToken);
}
finally
{
semaphore.Release();
}
});
await Task.WhenAll(tasks);
Only a limited number of jobs are processed concurrently.
The correct limit depends on the workload.
Ten database operations may be reasonable in one system and excessive in another.
Use Queues for Controlled Background Processing
For many applications, a queue is a better architecture than continuously scanning a database.
ASP.NET Core provides Channel<T>, which can be used to build an in-process work queue.
For example:
public interface IBackgroundTaskQueue
{
ValueTask QueueAsync(
Func<CancellationToken, ValueTask> workItem);
ValueTask<Func<CancellationToken, ValueTask>>
DequeueAsync(CancellationToken cancellationToken);
}
A bounded channel can prevent producers from adding unlimited work:
private readonly Channel<Func<CancellationToken, ValueTask>> _queue =
Channel.CreateBounded<Func<CancellationToken, ValueTask>>(
new BoundedChannelOptions(100)
{
FullMode = BoundedChannelFullMode.Wait
});
The important part is that the queue is bounded.
Without a limit, an application can accept work faster than it can process it.
Eventually memory becomes the bottleneck.
Separate Producers From Consumers
A useful architecture looks like this:
HTTP Request
|
v
Queue
|
v
Background Worker
|
v
Database / External Service
The HTTP request does not need to perform the entire operation.
For example:
await queue.QueueAsync(
async cancellationToken =>
{
await GenerateReportAsync(
reportId,
cancellationToken);
});
The worker later processes the job.
This can significantly reduce request latency, but it also changes the business semantics.
The HTTP request may now return before the operation is complete.
That means the application should provide a way to track job status when the operation is important.
Do Not Use BackgroundService as a Hidden Job Scheduler
A worker containing this code:
while (!stoppingToken.IsCancellationRequested)
{
await RunTaskAsync();
await Task.Delay(
TimeSpan.FromMinutes(5),
stoppingToken);
}
is effectively acting as a scheduler.
That can be acceptable for simple tasks, but it creates operational problems when the application runs multiple instances.
Suppose the API has five replicas.
Each replica starts the same worker:
Instance 1 -> Runs cleanup
Instance 2 -> Runs cleanup
Instance 3 -> Runs cleanup
Instance 4 -> Runs cleanup
Instance 5 -> Runs cleanup
The task may now execute five times.
This is a common problem in containerized or horizontally scaled applications.
For work that must execute exactly once across all application instances, use a distributed scheduling or job-processing design, or implement distributed coordination deliberately.
Understand What Happens During Scaling
Background services scale with the application process.
If your ASP.NET Core application has:
3 application instances
you usually have:
3 copies of the BackgroundService
If each worker consumes ten database connections, the application may consume up to thirty connections.
Scaling the API therefore also scales the background workload.
This is one reason high-volume background processing is often better separated from the web application.
Web Application
|
+-- Instance 1
+-- Instance 2
+-- Instance 3
Worker Application
|
+-- Worker 1
+-- Worker 2
Now web traffic and background processing can scale independently.
Protect the Database From Background Workers
Background processing frequently interacts with the same database as HTTP requests.
Suppose the API normally uses 70 database connections under load, while the worker starts another 30 concurrent queries.
A connection pool configured for 100 connections is now close to its limit.
If traffic increases slightly, HTTP requests may start waiting for connections.
A worker should therefore have explicit concurrency limits.
For example:
private const int MaxConcurrentJobs = 5;
and then use bounded processing.
The goal is to reserve enough database capacity for normal HTTP traffic.
Avoid Long Database Transactions
A background worker should not hold a database transaction while performing unrelated work.
Avoid:
Begin transaction
|
v
Update database
|
v
Call external API
|
v
Generate file
|
v
Publish message
|
v
Commit
This keeps database resources occupied for the entire workflow.
Prefer smaller transactions:
Database transaction
|
v
Update state
|
v
Commit
External processing
Database transaction
|
v
Save result
|
v
Commit
If multiple systems must be coordinated, patterns such as an outbox can provide better reliability without keeping a database transaction open during external calls.
Handle Exceptions Inside the Worker
An unhandled exception can terminate background processing.
Consider:
protected override async Task ExecuteAsync(
CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
await ProcessBatchAsync(stoppingToken);
}
}
If ProcessBatchAsync() throws an exception that escapes the worker, the behavior may not be what the application expects.
A worker should handle expected failures explicitly.
protected override async Task ExecuteAsync(
CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
try
{
await ProcessBatchAsync(stoppingToken);
}
catch (OperationCanceledException)
when (stoppingToken.IsCancellationRequested)
{
break;
}
catch (Exception ex)
{
_logger.LogError(
ex,
"Background batch processing failed");
await Task.Delay(
TimeSpan.FromSeconds(10),
stoppingToken);
}
}
}
The delay after a failure is important.
Without it, a persistent failure can create a tight retry loop.
Use CancellationToken Correctly
A background worker should respond to application shutdown.
For example:
await Task.Delay(
TimeSpan.FromSeconds(30),
stoppingToken);
and:
await ProcessJobAsync(
job,
stoppingToken);
The token should be passed down into database, HTTP, and other asynchronous operations where supported.
When the application shuts down:
Shutdown requested
|
v
CancellationToken triggered
|
v
Worker stops accepting new work
|
v
Current operation cancels
|
v
Worker exits
Ignoring cancellation can delay deployments and graceful shutdown.
Avoid Long Shutdown Times
A worker may be processing a job that takes several minutes.
If the application receives a shutdown request, the worker should not immediately start another job.
Check cancellation before starting new work:
if (stoppingToken.IsCancellationRequested)
{
break;
}
await ProcessJobAsync(
job,
stoppingToken);
For critical jobs, graceful shutdown should be designed around the business requirements.
Some jobs can be safely cancelled. Others may need to finish or be resumed later.
That is why background jobs should be designed to be restartable.
Make Jobs Idempotent
A worker can crash after completing the business operation but before marking the job as completed.
The job may then run again.
For example:
Process payment
|
v
Payment succeeds
|
X
Worker crashes
|
v
Job is retried
If the operation is not idempotent, the payment could potentially be processed twice.
Background jobs should therefore have a stable identifier and a way to safely detect repeated execution.
For example:
public sealed class Job
{
public Guid Id { get; set; }
public string Type { get; set; } = string.Empty;
public string Status { get; set; } = string.Empty;
}
The database can enforce uniqueness where appropriate.
Idempotency is particularly important for:
- Payments
- Emails
- Order processing
- Inventory updates
- Message publishing
- External API calls
Add Backpressure
Backpressure means the system does not accept unlimited work when downstream resources are already overloaded.
Consider:
10,000 incoming jobs
|
v
Queue capacity = 100
|
v
Worker processes 5 at a time
This gives the system a controlled processing rate.
Without backpressure:
10,000 jobs
|
v
10,000 tasks
|
v
Memory pressure
|
v
Database pressure
|
v
Application slowdown
A bounded queue is often much safer than unlimited concurrency.
Monitor Background Work Separately
Application health cannot be measured only by HTTP response time.
Monitor background workloads separately.
Useful metrics include:
| Metric | What it tells you |
|---|---|
| Queue depth | How much work is waiting |
| Processing duration | How long jobs take |
| Failed jobs | Worker reliability |
| Retry count | Downstream instability |
| Active jobs | Current concurrency |
| Database usage | Resource pressure |
| CPU usage | Compute pressure |
| Memory usage | Potential queue or processing problems |
| Job age | Whether work is becoming stale |
A useful operational metric is queue age.
If the oldest queued job has been waiting for ten minutes, the worker is not keeping up even if every individual job succeeds.
Health Checks Should Reflect Worker Health
An HTTP health endpoint can report that the web server is alive while the background worker is effectively broken.
For important workers, expose meaningful health information.
For example:
Worker status: Running
Queue depth: 42
Oldest job: 18 seconds
Last successful job: 3 seconds ago
Last failure: 5 minutes ago
This gives operations teams a much better view of the application.
Common Mistakes
Running Unlimited Parallel Work
Using Task.WhenAll() over an unrestricted collection can overwhelm downstream systems.
Forgetting That Every Replica Runs the Worker
A worker inside the web application usually runs once per application instance.
Holding Database Connections Too Long
Do not keep database connections open while performing unrelated processing.
Ignoring Cancellation
A worker that ignores shutdown signals can make deployments slow and unreliable.
Retrying Immediately
A failed job should not necessarily be retried in a tight loop.
Storing Large Queues in Memory
In-process queues are useful, but they are not a replacement for durable messaging when jobs must survive application restarts.
Using BackgroundService for Every Kind of Work
Small internal tasks are a good fit. High-volume, long-running, or business-critical workloads may need a dedicated worker architecture.
When Should Background Work Move to a Separate Process?
A separate worker application becomes attractive when:
- Background workload is CPU-intensive.
- Job volume is high.
- Processing needs independent scaling.
- Jobs must survive web application restarts.
- Worker deployments should be independent.
- Background processing requires different resource limits.
- The workload should not compete with HTTP requests.
A common architecture is:
+----------------+
HTTP Request ->| ASP.NET Core |
+-------+--------+
|
v
Durable Queue
|
v
+----------------+
| Worker Service |
+-------+--------+
|
v
Database / APIs
This architecture gives the web application and worker separate resource boundaries.
Advantages of Controlled Background Processing
A properly designed background workload provides:
- Faster HTTP responses
- Better resource isolation
- Predictable database usage
- Controlled concurrency
- Safer application shutdown
- Easier monitoring
- Better scalability
- More reliable job processing
Disadvantages of In-Process Background Services
Running workers inside the ASP.NET Core process can also have limitations:
- Worker failures can affect the web process.
- Multiple application replicas create multiple workers.
- CPU-heavy work competes with HTTP requests.
- In-memory queues lose work during process termination.
- Independent scaling is difficult.
- Resource limits apply to both workloads.
These limitations do not mean BackgroundService is a bad choice. It simply needs to be used for workloads that fit the application’s resource and reliability requirements.
Best Practices Checklist
Before deploying a background service, verify the following:
- Use asynchronous APIs for I/O operations.
- Pass
CancellationTokenthrough the call chain. - Limit concurrent work.
- Use bounded queues when appropriate.
- Keep database transactions short.
- Release database connections before unrelated work.
- Handle expected exceptions.
- Use controlled retry delays.
- Make important jobs idempotent.
- Avoid unlimited
Task.WhenAll()operations. - Understand how many worker instances run after scaling.
- Monitor queue depth and job age.
- Do not store critical jobs only in memory.
- Move high-volume or resource-intensive workloads to dedicated workers when necessary.
- Test graceful shutdown and restart behavior.
Summary
ASP.NET Core background services are useful because they allow applications to perform work outside the normal HTTP request path. The main risk is that the worker still shares the same process and resources as the web application.
A poorly controlled worker can consume database connections, CPU, memory, thread-pool capacity, and external service quotas. The resulting problem may first appear as slow API responses rather than an obvious background-service failure.
The safest approach is to treat background processing as a controlled workload. Limit concurrency, use bounded queues, release database resources quickly, handle cancellation and failures properly, and make jobs safe to retry.
For small internal tasks, an in-process BackgroundService can be a practical solution. When the workload becomes large, critical, or independently scalable, separating the worker from the ASP.NET Core application provides a much stronger resource boundary.
The important question is not whether an application uses background services. It is whether those services have clear limits on how much work they can consume and how that work behaves when the application is under pressure.
Best and Most Recommended ASP.NET Core 11.0 Hosting
Fortunately, there are a number of dependable and recommended web hosts available that can help you gain control of your website’s performance and improve your ASP.NET Core 11 web ranking. HostForLIFE.eu is highly recommended. In Europe, HostForLIFE.eu is the most popular option for first-time web hosts searching for an affordable plan. Their standard price begins at only €3.49 per month. Customers are permitted to choose quarterly and annual plans based on their preferences. HostForLIFE.eu guarantees “No Hidden Fees” and an industry-leading ’30 Days Cash Back’ policy. Customers who terminate their service within the first thirty days are eligible for a full refund.
By providing reseller hosting accounts, HostForLIFE.eu also gives its consumers the chance to generate income. You can purchase their reseller hosting account, host an unlimited number of websites on it, and even sell some of your hosting space to others. This is one of the most effective methods for making money online. They will take care of all your customers’ hosting needs, so you do not need to fret about hosting-related matters.