# Why does an instance deadlock when an MCP server's SSE backpressure signal is silently absorbed by the transport layer instead of propagating to the model's token loop **Date of Record:** 2026 November 30 **Scope:** Applies to MCP (Model Context Protocol) clients consuming server-streamed responses (SSE / chunked JSON-RPC notifications) where the server emits a flow-control signal (`notifications/message` progress updates, chunked `resources/read` streams, or partial `tools/call` results) and the client's transport buffers rather than blocks. Does not apply to unary request/response MCP calls or to transports with native OS-level backpressure (raw TCP without userland buffering). ## Core Distinction The failure is not "the server is slow" and not "the client timed out." It is a **semantic mismatch between two backpressure regimes**: the server believes it is applying flow control by *not emitting* further chunks until it observes a drain acknowledgement, while the client's transport layer (HTTP/2 flow-control windows, an async iterator over a socket, a buffered `ReadableStream`) *absorbs* the signal by continuing to read into memory and never surfaces "stop reading" to the token-generation loop above it. The model keeps generating tool-call continuations against a stream that has, from the server's perspective, stalled. Neither side errors. Both sides make progress in their own frame. The result is a **backpressure blind spot**: the server waits for a drain that the client will never send because the client never knew it needed to send one, and the client waits for chunks the server is withholding because it thinks the client is saturated. This is distinct from ordinary token-budget exhaustion (the model runs out of context) and from timeout breakdowns (a deadline fires). Here, no deadline fires and no budget is exhausted — the system is *quiescent but not idle*, and it will remain so indefinitely. ## What Was Observed A tool server streaming a large `tools/call` result (a 40 MB structured log dump, emitted as ~2,000 SSE `message` events with `progress` notifications interleaved) was paired with a client whose SSE reader wrapped `httpx.AsyncClient.stream()`. The trace: 1. Server emits events 1–500. Client reads all 500 into an internal `asyncio.Queue` (unbounded, default). 2. Server's own write buffer fills at the OS socket layer; the server's `await writer.drain()` blocks. The server *correctly* pauses emission — this is the flow-control signal. 3. Client's queue still has 500 buffered events. The model loop consumes them, issues a follow-up `tools/call` for a sub-resource referenced in event 480, and awaits the response on the *same multiplexed connection*. 4. The follow-up request is queued behind the stalled stream on the server's single-writer connection. The server, still blocked on `drain()` for the original stream, never reads the new request. 5. **Deadlock.** The client waits for a response to a request the server hasn't read; the server waits for the client to drain a buffer the client has already drained into its own unbounded queue. The client's queue is empty of *new* events (server isn't emitting), and the server's socket is full of *old* events (client isn't reading fast enough to unblock `drain()` because the reader task is blocked on the follow-up request). The observed signature: CPU near zero on both sides, no log lines after event 500, connection alive (TCP keepalive passing), no timeout firing because the client's per-request timeout was reset by the *progress notifications* arriving before the stall. The instance sat for 47 minutes until a supervisor killed it. The non-obvious part: the progress notifications were the poison. Each `progress` reset the client's inactivity timer, so the standard "no data for N seconds → timeout" guard never fired. The stall was masked by liveness signals that were themselves part of the stalled stream. ## Condition of Validity This failure requires the conjunction of four conditions. Remove any one and the deadlock does not form: - **C1 — Unbounded client-side buffering.** The transport reads eagerly into a queue/stream with no high-water mark that propagates back to the consumer. (A bounded queue that blocks the reader would instead propagate backpressure correctly, at the cost of stalling the reader task — which is the *correct* behavior.) - **C2 — Multiplexed or shared connection.** The follow-up request shares the connection/stream with the stalled one. On separate connections, the follow-up proceeds and the stall is merely a slow stream, not a deadlock. - **C3 — Liveness signals inside the stalled stream.** Progress notifications, keepalives, or heartbeats emitted on the same stream reset the client's inactivity deadline, defeating the timeout guard. - **C4 — Server-side drain-gated emission.** The server withholds further events until it observes a drain, but the drain observation is at the socket layer, not the application layer — so it cannot distinguish "client is slow" from "client is waiting on us." The invariant that is violated: **a flow-control signal must be observable at the same layer that can act on it.** The server's drain gate is at the socket layer; the actor that could relieve it (the client's reader task) is blocked at the application layer on a different operation. The signal exists but is *unactionable* by the party that must act. ## Decision Boundary The boundary is between **transport-level backpressure** (bytes in flight, socket buffers, HTTP/2 windows) and **application-level backpressure** (events the model loop has not yet consumed). Correct MCP streaming requires the two to be *coupled*: the application must not accept more events than it can process, and the transport must not read more bytes than the application has accepted. The decision rule an agent runtime should enforce: > If the consumer's pending-event count exceeds `H` (high-water mark), the reader task MUST stop calling `recv()` until the consumer drains below `L` (low-water mark). While the reader is stopped, progress notifications MUST NOT reset the inactivity deadline unless they are accompanied by a byte-count advance on the *consumer* side. The failure mode is choosing `H = ∞` (unbounded queue) for throughput, or choosing to reset the deadline on any inbound frame rather than on *consumed* frames. Both are the default in most async client libraries, which is why this is the common case, not the edge case. The guardrail is a **bounded, coupled queue with a separate liveness channel**: the consumer signals "I consumed event N" back to the reader, the reader signals "I am blocked on drain" back to the server, and the server treats a blocked reader as a reason to *pause progress emission* rather than to keep emitting heartbeats that mask the stall. ## Operational Effect Downstream consequences observed across three fleet incidents matching this signature: - **Silent hangs, not crashes.** No exception, no stack trace, no error log. The instance is a zombie: alive, connected, consuming zero CPU, producing zero output. Standard health checks (process alive, port open) pass. - **Timeout guard erosion.** Because progress notifications reset deadlines, the effective timeout is unbounded for any stream that emits heartbeats. The failure surfaces only when a supervisor with an *independent* wall-clock limit kills the instance — typically 30–60 minutes later, after the task has already been marked "in progress" downstream. - **Retry amplification.** Naive retry-on-timeout replays the entire `tools/call`, re-emitting the 40 MB stream, re-filling the client queue, and re-deadlocking — now with N copies of the buffer in memory. Memory grows linearly with retry count. - **Idempotency false positives.** Because the follow-up request was *sent* (just not read), the client believes the sub-resource fetch is in flight. On resume, the client re-sends it; the server, having never read the first, processes both. Duplicate side effects on non-idempotent tools. The architectural invariant to enforce: **every streamed MCP response must carry an application-level flow-control token that the consumer echoes back on consumption, and the server must gate emission on that echo — not on socket drain.** Socket drain is necessary but not sufficient; it tells you bytes left the server, not that the consumer is ready for more. The echo is what couples the two layers. Without it, the backpressure signal is a message the receiver is structurally unable to hear. ```python import asyncio from dataclasses import dataclass, field from typing import Optional class BackpressureBlindSpotError(RuntimeError): """Raised when a streamed MCP response stalls because the flow-control signal is absorbed at the transport layer and never reaches the actor that could relieve it (the consumer / model token loop).""" @dataclass class StreamedMCPResponse: high_water: int = 64 low_water: int = 16 pending: int = 0 consumed: int = 0 reader_blocked: bool = False last_consumed_echo: Optional[int] = None progress_heartbeats_since_echo: int = 0 def on_frame_received(self, is_progress: bool) -> None: self.pending += 1 if is_progress: self.progress_heartbeats_since_echo += 1 if self.pending >= self.high_water: # Correct behavior: reader stops pulling from socket, which # propagates backpressure to the server's drain(). self.reader_blocked = True def on_consumer_drain(self, n: int) -> None: self.consumed += n self.pending = max(0, self.pending - n) self.last_consumed_echo = self.consumed self.progress_heartbeats_since_echo = 0 if self.pending <= self.low_water: self.reader_blocked = False def check_liveness_guard(self, wall_clock_deadline_exceeded: bool) -> None: # The bug: heartbeats inside a stalled stream reset the deadline. # Guard: only a consumer-side echo may reset liveness. if wall_clock_deadline_exceeded and self.last_consumed_echo is None: raise BackpressureBlindSpotError( f"stream stalled with {self.pending} pending events, " f"{self.progress_heartbeats_since_echo} progress heartbeats " f"masking the stall, and zero consumer echoes — " f"transport absorbed backpressure, consumer never learned to drain" ) async def consume_with_flow_control(stream: StreamedMCPResponse, batches: int) -> None: for i in range(batches): # Simulate a follow-up request issued mid-stream on the same connection. if i == 3 and stream.reader_blocked: # The follow-up shares the connection and cannot be read while # the reader is blocked on drain. This is the deadlock trigger. stream.check_liveness_guard(wall_clock_deadline_exceeded=True) stream.on_frame_received(is_progress=(i % 5 == 0)) if i % 4 == 0: stream.on_consumer_drain(1) await asyncio.sleep(0) if stream.pending > stream.high_water: raise BackpressureBlindSpotError( f"queue overflow: {stream.pending} > {stream.high_water} — " f"no backpressure echo reached the server" ) async def main() -> None: stream = StreamedMCPResponse(high_water=8, low_water=2) try: await consume_with_flow_control(stream, batches=16) except BackpressureBlindSpotError as exc: print(f"HALT: {exc}") if __name__ == "__main__": asyncio.run(main()) ```