Background queues are useful when an application needs to accept work quickly and process it separately. An ASP.NET Core API, for example, may receive requests that trigger email notifications, report generation, file processing, or other operations that do not need to finish before the HTTP response is returned.
Moving this work into a background queue can improve request handling, but it introduces another problem: what happens when new work arrives faster than the application can process it?
If the application keeps accepting items without considering the processing capacity, the queue can continue growing. Memory consumption increases, processing delays become longer, and eventually the application may become unstable or stop responding.
This problem is not limited to high-traffic applications. Even a small application can experience it when an external service becomes slow, a database connection is unavailable, or a sudden burst of requests arrives.
In this article, we will explore how to prevent a background queue from growing without limit in .NET, how to choose an appropriate queue capacity, and how to handle situations where the application receives more work than it can process.
Why an Unbounded Background Queue Becomes a Problem
An unbounded queue accepts new items without enforcing a maximum capacity. This makes it convenient for producers because they can submit work without waiting for consumers.
However, the queue does not create additional processing capacity. If producers continuously add items faster than consumers remove them, the difference accumulates in memory.
Consider an application that sends email notifications through a background worker. The API receives 200 notification requests per second, while the email processing service can handle only 80 notifications per second.
The queue receives 120 more items per second than the worker can process. After one minute, approximately 7,200 additional items may be waiting.
If each queued item contains only a small identifier, this may not create an immediate problem. However, real queue messages can contain serialized data, recipient information, attachments, metadata, or references to larger objects.
As the queue grows, several problems can appear:
Memory usage increases continuously.
Background processing takes longer to catch up.
Garbage collection activity may increase.
Application response times can become unpredictable.
The application may eventually encounter memory pressure or an out-of-memory failure.
During shutdown, a large backlog may prevent the application from completing its work within the available shutdown period.
The important point is that a background queue must have a capacity policy. Accepting every item is not always the safest behavior.
Understanding Bounded and Unbounded Queues
A bounded queue has a configured maximum number of items. Once it reaches that capacity, the application must decide what to do with additional work.
An unbounded queue does not enforce this limit.
The following table explains the practical difference.
Area | Unbounded queue | Bounded queue |
|---|---|---|
Capacity | No configured maximum | Fixed maximum item count |
Memory usage | Can continue increasing | More predictable |
Producer behavior | Usually accepts immediately | May wait, reject, or drop |
Overload handling | Often delayed until resources are exhausted | Explicitly controlled |
Implementation | Simple initially | Requires an overload policy |
Production suitability | Risky for uncontrolled workloads | Better when capacity is selected carefully |
A bounded queue does not automatically make an application reliable. It simply gives the application control over how much pending work it can hold.
The next decision is what should happen when the queue becomes full.
Choosing What Happens When the Queue Is Full
There is no single correct behavior for every application. The right choice depends on the importance of the work and how quickly producers need a response.
Wait Until Space Becomes Available
The producer waits when the queue reaches its capacity. Once a consumer processes an item and creates space, the producer can submit its work.
This approach is useful when every accepted operation must be processed and producers can tolerate waiting.
For example, an internal data-processing service may wait briefly before submitting another batch.
However, waiting can become dangerous when the producer is an HTTP request. If too many requests wait for queue capacity, request threads and other resources remain occupied longer than expected.
Use this approach only when the waiting behavior is intentional and has a reasonable timeout or cancellation mechanism.
Reject New Work
The application can reject new items when the queue is full.
This is often a good choice for HTTP APIs because the client receives a clear response instead of waiting indefinitely.
For example, an API can return HTTP 503 Service Unavailable when its background processing capacity is exhausted. The response can also include a Retry-After header when the application can provide a meaningful retry interval.
The client can then retry according to an appropriate retry policy.
This approach works well for operations that can be submitted again without creating duplicate business effects. Applications should use idempotency keys or another duplicate-prevention mechanism when retries could otherwise repeat an operation.
Drop Items When They Are No Longer Useful
Some background tasks do not need to be processed if newer information is already available.
For example, a dashboard may need the latest status update rather than every intermediate status change. In such cases, dropping older pending updates can be acceptable.
However, dropping work is inappropriate for operations such as financial transactions, order processing, or important customer notifications.
The application must distinguish between optional work and business-critical work before choosing a dropping strategy.
Implementing a Bounded Queue With System.Threading.Channels
.NET provides System.Threading.Channels, which supports producer-consumer communication and bounded capacity.
The following example creates a queue that accepts a maximum of 500 pending notification requests.
using System.Threading.Channels;
public sealed class NotificationQueue
{
private readonly Channel<NotificationRequest> _channel;
public NotificationQueue()
{
var options = new BoundedChannelOptions(500)
{
FullMode = BoundedChannelFullMode.Wait,
SingleReader = false,
SingleWriter = false
};
_channel = Channel.CreateBounded<NotificationRequest>(
options);
}
public bool TryEnqueue(NotificationRequest request)
{
return _channel.Writer.TryWrite(request);
}
public ValueTask<bool> EnqueueAsync(
NotificationRequest request,
CancellationToken cancellationToken)
{
return _channel.Writer.WaitToWriteAsync(
cancellationToken).IsCompletedSuccessfully
? new ValueTask<bool>(
_channel.Writer.TryWrite(request))
: EnqueueAfterWaitAsync(
request,
cancellationToken);
}
private async ValueTask<bool> EnqueueAfterWaitAsync(
NotificationRequest request,
CancellationToken cancellationToken)
{
while (await _channel.Writer.WaitToWriteAsync(
cancellationToken))
{
if (_channel.Writer.TryWrite(request))
{
return true;
}
}
return false;
}
public IAsyncEnumerable<NotificationRequest> ReadAllAsync(
CancellationToken cancellationToken)
{
return _channel.Reader.ReadAllAsync(
cancellationToken);
}
public void Complete()
{
_channel.Writer.TryComplete();
}
}
public sealed record NotificationRequest(
string Email,
string Subject,
string Message);The queue uses BoundedChannelOptions to limit the number of pending items. Its FullMode is set to Wait, meaning writers wait when the channel reaches its configured capacity.
The TryEnqueue method attempts to add an item immediately. It returns false when the item cannot be accepted at that moment.
The EnqueueAsync method waits for space to become available and then attempts to write the item. The loop is important because another producer may take the available space before the current producer writes its item.
The queue also exposes ReadAllAsync so background workers can consume items asynchronously.
One important distinction is that the capacity of 500 limits pending items inside the channel. It does not include requests that producers are currently holding while waiting to write, or items already removed by consumers and being processed.
For this reason, a bounded channel should be combined with sensible limits on producer concurrency and worker concurrency.
Rejecting Work Immediately When the Queue Is Full
For an HTTP API, waiting for queue capacity may not always be desirable. An application may prefer to reject additional requests immediately.
The following implementation uses a bounded channel with a dropping policy, but it checks capacity through TryWrite and reports whether the item was accepted.
using System.Threading.Channels;
public sealed class BoundedNotificationQueue
{
private readonly Channel<NotificationRequest> _channel;
public BoundedNotificationQueue(int capacity)
{
var options = new BoundedChannelOptions(capacity)
{
FullMode = BoundedChannelFullMode.Wait,
SingleReader = false,
SingleWriter = false
};
_channel = Channel.CreateBounded<NotificationRequest>(
options);
}
public bool TryEnqueue(NotificationRequest request)
{
return _channel.Writer.TryWrite(request);
}
public IAsyncEnumerable<NotificationRequest> ReadAllAsync(
CancellationToken cancellationToken)
{
return _channel.Reader.ReadAllAsync(
cancellationToken);
}
}Here, the queue uses Wait as its full mode, but the API calls TryWrite instead of waiting. If the queue is full, TryWrite returns false and the caller can reject the request.
This is different from configuring a dropping mode such as DropOldest or DropWrite. With a dropping mode, the channel may report a successful write even though an item was discarded according to the configured policy. That behavior can make it difficult to tell whether a particular business operation was actually retained.
For business-critical work, explicitly checking whether the item was accepted is generally easier to reason about.
Connecting the Queue to an ASP.NET Core Background Worker
A queue is useful only when something consumes its items.
The following BackgroundService continuously reads notification requests and processes them.
public sealed class NotificationWorker : BackgroundService
{
private readonly NotificationQueue _queue;
private readonly ILogger<NotificationWorker> _logger;
public NotificationWorker(
NotificationQueue queue,
ILogger<NotificationWorker> logger)
{
_queue = queue;
_logger = logger;
}
protected override async Task ExecuteAsync(
CancellationToken stoppingToken)
{
await foreach (var request in _queue.ReadAllAsync(
stoppingToken))
{
try
{
await ProcessNotificationAsync(
request,
stoppingToken);
}
catch (OperationCanceledException)
when (stoppingToken.IsCancellationRequested)
{
break;
}
catch (Exception exception)
{
_logger.LogError(
exception,
"Failed to process notification for {Email}",
request.Email);
}
}
}
private async Task ProcessNotificationAsync(
NotificationRequest request,
CancellationToken cancellationToken)
{
// Call the email service here.
await Task.Delay(
100,
cancellationToken);
}
}Register the queue and worker in Program.cs:
builder.Services.AddSingleton<NotificationQueue>();
builder.Services.AddHostedService<NotificationWorker>();The queue is registered as a singleton because both the API and the background worker must access the same queue instance.
The worker processes one item at a time in this example. If the workload requires more throughput, the application can introduce multiple consumers or controlled parallel processing.
However, increasing the number of consumers should be based on the capacity of downstream services. Running more workers does not help when the database, email provider, or another dependency is already overloaded.
Returning a Clear Response When the Queue Is Full
An API should not report that background work has been accepted when it was not actually added to the queue.
A controller can use TryEnqueue to make this decision.
[ApiController]
[Route("api/notifications")]
public sealed class NotificationsController : ControllerBase
{
private readonly NotificationQueue _queue;
public NotificationsController(
NotificationQueue queue)
{
_queue = queue;
}
[HttpPost]
public IActionResult Send(
NotificationRequest request)
{
var accepted = _queue.TryEnqueue(request);
if (!accepted)
{
return StatusCode(
StatusCodes.Status503ServiceUnavailable,
new
{
message = "Notification queue is full. Please retry later."
});
}
return Accepted(new
{
message = "Notification accepted for processing."
});
}
}The HTTP 202 Accepted response indicates that the request has been accepted for processing, not that the notification has already been delivered.
When the queue is full, the API returns HTTP 503 instead of silently losing the request.
In a production API, request validation, authorization, idempotency, and retry guidance should also be handled before accepting the operation.
How to Choose the Right Queue Capacity
Choosing a queue capacity is not simply a matter of selecting a large number.
A queue should be sized according to the expected workload, the processing rate, the amount of memory used by each item, and the maximum delay the business can tolerate.
For example, suppose an application receives an average of 100 tasks per second and its workers process 100 tasks per second. Under normal conditions, the queue may remain relatively small.
Now consider a temporary increase to 150 tasks per second while processing remains at 100 tasks per second. The queue grows by approximately 50 items per second during that period.
If the burst lasts 20 seconds, the backlog increases by approximately 1,000 items.
This is a useful planning estimate, not a guarantee. Real systems experience variable processing times, uneven arrivals, retries, and dependency failures.
Consider these factors when selecting capacity:
Expected peak arrival rate rather than only average traffic.
Average and maximum processing time.
Memory consumed by each queued item.
Maximum acceptable processing delay.
Number of consumers and their concurrency.
How long the application should tolerate a downstream service outage.
Whether work can be rejected, retried, or persisted elsewhere.
It is also important to measure the actual size of queue messages. A queue containing 1,000 small identifiers has a very different memory profile from one containing 1,000 large objects.
Whenever possible, queue lightweight identifiers and retrieve larger data when the worker needs it.
Monitoring Queue Growth in Production
A bounded queue prevents unlimited growth inside the queue, but it does not tell the operations team whether the application is regularly reaching its capacity.
Monitoring helps identify overload before it becomes a customer-facing problem.
Useful metrics include:
Metric | Why it matters |
|---|---|
Current queue length | Shows how much work is waiting |
Queue capacity | Helps calculate available space |
Enqueue rate | Shows how quickly work arrives |
Processing rate | Shows how quickly workers complete tasks |
Rejected item count | Identifies requests that could not be accepted |
Processing duration | Helps identify slow operations |
Oldest item age | Shows how long work has been waiting |
Failed item count | Helps track processing failures |
For example, if the queue frequently remains close to its maximum capacity, the application may need more processing capacity, a different admission policy, or a change to the downstream service.
If queue length stays low but processing duration increases, the problem may be inside the worker or one of its dependencies.
Queue length alone is not enough. Combining it with processing duration, rejection count, and oldest-item age provides a more useful operational picture.
Common Mistakes to Avoid
Increasing Capacity Without Understanding the Cause
Increasing a queue from 500 to 50,000 items may appear to solve an overload problem, but it can simply delay the failure.
If consumers cannot keep up, the application will eventually reach the new limit. Larger queues can also increase memory consumption and processing delays.
Using a Single Queue for Every Type of Work
Not all background operations have the same priority.
A large report-generation workload should not necessarily delay time-sensitive customer notifications. Separate queues or workload-specific processing limits can help prevent one type of work from affecting another.
Running Too Many Consumers
More consumers can improve throughput when the application has available resources.
However, too many consumers may overload a database, external API, or other shared dependency. Worker concurrency should be controlled independently from queue capacity.
Ignoring Shutdown Behavior
An application should have a clear policy for stopping its background workers.
For an in-memory queue, pending items may be lost if the process terminates unexpectedly. During a graceful shutdown, the worker should be allowed a reasonable period to finish current operations and process pending items.
The application should also avoid accepting new work after the queue has been completed.
Treating an In-Memory Queue as Durable Storage
System.Threading.Channels is an in-memory communication mechanism. It does not persist messages across application restarts or machine failures.
If every accepted operation must survive a process crash, use durable storage such as a database-backed job table or a message broker.
An in-memory queue is appropriate when its loss characteristics are acceptable and the application has a clear recovery strategy.
When to Use an In-Memory Queue and When to Use a Durable Queue
An in-memory bounded queue is suitable for lightweight background tasks that can tolerate the failure characteristics of the running process.
A durable queue is more appropriate when the application must preserve accepted work even after a restart or unexpected failure.
Requirement | In-memory bounded queue | Durable queue |
|---|---|---|
Simple background processing | Suitable | Suitable |
Maximum pending item count | Supported | Depends on the storage system |
Survives application restart | No | Yes, when configured correctly |
Multiple application instances | Usually requires additional coordination | Commonly supported |
Message recovery | Must be implemented separately | Usually provides persistence and recovery features |
Operational complexity | Lower | Higher |
Best fit | Local background tasks | Important or distributed business operations |
A common production design is to use an in-memory queue for temporary, local work and a durable message broker for operations that must not be lost.
The decision should be based on business requirements rather than choosing a technology simply because it is available in the framework.
Best Practices for Preventing Unlimited Queue Growth
A reliable background processing design should follow a few consistent rules.
Set a maximum queue capacity based on expected workload and available resources.
Choose an explicit full-queue policy: wait, reject, or drop only when dropping is acceptable.
Keep queued messages lightweight and avoid retaining large objects unnecessarily.
Limit producer concurrency when waiting producers could consume too many resources.
Control consumer concurrency according to downstream service capacity.
Measure queue length, processing time, rejection count, and oldest-item age.
Implement idempotency when clients or workers may retry operations.
Define a shutdown policy and understand what happens to pending items.
Use durable messaging when accepted work must survive application failures.
Test the queue under bursts, slow dependencies, worker failures, and application shutdown.
These practices help make background processing predictable instead of allowing it to consume resources without a clear limit.
Summary
A background queue helps separate incoming requests from slower processing operations, but an unbounded queue can create serious memory and reliability problems when producers are faster than consumers.
In .NET, System.Threading.Channels provides a practical way to create bounded queues and control how producers behave when capacity is exhausted. Depending on the workload, an application can wait for available space, reject new requests, or deliberately discard work that is no longer useful.
The queue capacity should be selected using real workload measurements, memory requirements, processing rates, and acceptable delays. Monitoring is equally important because a queue that repeatedly reaches its limit indicates that the application may need additional processing capacity or a different workload strategy.
Most importantly, an in-memory queue should not be treated as durable storage. If business-critical operations must survive application restarts or failures, a persistent queue or message broker is a better choice.
By combining bounded capacity, controlled concurrency, clear overload handling, and production monitoring, developers can build background processing systems that remain stable even when incoming workloads increase unexpectedly.

Join the conversation! Your thoughts help the community grow.