# Which invariants prevent HTTP-native MCP stream multiplexing from collapsing under backpressure-induced framing skew **Date of Record:** 2026 November 25 **Scope:** Applies to MCP servers exposing multiple concurrent tool-call streams over a single HTTP/1.1 or HTTP/2 connection using chunked/streamed framing (SSE, `application/x-ndjson`, or length-prefixed frames) where the client applies per-stream backpressure. Does not apply to one-shot request/response MCP transports, WebSocket-framed sessions, or stdio transports where the OS pipe provides flow control. ## Core Distinction The distinction that matters is between **transport-level backpressure** and **frame-level framing authority**. HTTP provides backpressure only at the connection or stream granularity (TCP window, HTTP/2 `WINDOW_UPDATE`, or client-side read pacing on a chunked body). It does *not* provide any notion of "pause this logical MCP message stream but keep the connection flowing." MCP multiplexing rides on top of HTTP by packing many logical message streams into one byte stream, and the frame boundaries are defined by the MCP framing layer, not by HTTP. The failure mode is **framing skew under backpressure**: when the client stops reading the socket to apply backpressure to one logical stream, the server's framing writer continues to emit frames for *other* logical streams into the same kernel socket buffer. Those frames interleave into the byte stream in an order the client never observes, because the client has stopped draining. When the client resumes, it must reconstruct logical streams from a byte sequence whose interleaving was decided by the server's write scheduler, not by any per-stream ordering the client can reason about. If the framing layer assumes "frames for stream A are contiguous until stream A's terminator," that assumption is silently violated the moment two writers share a socket and the reader pauses. The invariant that prevents collapse is: **frame atomicity must be independent of reader pacing.** A frame must be fully delimited by bytes already in the stream (length prefix or explicit terminator) such that a reader can always parse the next frame without blocking mid-frame, and a writer must never begin a frame it cannot finish in a single `write()` that is not interleaved with another stream's bytes. ## What Was Observed A representative trace from an MCP server exposing three concurrent tool streams (`A`, `B`, `C`) over one HTTP/2 connection, using newline-delimited JSON frames: 1. Client issues three `tools/call` requests, each mapped to a logical stream on the same HTTP response body. 2. Server writes frames `A1, B1, A2, B2, C1` into the socket. Kernel buffer accepts all; client reads `A1, B1, A2`, then applies backpressure because stream `A`'s consumer is slow (application-level queue full). Client stops reading the socket. 3. Server's stream `C` producer is fast and continues writing `C2, C3, C4` into the socket buffer. Server's stream `A` producer is blocked waiting for the client to drain, but the *framing writer* is a single goroutine/task that serializes all streams; it is not blocked, because it only blocks when the socket buffer is full, not when a specific logical stream is slow. 4. Client resumes reading. It now sees `B2, C1, C2, C3, C4, A3, ...`. If the client's demultiplexer buffers per-stream by scanning for the next frame for stream `A`, it has already consumed `B2` and `C1..C4` into the wrong queues — or, worse, if it uses a "current stream" cursor that assumes contiguity, it attributes `C2..C4` to stream `A`. 5. The client's stream `A` assembler receives a frame whose `id` does not match the expected next sequence and either drops it (silent data loss) or raises a framing error that tears down the whole connection, killing streams `B` and `C` too. The non-obvious part: **the server did nothing wrong at the HTTP layer.** It correctly multiplexed. The bug is that the client's demultiplexer conflated *byte-stream backpressure* with *logical-stream ordering*, and the framing layer did not carry an explicit per-frame stream identifier and sequence number that made the interleaving self-describing. ## Condition of Validity The invariant "frame atomicity independent of reader pacing" holds only when all of the following are true: - Every frame carries an explicit `stream_id` and a monotonically increasing `seq` per stream, in the frame header, *before* any payload bytes that could be partially consumed. - The framing writer emits each frame with a single atomic append to the connection's write queue, and the connection writer never splits a frame across two `write()` calls that could be reordered relative to another stream's frame. - The client demultiplexer is *stateless with respect to stream ordering*: it routes each frame purely by `stream_id` from the header, and per-stream reassembly is done by `seq`, buffering out-of-order frames up to a bounded window. - Backpressure is applied per logical stream by the client's *application consumer*, not by pausing the socket read. The socket must always be drained promptly; slow consumers cause bounded per-stream buffering and, if the bound is exceeded, an explicit per-stream `RESET_STREAM`-equivalent, never a global read pause. The invariant is **invalid** when the transport relies on reader pacing as the only flow-control signal (e.g., a naive `for line in response.iter_lines()` loop that blocks on a slow consumer), or when frames are not self-delimiting (e.g., a stream that emits a JSON array incrementally without per-element length prefixes), or when the server's writer coalesces frames from multiple streams into one `write()` without preserving frame boundaries. ## Decision Boundary The decision boundary is whether to **buffer or reset** when a per-stream consumer falls behind. Two policies are defensible; the choice determines the failure mode: - **Bounded per-stream buffer + reset on overflow.** The client drains the socket unconditionally, buffers up to `N` frames per stream, and when stream `A` exceeds `N`, it sends a per-stream cancellation and discards `A`'s buffered frames. This preserves streams `B` and `C` and converts a slow consumer into a bounded, observable per-stream failure. This is the correct default for multiplexed MCP. - **Global read pause.** The client stops reading the socket when any consumer is slow. This is only safe if the server's framing writer also blocks per-stream (i.e., the server applies per-stream send backpressure via a bounded per-stream outbound queue and never writes a frame for a stream whose queue is full). If the server does not implement that, global read pause causes framing skew and cross-stream head-of-line blocking, and the failure is silent. The boundary condition that flips the decision: if the server cannot guarantee per-stream outbound queueing (common in implementations that serialize all streams through one writer without per-stream admission control), then the client **must not** use global read pause, and must instead use bounded per-stream buffering with reset. There is no safe middle ground. ## Operational Effect The operational consequence is that **multiplexing correctness is a property of the framing layer, not the transport layer.** Teams that treat HTTP/2 stream multiplexing as "free concurrency" and layer MCP logical streams on top without per-frame stream identity and sequence numbers will observe intermittent, load-dependent cross-stream corruption that only appears when one consumer is slow — exactly the condition that never occurs in unit tests and always occurs in production under partial failure. The guardrail is a framing contract: every frame is `[stream_id][seq][length][payload]`, the writer appends frames atomically, the reader drains unconditionally and routes by header, and per-stream overflow is a per-stream reset, not a connection teardown. Violating any one of these reintroduces framing skew under backpressure. ```python import struct from collections import defaultdict FRAME_HEADER = struct.Struct(">IQI") # stream_id, seq, payload_len MAX_PER_STREAM_BUFFER = 64 class FramingSkewError(RuntimeError): """Raised when a frame's stream/seq cannot be reconciled with the demux state.""" class StreamResetError(RuntimeError): """Raised when a per-stream buffer overflows and the stream must be reset.""" class Demux: def __init__(self, max_buffer: int = MAX_PER_STREAM_BUFFER): self.max_buffer = max_buffer self.buffers: dict[int, dict[int, bytes]] = defaultdict(dict) self.next_seq: dict[int, int] = defaultdict(int) self.reset_streams: set[int] = set() def feed(self, frame: bytes) -> list[tuple[int, bytes]]: if len(frame) < FRAME_HEADER.size: raise FramingSkewError(f"short frame: {len(frame)} bytes") stream_id, seq, plen = FRAME_HEADER.unpack_from(frame, 0) payload = frame[FRAME_HEADER.size:FRAME_HEADER.size + plen] if len(payload) != plen: raise FramingSkewError( f"frame for stream {stream_id} seq {seq} truncated: " f"declared {plen}, got {len(payload)}" ) if stream_id in self.reset_streams: return [] expected = self.next_seq[stream_id] if seq < expected: raise FramingSkewError( f"stream {stream_id}: seq {seq} < expected {expected} (replay or skew)" ) if seq > expected + self.max_buffer: self.reset_streams.add(stream_id) raise StreamResetError( f"stream {stream_id}: seq {seq} exceeds window at {expected}; reset" ) self.buffers[stream_id][seq] = payload if len(self.buffers[stream_id]) > self.max_buffer: self.reset_streams.add(stream_id) raise StreamResetError( f"stream {stream_id}: buffer overflow ({len(self.buffers[stream_id])}); reset" ) ready: list[tuple[int, bytes]] = [] while self.next_seq[stream_id] in self.buffers[stream_id]: s = self.next_seq[stream_id] ready.append((stream_id, self.buffers[stream_id].pop(s))) self.next_seq[stream_id] = s + 1 return ready ```