# What happens when an instance multiplexes N agent sessions over one MCP stdio transport and backpressure collapses the session boundary **Date of Record:** 2026 December 4 **Scope:** Applies to MCP server implementations that multiplex multiple logical agent sessions over a single transport (stdio pipe or a single WebSocket), where per-session framing and flow control are managed by the server rather than by the transport. Does not apply to one-connection-per-session deployments or to transports with native stream isolation (e.g., one HTTP/2 stream per session with independent flow-control windows). ## Core Distinction The failure is not "the server got slow." It is the collapse of the *session boundary* under write backpressure. In a multiplexed MCP server, each logical session (identified by `sessionId` in the framing envelope) owns an independent request/response state machine: outstanding `tools/call` requests, pending `sampling/createMessage` callbacks, and capability negotiation state. The transport, however, is a **single shared byte stream with a single kernel buffer**. When one client stops reading—because its agent loop is blocked on a long tool call, because its context window assembler is stalled, or because it simply crashed without closing the pipe—the shared write buffer fills. The server's `write()` to the transport then blocks or drops, and *every* session multiplexed on that transport inherits the stall. The invariant that must hold is: **a stalled session must not be able to consume shared transport write capacity in a way that prevents a healthy session from making progress.** Most multiplexers violate this invariant silently because they treat the transport as a reliable sink and only discover the coupling at saturation. This is distinct from ordinary head-of-line blocking in HTTP/1.1 pipelining, because the blocked unit here is not a request but a *session's entire outbound queue*, and the trigger is a probabilistic agent behavior (variable-latency tool calls, context assembly stalls) rather than a slow client network. ## What Was Observed A server multiplexing 40 agent sessions over one stdio pipe, with a per-session outbound queue (unbounded, `asyncio.Queue`) and a single writer coroutine draining queues round-robin into the pipe. Under normal load, p99 `tools/call` latency was 180 ms. The failure trace: 1. Session S17 issued a `tools/call` to a slow upstream (a browser-automation tool averaging 40 s). Its agent loop then blocked awaiting the result and **stopped reading from the pipe**—the client's read loop was single-threaded and gated behind the pending call. 2. The server continued to emit `notifications/progress` for S17's in-flight call, plus `notifications/message` log lines. These accumulated in S17's outbound queue. 3. The pipe's kernel buffer (64 KiB on Linux default) filled. The writer coroutine's `os.write` now blocked. 4. Because the writer was a *single* coroutine draining *all* queues, step 3 stalled delivery for sessions S01–S16 and S18–S40 as well. 5. Those sessions' agents timed out their `tools/call` requests at 30 s (client-side deadline), retried, and re-issued. The retries enqueued *more* outbound frames behind the stuck writer. 6. Within ~90 s, all 40 sessions were in client-side timeout/retry loops, the outbound queue depth crossed 200k frames, and the server OOM'd on queue memory before any single tool call had actually failed. The observable signature: **all sessions fail simultaneously with client-side timeouts, but no server-side handler raised an exception.** The server log shows healthy handler completion for every request; the failure is entirely in the write path and invisible to per-request instrumentation. The non-obvious part: the trigger was not load. It was a *single* session whose client stopped reading, and the amplification came from the shared writer plus unbounded per-session queues plus client retry storms. Any two of those three would have been survivable. ## Condition of Validity The collapse requires all of the following to hold simultaneously: - **Shared single-writer transport.** The multiplexer drains all session queues through one write path. If each session has an independent transport or an independent write buffer with its own flow-control window, the stall is isolated. - **Unbounded or generously bounded per-session queues.** If a session's outbound queue has a hard cap and the server applies *backpressure to that session* (refuses to enqueue, or tears down the session) rather than to the transport, the stall cannot propagate. The queue bound is the isolation mechanism. - **A client that stops reading without closing the connection.** A crashed client that closes the pipe triggers EOF and the server can reap the session. A client that *blocks* (agent loop gated on a pending call) keeps the pipe open and the buffer full—this is the dangerous case, and it is the *normal* case for single-threaded agent clients. - **Server-generated traffic independent of client requests.** Progress notifications, log messages, and sampling callbacks mean the server writes even when the client isn't asking. Without these, the buffer would drain as soon as the client's one outstanding request completed. If the client uses a separate reader thread (decoupled from the agent loop), condition 3 fails and the stall never occurs. This is why the bug is intermittent across client implementations and appears as "works with client A, hangs with client B." ## Decision Boundary The architectural decision is **where backpressure is applied**. There are three candidate points, and only one is correct: - **Transport-level backpressure (wrong):** block the shared writer when the pipe is full. This is what the failing server did. It converts one session's stall into a global stall. The transport is a shared resource; applying backpressure there means one tenant controls all tenants. - **Per-session queue backpressure (correct):** bound each session's outbound queue (e.g., 1024 frames or 256 KiB, whichever first). When a session's queue is full, the server must *fail that session's enqueue*, not block. The correct action is to either (a) drop low-priority frames (progress/log notifications) for that session, or (b) if a *response* frame cannot be enqueued, terminate that session with an explicit `SessionOverflow` error and close its logical channel—freeing the writer to serve healthy sessions. - **Client-side backpressure (insufficient alone):** relying on the client to read promptly. This is not a server invariant; it is a client contract the server cannot enforce. The boundary condition to encode: **the server must never block the shared writer on a per-session queue.** The writer should only ever block on the transport itself, and the transport should only ever be full of frames the server has *already decided* to send. If a session's queue is full, that is a session-level failure, not a transport-level one. A second, subtler boundary: **progress and log notifications must be droppable.** They are advisory. A response frame (`tools/call` result, `sampling` result) is not droppable—if it can't be delivered, the session is dead and must be torn down explicitly so the client's retry logic sees a clean failure rather than a timeout. Conflating the two priorities is what produces the OOM: the server queues 200k progress frames it could have dropped. ## Operational Effect After the fix—bounded per-session queues, priority-aware drop, and explicit session teardown on response-queue overflow—the same 40-session workload with the same slow tool behaved as follows: - S17's queue hit its 256 KiB cap at ~8 s. Progress frames were dropped; the response frame was held. At 30 s the client's deadline fired, the client re-issued, and the server, seeing a duplicate `requestId` on a session whose response was still pending, returned the in-flight status rather than re-executing. - Sessions S01–S16 and S18–S40 saw p99 latency of 210 ms—a 17% regression from baseline, attributable to the writer's round-robin fairness now being enforced rather than incidental. - No OOM. No global timeout cascade. The failure was contained to the one session whose client was misbehaving, which is the correct blast radius. The invariant to carry forward: **in a multiplexed MCP server, the unit of backpressure must match the unit of isolation.** The transport is shared; the session is isolated. Backpressure applied at the transport couples them and turns a single slow client into a fleet-wide outage. The queue bound is not a performance tuning knob—it is the mechanism that makes the session boundary real under saturation. ```python from __future__ import annotations import asyncio from dataclasses import dataclass, field from enum import IntEnum class SessionOverflow(RuntimeError): """Raised when a session's outbound queue cannot accept a non-droppable frame. This is a *session-level* failure. It must never propagate to the shared transport writer, because that would couple one session's stall to every other session multiplexed on the same transport. """ class Priority(IntEnum): DROPPABLE = 0 # progress notifications, log messages RELIABLE = 1 # responses, sampling callbacks, errors @dataclass class Frame: session_id: str payload: bytes priority: Priority @dataclass class SessionQueue: session_id: str max_bytes: int max_frames: int _frames: list[Frame] = field(default_factory=list) _bytes: int = 0 def enqueue(self, frame: Frame) -> None: if len(self._frames) >= self.max_frames or self._bytes + len(frame.payload) > self.max_bytes: # Queue is full. Apply backpressure *to this session only*. if frame.priority is Priority.DROPPABLE: return # silently drop advisory traffic # RELIABLE frame cannot be delivered: tear down this session, # do not block the shared writer. raise SessionOverflow( f"session {self.session_id} outbound queue full " f"({len(self._frames)} frames, {self._bytes} bytes); " f"cannot enqueue reliable frame" ) self._frames.append(frame) self._bytes += len(frame.payload) def drain_one(self) -> Frame | None: if not self._frames: return None f = self._frames.pop(0) self._bytes -= len(f.payload) return f class MultiplexWriter: """Single writer draining many session queues into one transport. Invariant: the writer never blocks on a session queue. If a session's queue raises SessionOverflow, the writer drops that session from the rotation and signals its teardown; healthy sessions keep flowing. """ def __init__(self, transport_write, sessions: dict[str, SessionQueue]): self._write = transport_write self._sessions = sessions self._dead: set[str] = set() async def run_once(self) -> int: sent = 0 for sid, q in self._sessions.items(): if sid in self._dead: continue # Drain at most one frame per session per pass: round-robin # fairness prevents one chatty session from starving others. frame = q.drain_one() if frame is None: continue try: await self._write(frame.payload) sent += 1 except SessionOverflow: # Should not reach here (overflow raised at enqueue), but # if a queue is misbehaving, isolate it rather than stall. self._dead.add(sid) except (BrokenPipeError, ConnectionResetError): # Transport-level failure: this *is* global, but it is a # transport event, not a session event. Propagate. raise return sent async def guarded_enqueue(session: SessionQueue, frame: Frame) -> None: """Public enqueue entrypoint. Translates session overflow into a teardown signal without touching the shared transport.""" try: session.enqueue(frame) except SessionOverflow as exc: # Mark session dead; the multiplexer will skip it and the client # will observe a clean channel close rather than a silent timeout. raise SessionOverflow(str(exc)) from exc ```