Background workers are commonly used in .NET applications to process tasks outside the normal HTTP request lifecycle. They are useful for sending notifications, processing uploaded files, generating reports, synchronizing data, and handling messages from external systems.
A background worker often follows a producer-consumer model. One part of the application creates work, while another part processes it. This design works well when both sides operate at a similar speed. However, problems begin when producers continuously generate work faster than consumers can process it.
For example, an API may receive 300 file-processing requests per second, while the background worker can process only 100 files per second. The remaining work starts accumulating in the queue. Even if the queue has a maximum capacity, the application must decide what to do when producers cannot submit additional items.
This is where backpressure becomes important.
Backpressure is a way to control the flow of incoming work according to the processing capacity of downstream components. Instead of allowing producers to overwhelm consumers, the application slows down, limits, or rejects incoming work when necessary.
In this article, we will explore how backpressure works in .NET background workers, how to implement it with System.Threading.Channels, and how to handle overload conditions in production applications.
Understanding Backpressure in Background Processing
Consider a background worker that processes customer document uploads.
The API accepts uploaded documents and places processing requests into a queue. A worker reads each request, validates the document, extracts information, and saves the results to a database.
Under normal conditions, the worker may process every request as quickly as it arrives.
Now imagine that the database becomes slower because of a temporary performance issue. The worker takes longer to complete each document, but the API continues accepting new uploads at the same rate.
The queue starts growing because the processing rate has decreased.
Without backpressure, the application may continue accepting work until it runs out of available memory or reaches another resource limit.
With backpressure, the application recognizes that downstream processing cannot keep up and controls the flow of new work.
Backpressure can be applied in several ways:
Producers wait until the worker has capacity.
The application rejects new work when the queue is full.
The application limits how many operations can run concurrently.
Incoming requests are throttled before they reach the queue.
Work is persisted to a durable system for later processing.
The important difference between queue capacity and backpressure is that capacity defines how much work can wait, while backpressure controls how producers respond when processing capacity becomes limited.
How Backpressure Works in a .NET Application
A typical background processing system contains three main components.
Producer
The producer creates work items. It could be an ASP.NET Core controller, a scheduled service, another background worker, or an external message consumer.
The producer should not assume that the consumer can process an unlimited number of items.
Queue
The queue temporarily stores pending work. A bounded queue provides a maximum capacity.
When the queue becomes full, the producer must follow the configured overload policy.
Consumer
The consumer reads items from the queue and performs the actual processing.
The consumer's processing rate determines how quickly pending work can be removed.
The following diagram shows the basic flow.
Incoming Requests
|
v
Producer
|
v
Bounded Queue
|
Queue Is Full?
/ \
No Yes
| |
v v
Add Item Apply Backpressure
| / | \
| Wait Reject Throttle
| \ | /
| |
v v
Background Consumer
|
v
Process the Work
|
v
Release CapacityThe key idea is that the producer and consumer should work together. When the consumer becomes slower, the producer must not continue generating work without considering the available capacity.
Implementing Backpressure With System.Threading.Channels
System.Threading.Channels provides bounded channels that support asynchronous producer-consumer communication.
A bounded channel can be configured to wait when it reaches its capacity. This allows producers to slow down naturally instead of continuously adding more work.
Consider the following queue implementation.
using System.Threading.Channels;
public sealed record FileProcessingRequest(
Guid FileId,
string FileName);
public sealed class FileProcessingQueue
{
private readonly Channel<FileProcessingRequest> _channel;
public FileProcessingQueue(int capacity)
{
var options = new BoundedChannelOptions(capacity)
{
FullMode = BoundedChannelFullMode.Wait,
SingleReader = false,
SingleWriter = false
};
_channel = Channel.CreateBounded<FileProcessingRequest>(
options);
}
public ValueTask EnqueueAsync(
FileProcessingRequest request,
CancellationToken cancellationToken)
{
return _channel.Writer.WriteAsync(
request,
cancellationToken);
}
public IAsyncEnumerable<FileProcessingRequest> ReadAllAsync(
CancellationToken cancellationToken)
{
return _channel.Reader.ReadAllAsync(
cancellationToken);
}
public void Complete()
{
_channel.Writer.TryComplete();
}
}The constructor creates a bounded channel with a configurable capacity.
The FullMode property is set to Wait. When the channel is full, WriteAsync waits until space becomes available.
This is the main backpressure mechanism in this implementation.
The producer does not need to continuously check the queue length or repeatedly attempt to insert an item. It can use an asynchronous write operation and allow the channel to coordinate access.
The cancellation token is also important. If the producer is no longer interested in submitting the item, the waiting operation can be canceled.
Applying Backpressure in an ASP.NET Core Background Worker
The next step is to connect the queue to a BackgroundService.
The worker continuously reads requests and processes them.
public sealed class FileProcessingWorker : BackgroundService
{
private readonly FileProcessingQueue _queue;
private readonly ILogger<FileProcessingWorker> _logger;
public FileProcessingWorker(
FileProcessingQueue queue,
ILogger<FileProcessingWorker> logger)
{
_queue = queue;
_logger = logger;
}
protected override async Task ExecuteAsync(
CancellationToken stoppingToken)
{
await foreach (var request in _queue.ReadAllAsync(
stoppingToken))
{
try
{
await ProcessFileAsync(
request,
stoppingToken);
}
catch (OperationCanceledException)
when (stoppingToken.IsCancellationRequested)
{
break;
}
catch (Exception exception)
{
_logger.LogError(
exception,
"File processing failed for {FileId}",
request.FileId);
}
}
}
private async Task ProcessFileAsync(
FileProcessingRequest request,
CancellationToken cancellationToken)
{
_logger.LogInformation(
"Processing file {FileName}",
request.FileName);
// Perform file validation and processing here.
await Task.Delay(
500,
cancellationToken);
}
}Register the queue and worker in Program.cs.
builder.Services.AddSingleton<FileProcessingQueue>(
_ => new FileProcessingQueue(200));
builder.Services.AddHostedService<FileProcessingWorker>();The queue is registered as a singleton because the API and background worker must share the same instance.
In this example, the queue can hold 200 pending requests. When the queue reaches that limit, new producers calling WriteAsync wait until the worker removes an item.
This provides a simple form of backpressure without introducing a separate queue-management mechanism.
However, the example processes one request at a time. For workloads that need higher throughput, the worker can process multiple items concurrently.
Controlling Producer Behavior When the Queue Is Full
Waiting is not always the right behavior.
For example, an HTTP request may have a limited request timeout. If the queue is full and the controller waits for a long time, the request may remain active even though the application cannot immediately accept the work.
There are two common alternatives.
Reject Requests When Capacity Is Exhausted
An API can attempt to add an item without waiting.
The following method uses TryWrite to determine whether the queue can accept the request immediately.
public bool TryEnqueue(FileProcessingRequest request)
{
return _channel.Writer.TryWrite(request);
}The controller can return a service-unavailable response when the queue is full.
Join the conversation! Your thoughts help the community grow.