C# Bounded Channels: Add Backpressure to a Producer–Consumer Pipeline

An async worker can keep accepting work faster than it can process it. If every incoming item becomes a new task or stays in an unbounded in-memory queue, a temporary traffic spike can turn into rising memory use. A bounded channel gives a producer–consumer pipeline a capacity limit and makes the overflow decision visible in code.

Editorial illustration: a bounded .NET channel holds a fixed row of work tickets and pauses the producer until a consumer frees space

Editorial illustration; Channel<T> is a .NET library API, not C# language syntax.

Summary

  • Channel.CreateBounded<T> limits queued items and can make writers wait when consumers fall behind.
  • BoundedChannelFullMode.Wait preserves work through backpressure; drop modes deliberately discard items and suit only loss-tolerant data.
  • Channels coordinate in-process producers and consumers, but they are not a durable queue across process restarts.

When a channel helps

System.Threading.Channels is a .NET producer–consumer library. A writer publishes items; one or more readers process them asynchronously. A bounded channel restricts how many items wait at once. With the default Wait mode, WriteAsync waits until room is available, slowing the producer rather than allowing memory use to grow without limit.

This is useful when a service accepts a finite stream of jobs and can apply pressure upstream. It is not a replacement for a persistent message broker when work must survive a process crash, deploy or machine restart. If a process stops, items only held in memory are lost.

The following complete console example targets .NET 8 or later and uses the shared framework’s channels APIs. System.Threading.Channels is included in .NET Core 3.0 and later. Older .NET Standard or .NET Framework targets may need the NuGet package; confirm compatibility for the target framework before copying the example.

using System.Threading.Channels;

var channel = Channel.CreateBounded<int>(new BoundedChannelOptions(4)
{
    FullMode = BoundedChannelFullMode.Wait,
    SingleWriter = true,
    SingleReader = true
});

Task consumer = Task.Run(async () =>
{
    await foreach (int value in channel.Reader.ReadAllAsync())
    {
        Console.WriteLine($"Processing {value}");
        await Task.Delay(150); // stand-in for asynchronous work
    }
});

try
{
    for (int value = 1; value <= 12; value++)
    {
        await channel.Writer.WriteAsync(value);
        Console.WriteLine($"Queued {value}");
    }
}
finally
{
    channel.Writer.TryComplete();
}

await consumer;

The top-level await and await foreach syntax is supported by the modern C# version used by current .NET SDK templates. Those are C# language features; the channel types and behavior belong to the .NET library. SingleWriter and SingleReader are promises about how the program uses the channel, so set them to false if multiple writers or readers may operate concurrently.

Choose the full mode from the meaning of the data

Wait is the safest starting point for work that must be processed. When capacity is full, WriteAsync pauses until a consumer makes room. That pause propagates backpressure to the caller. The caller still needs cancellation and a timeout policy if waiting forever would be harmful.

The other modes drop data when full. DropOldest is useful for a live dashboard where the newest reading matters more than stale samples. DropWrite can suit telemetry where occasional loss is acceptable. DropNewest removes the newest item already in the channel to make room for the incoming write. These modes are not interchangeable: for payments, emails, or user-submitted jobs, dropping may silently lose important work. Recent .NET APIs also provide an item-dropped callback on relevant overloads so a deliberate loss can be observed.

Avoid Channel.CreateUnbounded for an uncontrolled producer. It has no capacity ceiling, so a slow consumer can allow queued items to grow. Unbounded channels are reasonable when the producer count and maximum burst are demonstrably small, or when the program has another hard limit.

Handle cancellation and completion

The example completes the writer in a finally block so the reader’s ReadAllAsync loop ends after queued items are drained. A hosted service should tie producer and consumer lifetimes to the host’s cancellation token and decide whether shutdown drains existing work or stops promptly. Pass a cancellation token to WriteAsync or ReadAllAsync where appropriate. If a writer completes with an error, readers can observe that completion when the channel is exhausted.

Multiple consumers share work rather than each receiving a copy. If every subscriber must see each event, use separate channels or a pub/sub design. Channels also do not provide job persistence, retry counts, delayed delivery or dead-letter storage by themselves; implement those requirements explicitly or select a durable queue service.

Size the capacity with a reason

Capacity four in the sample is for illustration, not a performance recommendation. Estimate how many items can safely wait and the memory footprint of each item. If each payload holds a large byte array, even a modest count may consume substantial memory. Prefer queueing identifiers and loading large data later when that is safe.

Watch queue depth, item age, processing duration and dropped-item count. A channel that is always full means demand exceeds worker capacity; raising the bound only postpones the pressure and increases memory use. Add readers only if the work is independent and downstream systems can handle the concurrency.

Common mistakes

  • Using drop modes for work that cannot be lost.
  • Creating an unbounded channel for traffic with no hard upper limit.
  • Setting SingleWriter or SingleReader to true without enforcing that constraint.
  • Forgetting to complete the writer, leaving a consumer waiting forever.
  • Assuming an in-memory channel survives a process restart.

For smaller asynchronous operations, see how to pass cancellation tokens through C# async methods. If the data has a calendar date rather than an instant, model it with .NET DateOnly and TimeOnly instead of putting timestamps into a work item unnecessarily.

My Take

The best part of a bounded channel is the decision it forces: wait, discard, or persist elsewhere. I’d start with Wait for work that matters, instrument the wait, and only choose a drop mode after the product owner agrees which data can be lost.

Bottom Line

Bounded channels give in-process async pipelines a clear capacity limit. Choose the full policy from the value of the data, wire completion and cancellation into shutdown, and use a durable queue when jobs must survive restarts.

Sources