# Where must an instance enforce per-session credit accounting in an HTTP-native MCP multiplexer before shared transport buffers absorb cross-session backpressure? **Date of Record:** 2026 November 29 **Scope:** Applies to HTTP-native MCP servers that multiplex multiple logical sessions (streamable HTTP / SSE-per-session) over a shared connection pool or shared worker process, where per-session flow control is emulated rather than delegated to the transport. Does not apply to stdio-per-process MCP servers, where the OS pipe provides natural backpressure, nor to single-session deployments. ## Core Distinction The distinction that matters is between **transport-level backpressure** and **session-level flow control**. HTTP gives you the former for free: when a TCP send buffer fills, `write()` blocks or returns `EAGAIN`, and the kernel propagates that pressure back to the producer. MCP multiplexing gives you the latter only if you build it, because a single HTTP/2 connection (or a `multiplex`-style shared socket, or a shared worker thread pool behind a load balancer) carries many logical sessions whose message streams are independent. When one session's consumer (an agent instance mid-tool-call) stalls, the shared connection's send buffer fills, and the kernel's backpressure signal is *connection-scoped*, not *session-scoped*. The multiplexer must translate that single scalar pressure into per-session credit exhaustion. If it does not, the stalled session's unread bytes occupy the shared buffer and apply head-of-line pressure to every co-tenant session on that connection — a failure that looks like "the whole MCP server got slow" and is misdiagnosed as CPU or GC pressure. ## What Was Observed A streamable-HTTP MCP server fronted by an HTTP/2 terminator was serving ~40 concurrent agent sessions per connection. Session `A` issued a `tools/call` for a long-running operation and its client stopped reading the SSE response stream — the agent instance had entered a reasoning pause and was not draining `response.body`. The server kept writing `notifications/progress` frames for `A` into the shared HTTP/2 connection's send queue. The terminator's per-stream flow-control window (HTTP/2 `SETTINGS_INITIAL_WINDOW_SIZE`, default 65,535 bytes) filled for stream `A`. HTTP/2 flow control is *per-stream*, so in principle this should have isolated `A`. It did not, because the server's application layer had a single `asyncio.Queue` per connection feeding all sessions, and the writer coroutine for the connection blocked on the first `await writer.drain()` that hit the full stream window for `A`. That single blocked `drain()` suspended the connection writer coroutine, which was the only consumer of the shared queue. Sessions `B` through `AN` had their outbound frames queued behind `A`'s undrained progress notifications. Within ~4 seconds, 39 healthy sessions reported MCP client-side timeouts on `tools/list` and `ping`. The trace signature: one session's `send_queue_depth` climbing monotonically while all other sessions' `last_write_timestamp` froze simultaneously — a single-writer starvation, not a per-session stall. ## Condition of Validity The invariant that must hold is: **a session's outbound buffer must be bounded and accounted before it enters any shared transport buffer, and a session that exhausts its credit must be suspended or terminated without suspending the shared writer.** This is valid only when the multiplexer owns per-session credit accounting *upstream* of the shared writer. Concretely, the per-session queue must be a bounded `asyncio.Queue(maxsize=N)` whose `put_nowait` raises `QueueFull` when the session's credit is exhausted, and the shared writer must never `await` on a single session's `drain()` in a way that blocks other sessions. The correct pattern is: shared writer iterates ready sessions round-robin, writes one frame, calls `drain()` with a bounded timeout, and on timeout marks that session's transport as `backpressured` and skips it for the next round. The session-level credit is the guardrail; the transport drain is only a liveness probe. The condition fails — and the invariant is violated — whenever the shared writer's `drain()` is the *only* backpressure mechanism. In that regime the kernel's connection-scoped signal is the sole governor, and it cannot distinguish sessions. ## Decision Boundary The boundary is reached when `sum(per_session_outbound_bytes) > connection_send_buffer_bytes`. Below that threshold, connection-level backpressure and session-level flow control are observationally equivalent — the connection never fills, so no session ever starves another. Above it, the two diverge sharply, and the multiplexer must have already been enforcing per-session credit. The decision for operators: if you cannot bound per-session outbound bytes to a known fraction of the connection buffer, you must either (a) dedicate a connection per session (defeating multiplexing's purpose but restoring isolation), or (b) implement explicit per-session credit with a suspension policy. There is no middle ground where the shared writer can safely block on one session's stream window. The suspension policy must specify: on credit exhaustion, does the session get `notifications/cancelled` for its in-flight request, or is it held with a `progress` heartbeat suppressed? For MCP, the correct choice is to send a JSON-RPC error with code `-32000` (server-defined) and close the session's logical stream, because a stalled agent instance will not resume reading without an external trigger, and holding the session open consumes credit indefinitely. ## Operational Effect With per-session credit accounting in place, a stalled session's `put_nowait` raises `QueueFull` at the session queue boundary, the multiplexer emits a terminal error frame for that session and closes its stream, and the shared writer continues draining healthy sessions without ever observing the stalled session's window. The observable effect is that one agent instance's failure to drain becomes a single-session termination event with a bounded blast radius, rather than a connection-wide latency collapse. The cost is that you must size `maxsize` per session against the expected `notifications/progress` burst rate — too small and healthy slow consumers get killed; too large and the credit bound exceeds the connection buffer and the invariant is vacuous. The safe sizing rule is `maxsize * frame_size < connection_send_buffer_bytes / expected_sessions_per_connection`, with headroom for the largest single tool response. The secondary effect is diagnostic: with credit accounting, the failure surfaces as a `SessionCreditExhausted` event tagged with the offending session ID, which is directly actionable. Without it, the failure surfaces as correlated timeouts across unrelated sessions and is routinely misattributed to the reasoning loop rather than the transport multiplexer. ```python import asyncio from dataclasses import dataclass, field class SessionCreditExhausted(RuntimeError): """Raised when a session's outbound credit is spent before the shared writer drains it.""" pass @dataclass class Session: session_id: str max_outbound_bytes: int outbound: asyncio.Queue = field(default_factory=asyncio.Queue) bytes_queued: int = 0 backpressured: bool = False class MultiplexedWriter: def __init__(self, connection_send_buffer_bytes: int): self.connection_send_buffer_bytes = connection_send_buffer_bytes self.sessions: dict[str, Session] = {} def register(self, session_id: str, max_outbound_bytes: int) -> Session: if max_outbound_bytes >= self.connection_send_buffer_bytes: raise SessionCreditExhausted( f"session {session_id} credit {max_outbound_bytes} >= connection buffer " f"{self.connection_send_buffer_bytes}; invariant vacuous" ) s = Session(session_id=session_id, max_outbound_bytes=max_outbound_bytes) self.sessions[session_id] = s return s def enqueue(self, session_id: str, frame: bytes) -> None: s = self.sessions[session_id] if s.bytes_queued + len(frame) > s.max_outbound_bytes: s.backpressured = True raise SessionCreditExhausted( f"session {session_id} would exceed credit: " f"{s.bytes_queued}+{len(frame)} > {s.max_outbound_bytes}" ) s.outbound.put_nowait(frame) s.bytes_queued += len(frame) async def run_writer(self, writer) -> None: while True: progressed = False for s in list(self.sessions.values()): if s.backpressured or s.outbound.empty(): continue frame = s.outbound.get_nowait() writer.write(frame) s.bytes_queued -= len(frame) try: await asyncio.wait_for(writer.drain(), timeout=0.05) except asyncio.TimeoutError: s.backpressured = True self._terminate(s, code=-32000, reason="transport backpressure") progressed = True if not progressed: await asyncio.sleep(0.001) def _terminate(self, s: Session, code: int, reason: str) -> None: # Emit a terminal JSON-RPC error for this session only; never block the shared writer. s.outbound.put_nowait( b'{"jsonrpc":"2.0","error":{"code":%d,"message":"%s"}}' % (code, reason.encode()) ) s.bytes_queued = 0 s.backpressured = True ```