---
title: "Handle stdio backpressure in C#"
url: https://recursiveai.org/onemodelcontext/cookbook/handle-stdio-backpressure/
description: "See a slow local pipe reader pause Model Context Protocol® replies in C#, then drain the OneModelContext stdio queue to resume writes."
version: "1.0.2"
---

# Handle stdio backpressure in C#

**OneModelContext** is a free, open-source .NET SDK for the Model Context Protocol® from Recursive AI. MIT or Apache-2.0, no native dependencies.

[NuGet](https://www.nuget.org/packages/RecursiveAI.OneModelContext) · [GitHub](https://github.com/recursive-ai-oss/onemodelcontext-csharp) · [Docs](https://recursiveai.org/onemodelcontext/docs/) · [Download example (.zip)](https://recursiveai.org/onemodelcontext/cookbook/handle-stdio-backpressure/handle-stdio-backpressure.zip)

When a client reads replies slowly, keep reading while writes wait for space.

```shell
dotnet add package RecursiveAI.OneModelContext
```

Requires [.NET 10](https://dotnet.microsoft.com/download/dotnet/10.0) (net10.0); .NET 9 and earlier aren’t supported.

```shell
# In the downloaded project
dotnet run
```

Unzip [the example](https://recursiveai.org/onemodelcontext/cookbook/handle-stdio-backpressure/handle-stdio-backpressure.zip), then `dotnet run`.

```text
Third reply waits for queue space.
Read reply 1.
Read reply 2.
Read reply 3.
```

## The full program

The demo uses `NewlineChannel`, the same line framing used for standard input and output (stdio). It uses a local pipe in place of child-process stdout so it can control exactly when the reader stops and starts. Each reply contains a generated 768 KiB string; there’s no input file.

The reader takes one byte, then pauses. One reply is in flight and a second fits in the 1 MiB queue, but a third doesn’t fit alongside the second. Start draining while that third write is pending. If the reader never resumes, the example’s cancellation token stops the wait.

```csharp
using System.IO.Pipes;
using System.Text;
using System.Text.Json;
using RecursiveAI.OneModelContext.JsonRpc;

using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(15));
var stop = timeout.Token;
var name = $"backpressure-{Guid.NewGuid():N}";
await using var output = new NamedPipeServerStream(name, PipeDirection.Out, 1,
    PipeTransmissionMode.Byte, PipeOptions.Asynchronous, 0, 4096);
await using var input = new NamedPipeClientStream(".", name, PipeDirection.In,
    PipeOptions.Asynchronous);
await Task.WhenAll(output.WaitForConnectionAsync(stop), input.ConnectAsync(stop));

await using var sender = new NewlineChannel(Stream.Null, output, leaveOpen: true);
using var reader = new StreamReader(input, Encoding.UTF8, leaveOpen: true);
var padding = new string('x', 768 * 1024);
byte[] Reply(int id) => JsonSerializer.SerializeToUtf8Bytes(new
{
    jsonrpc = "2.0", id, result = padding
});

if (args is ["read-first"])
{
    await Task.WhenAll(DrainRepliesAsync(), SendRepliesAsync());
    return;
}

await sender.WriteAsync(Reply(1), stop);
// Read one byte to know the first block reached the pipe, then pause.
var firstByte = new byte[1];
await input.ReadExactlyAsync(firstByte, stop);
if (firstByte[0] != (byte)'{')
    throw new InvalidDataException("Expected a JSON object.");
await sender.WriteAsync(Reply(2), stop);
var third = sender.WriteAsync(Reply(3), stop).AsTask();
if (third.IsCompleted)
    throw new InvalidOperationException("Expected the third write to wait.");
Console.WriteLine("Third reply waits for queue space.");

// Drain while the pending write is still waiting. Do not await it first.
await Task.WhenAll(third, DrainRepliesAsync(firstByteRead: true));

async Task SendRepliesAsync()
{
    for (int id = 1; id <= 3; id++)
        await sender.WriteAsync(Reply(id), stop);
}

async Task DrainRepliesAsync(bool firstByteRead = false)
{
    for (int expected = 1; expected <= 3; expected++)
    {
        var line = await reader.ReadLineAsync(stop)
            ?? throw new IOException("The pipe closed before all replies arrived.");
        // Restore the opening brace if the demo already read it.
        using var reply = JsonDocument.Parse(expected == 1 && firstByteRead ? "{" + line : line);
        var id = reply.RootElement.GetProperty("id").GetInt32();
        if (id != expected || reply.RootElement.GetProperty("result").GetString() != padding)
            throw new InvalidDataException("Unexpected reply.");
        Console.WriteLine($"Read reply {id}.");
    }
}
```

## Variations

### Start draining before sending

The `read-first` branch starts the receive loop and send loop together:

```shell
dotnet run -- read-first
```

Its two loops join with:

```csharp
await Task.WhenAll(DrainRepliesAsync(), SendRepliesAsync());
```

```text
Read reply 1.
Read reply 2.
Read reply 3.
```

## Related recipes

- [Connect to a server in C#](https://recursiveai.org/onemodelcontext/cookbook/connect-to-a-server/)
- [Close a stdio client cleanly](https://recursiveai.org/onemodelcontext/cookbook/close-stdio-client-cleanly/)

---

## The short answer

For a Model Context Protocol® client using stdio, read replies while you write requests. Don’t send an entire batch and start reading only after every write completes. OneModelContext bounds its outgoing queue and also pauses input when the output queue is full. A client that waits to read can get stuck: the server needs space to write replies before it will take more input, but the client is waiting for the server to take that input.

## Why does a stdio client hang when it sends a batch of requests?

The process’s input and output use separate pipes. Each pipe can buffer some bytes, but neither has unlimited room. If the client only writes, the server can eventually fill its outgoing pipe and then its reply queue. Once that queue is full, the server stops reading more requests until output can move. The total request size at which you see a stall depends on the requests, the replies, and the pipe buffers; the 1 MiB figure is the library’s outgoing queue bound, not an operating-system pipe size or a maximum batch size.

A client with separate send and receive loops can keep accepting replies while request writes wait. If you’re using a raw process transport, put only protocol messages on stdout and route diagnostics to stderr. Request handlers may run concurrently and replies can arrive out of order, so match each reply to its request ID rather than assuming that the next line belongs to the oldest request. The sample sends three already-formed replies in order to isolate the output queue; it isn’t testing handler execution order.

In [Connect to a server in C#](https://recursiveai.org/onemodelcontext/cookbook/connect-to-a-server/), `ModelContext.ConnectAsync` starts the calculator as a child process. OneModelContext runs the receive loop on the child’s stdout while calls write to its stdin, so you don’t write a separate read loop.

## How much output does the stdio transport buffer?

`NewlineChannel` queues up to 1 MiB, including the newline after each message. In version 1.0.2, `NewlineChannel.MaxQueuedBytes` is a constant; there’s no option to change it. `ProcessTransportOptions.MaxLineBytes` limits the length of one incoming line, not the output queue. It accepts a single larger message into an empty queue. There can also be one write block in flight to the stream, separate from the queue. The writer waits for room before the channel copies a message into a full queue. That wait doesn’t mean the reader got the message; a completed write can mean the bytes were accepted into the queue.

The pipe example exercises that distinction directly. It waits until the first reply has begun reaching the pipe, then puts the second into the queue and checks that the third can’t complete yet. Reading frees pipe space so the sender can move its next block out of the queue. The program waits for all three complete replies, rather than declaring success when the last write is accepted.
