Producer-consumer in .NET with Channels: bounded queues and backpressure
Work that does not need to happen inside an API request tends to pile up over time: sending notifications, generating a thumbnail for a file, updating a search index, exporting telemetry in batches. The quickest way to move this work out of the request is often a ConcurrentQueue and a background task that reads it in a loop. In the early days it works without problems.
The trouble shows up when load increases. If the producer is faster than the consumer, the queue grows, memory swells, latency quietly climbs into minutes, and eventually the process dies from running out of memory. In this post I look at building a bounded in-process queue with .NET's System.Threading.Channels library, designing backpressure deliberately, and wiring the queue properly into the application's lifecycle.
Why a queue should not be unbounded
A queue exists to temporarily absorb the speed difference between a producer and a consumer. For short bursts, that is exactly what we want. But if the speed difference is permanent, the queue does not solve the problem; it only postpones and amplifies it.
With an unbounded queue, the system gives no signal when it is overloaded. Requests keep returning 202 Accepted quickly, metrics look healthy, but the number of pending jobs keeps growing in the background. For users this shows up as "the notification never arrived"; for the system, as a rising memory graph. When the process restarts, everything in memory is lost.
A bounded queue makes this situation visible. When capacity is reached, you are forced to make a decision: make the producer wait, reject the new work, or drop some work. What we call backpressure is this decision being reflected back to the producer.
Getting to know Channel: bounded, unbounded and FullMode
Channel<T> exposes a write end (ChannelWriter<T>) and a read end (ChannelReader<T>). It is designed to be asynchronous: the reader waits for work without blocking a thread, and the writer can also wait without blocking when capacity is full.
var channel = Channel.CreateBounded<ThumbnailJob>(new BoundedChannelOptions(500)
{
FullMode = BoundedChannelFullMode.Wait,
SingleReader = false,
SingleWriter = false
});
CreateUnbounded exists too, but for the reasons above a bounded channel should be the default choice. What happens when capacity is reached is determined by FullMode:
Wait: the writer waits until space becomes available. This is the most direct form of backpressure.DropOldest: the oldest item in the queue is removed and the new one is added.DropNewest: the newest item in the queue is removed.DropWrite: the item being written is silently discarded.
The drop modes suit telemetry or "latest state is enough" kinds of work; losing a measurement is acceptable, the system clogging up is not. When money, orders or work promised to a user are involved, Wait or an explicit rejection is more appropriate. To at least count dropped items, you can use the CreateBounded overload that takes an itemDropped callback.
The SingleReader and SingleWriter options let the channel pick a lighter implementation when there really is only one reader or one writer. If you are not sure, leave them false; setting true in the wrong place leads to subtle concurrency bugs.
The producer side: wait or reject
WriteAsync waits until space is available when capacity is full. Inside an HTTP request, that means the request slows down. Sometimes this is the desired behaviour: the client slows down and load drops naturally. But unbounded waiting can leave requests hanging until they time out and cause open connections to pile up.
For most APIs, a clearer approach is to try writing and respond immediately if it fails:
app.MapPost("/images/{id}/thumbnail", (Guid id, ChannelWriter<ThumbnailJob> writer) =>
{
if (!writer.TryWrite(new ThumbnailJob(id)))
{
return Results.Problem(
title: "The queue is full, please try again later.",
statusCode: StatusCodes.Status503ServiceUnavailable);
}
return Results.Accepted();
});
TryWrite does not wait; it returns false if the channel is full. In that case a 503 with a suitable Retry-After header honestly tells the client the state of the system. A middle ground is also possible: call WriteAsync with a short timeout and reject if it expires. Whichever you choose, what matters is that the decision is clearly visible in the code.
Registering the channel in DI as a singleton and exposing the write and read ends separately also clarifies responsibilities. The endpoint only sees ChannelWriter<T>, the background service only sees ChannelReader<T>.
builder.Services.AddSingleton(_ => Channel.CreateBounded<ThumbnailJob>(500));
builder.Services.AddSingleton(sp => sp.GetRequiredService<Channel<ThumbnailJob>>().Writer);
builder.Services.AddSingleton(sp => sp.GetRequiredService<Channel<ThumbnailJob>>().Reader);
The consumer side: ReadAllAsync, parallelism and error isolation
The simplest form of the reading side is an await foreach loop over ReadAllAsync. The loop continues until the channel is completed and drained, or the cancellation token fires.
A single consumer is often not enough. Having several tasks share the same reader gives a fixed degree of parallelism:
protected override Task ExecuteAsync(CancellationToken stoppingToken)
{
var workers = Enumerable.Range(0, _options.Workers)
.Select(_ => ConsumeAsync(stoppingToken));
return Task.WhenAll(workers);
}
private async Task ConsumeAsync(CancellationToken ct)
{
await foreach (var job in _reader.ReadAllAsync(ct))
{
try
{
await _processor.ProcessAsync(job, ct);
}
catch (Exception ex) when (ex is not OperationCanceledException)
{
_logger.LogError(ex, "Thumbnail job failed: {ImageId}", job.ImageId);
}
}
}
The try/catch here is critical. If an exception thrown while processing an item escapes the loop, that consumer task ends and never reads again. After a few bad items there are no consumers left, the queue fills up and the system silently stops. Processing each item within its own error boundary prevents a single bad item from halting the whole pipeline.
If the processor has scoped dependencies (a DbContext, for example), you need to open a new scope for each item with IServiceScopeFactory. Because the background service is a singleton, injecting scoped services directly would cause a single DbContext to be shared across all jobs.
Batching: groups instead of one by one
Some work is expensive one item at a time but cheap in bulk: writing rows to a database, sending metrics to an external service, adding documents to a search index. The channel provides a good foundation for this too:
var batch = new List<AuditEntry>(capacity: 100);
while (await _reader.WaitToReadAsync(ct))
{
while (batch.Count < 100 && _reader.TryRead(out var entry))
{
batch.Add(entry);
}
await _store.InsertManyAsync(batch, ct);
batch.Clear();
}
WaitToReadAsync waits until at least one item arrives; then the items ready at that moment are collected with TryRead without waiting. Under low load the batches stay small and latency does not grow; under high load the batches fill up and throughput increases. If a batch must be sent before a certain time passes, a time limit can be added, but in most cases this simple structure is enough.
Shutdown and draining: tying the queue to the lifecycle
What happens to the jobs waiting in the queue when the application shuts down? The answer to that question should be part of the design.
In a clean shutdown the writer is completed first (Writer.Complete()), so no new work is accepted. Consumers keep processing the items left in the channel; when the channel is empty, the ReadAllAsync loop ends by itself. The Reader.Completion task signals that the channel has been fully drained.
There is one detail to watch here: stoppingToken fires as soon as shutdown begins. If you pass this token to the loop, as in the example above, consumers stop without draining the queue. If draining is wanted, StopAsync should first complete the writer and then wait for the consumers to finish within a timeout bounded by the shutdown period. The shutdown timeout (HostOptions.ShutdownTimeout) and the termination grace period in the container environment should be set accordingly; otherwise the process will be killed before the work finishes.
Publishing the number of items in the channel (Reader.Count, supported on bounded channels) as a regular metric also lets you see the queue starting to fill up before user complaints do.
When Channel is not enough
A channel lives in process memory. When the process crashes, is redeployed, or the container is forcibly terminated, everything in it is lost. If several instances are running, each has its own queue; work is not balanced across instances.
So for work that must not be lost, a channel alone is not the right tool. In those cases the work should first be written somewhere durable: a table in the database, the outbox pattern, or a real message queue. The channel can still be useful; it is a good intermediate layer for distributing work read from a durable source with bounded parallelism inside the process.
A practical distinction looks like this: if the work can be regenerated or does not matter much when lost (thumbnails, cache warming, telemetry), a channel is enough. If losing it affects someone's money, order or data, you need a durable queue.
Closing
System.Threading.Channels is a small API, but used properly it makes in-process workflows noticeably more predictable. The real gain does not come from the library itself but from the decisions it forces: what the queue's capacity should be, what the producer should do when it is full, what happens when an item fails, and where pending work goes when the application shuts down. A queue that answers these questions up front reports its state clearly when load increases, instead of silently swelling.