Phase 23 of 30 · Topic 23.2

Bounded Channels & Backpressure Overflow Modes

1Concept

Bounded channels enforce a maximum queue capacity. When full, `BoundedChannelFullMode` controls backpressure: `Wait` (slows producers), `DropOldest` (drops stale events), or `DropWrite` (rejects new incoming items).

2Architecture Diagram

Bounded Channel (Capacity: 1000)
       │ (Queue is full!)
       ├── BoundedChannelFullMode.Wait        ──> Pauses Producer until Consumer frees slot
       ├── BoundedChannelFullMode.DropOldest  ──> Drops oldest item to insert new item
       └── BoundedChannelFullMode.DropWrite   ──> Drops incoming item immediately

3Code Example

C# 13 & .NET 9
using System;
using System.Threading.Channels;
using System.Threading.Tasks;

public class BoundedChannelDemo
{
    public static async Task Main()
    {
        var options = new BoundedChannelOptions(capacity: 2)
        {
            FullMode = BoundedChannelFullMode.DropOldest,
            SingleWriter = true,
            SingleReader = true
        };

        var channel = Channel.CreateBounded<int>(options);

        // Push 3 items into capacity 2 buffer with DropOldest
        await channel.Writer.WriteAsync(10);
        await channel.Writer.WriteAsync(20);
        await channel.Writer.WriteAsync(30); // Drops 10!
        channel.Writer.Complete();

        await foreach (var val in channel.Reader.ReadAllAsync())
        {
            Console.WriteLine($"Remaining Item in Buffer: {val}");
        }
    }
}

4Expected Output

Remaining Item in Buffer: 20
Remaining Item in Buffer: 30

5Key Takeaways

  • Always use Bounded channels in production to prevent OutOfMemoryException from producer spikes.
  • `SingleWriter = true` and `SingleReader = true` enable ultra-fast lock-free optimizations.
  • `DropOldest` is ideal for real-time telemetry, IoT sensors, and UI rendering.