# Under what conditions must an instance pin MCP streamable-HTTP sessions to a single replica before backpressure can be trusted **Date of Record:** 2026 November 30 **Scope:** Applies to MCP servers using the streamable-HTTP transport with multiple replicas behind a load balancer, where a single logical session spans a POST request stream and a paired GET SSE stream. Does not apply to stdio transport, single-replica deployments, or stateless JSON-RPC-over-HTTP shims where each request is fully self-contained. ## Core Distinction There are two distinct kinds of "connection" in the streamable-HTTP MCP transport, and conflating them is the root of the failure. The **transport connection** is the TCP/TLS socket the LB sees. The **session** is a server-assigned identifier (`Mcp-Session-Id`) that binds a POST request-stream and a GET event-stream into one logical conversation with shared server state: the request/response correlation table, the SSE event queue, and the backpressure watermark. A load balancer balances transport connections. It has no concept of the session. Therefore, under concurrency, the POST stream and the GET stream for the *same* session will land on *different* replicas unless affinity is explicitly enforced at the session layer, not the connection layer. When they split, the replica holding the GET stream has no request table to drain, and the replica holding the POST stream has an event queue with no consumer. Backpressure — which is a *per-session* invariant — is silently violated because each replica independently believes the session is healthy. ## What Was Observed A four-replica MCP server behind a round-robin LB with keep-alive enabled. A single agent client opened a session, issued `initialize`, received `Mcp-Session-Id: s-7f3a`, then opened the GET SSE stream and began issuing `tools/call` POSTs concurrently from a worker pool of eight. Trace of the failure: 1. `initialize` POST → replica R1. R1 creates session `s-7f3a`, stores request table and empty event queue, returns the ID. LB records R1 for the *connection*. 2. Client opens GET SSE stream on a *new* connection (the transport spec permits this). LB hashes the new connection → R2. R2 receives `GET /mcp` with `Mcp-Session-Id: s-7f3a` for a session it has never seen. Depending on implementation it either (a) returns `404 Session not found`, which the client interprets as session death and re-initializes, or (b) lazily creates an empty shadow session and holds the SSE open — the dangerous case. 3. Eight `tools/call` POSTs fire concurrently. Keep-alive is on, but the worker pool uses fresh connections for the first burst; LB distributes them across R1, R3, R4. R3 and R4 have no session `s-7f3a`; they return `404`, client retries, retries land on R1 by chance for some, on R2/R3/R4 for others. 4. On R1, the requests that did land enqueue SSE events into R1's event queue. But the GET stream is held by R2. R1's queue grows unbounded because its backpressure watermark is computed as "events pending / consumer drain rate," and R1 believes there is no consumer, so it applies the *no-consumer* policy: buffer indefinitely up to a hard cap, then drop oldest. 5. R2's shadow session emits nothing (it has no requests). The client sees a live SSE stream that never delivers results. Requests that landed on R1 time out at the client after 30s. The client, per its own retry policy, re-issues — amplifying load exactly when R1's queue is saturated. The observable signature: **client-side request timeouts with a server-side event queue at its cap, on a replica the client never addressed, while a healthy-looking SSE stream sits idle on a different replica.** No single replica's metrics show the failure; the failure is in the *split*. ## Condition of Validity Session-pinned backpressure is valid if and only if all three hold simultaneously: - **Affinity is session-keyed, not connection-keyed.** The LB (or an ingress rule) routes on `Mcp-Session-Id` (header or path segment), not on source-IP hash or round-robin. Connection-level affinity is insufficient because the spec permits the GET stream on a separate connection. - **The session directory is authoritative and replicated.** A replica receiving a request for an unknown session must *not* lazily create a shadow. It must consult a shared session directory (consistent hash ring, Redis lease, or gossip) and either proxy to the owner or return a retryable `421 Misdirected Request` with the owner hint. Lazy creation converts a routing error into silent state divergence. - **The backpressure watermark is computed against the actual consumer, not a local guess.** The replica that owns the event queue must know whether the GET stream is attached and its drain rate. If the GET stream is on another replica, the watermark must be derived from cross-replica signal (a shared counter updated by the SSE replica as it flushes), not from local socket state. If any of the three fails, backpressure is not a bound — it is a local heuristic that the system's routing can invalidate at any moment. ## Decision Boundary The boundary is **whether the GET stream and the POST stream for a session can be routed independently.** If the transport guarantees they share a connection (many clients do this by default, and some servers enforce it), connection affinity suffices and the whole class of failure is out of scope. If the transport permits them to split — and the streamable-HTTP spec does — then session-keyed affinity is mandatory *before* any backpressure policy is meaningful. A secondary boundary: **retry semantics.** A `404 Session not found` on a POST is ambiguous between "session expired" and "wrong replica." Treating it as expiry triggers re-initialization, which is correct only if the session directory confirms expiry. Treating it as a routing miss triggers retry-with-hint, which is correct only if the directory is authoritative. The decision hinges on whether the directory is the source of truth or a cache. If it is a cache, `404` must be non-authoritative and retried; if authoritative, it must be terminal. Mixing the two produces the retry-amplification seen in step 5. ## Operational Effect When the invariant holds, backpressure bounds memory per session and the client sees monotonic progress: each `tools/call` result arrives on the same SSE stream that carries its correlation ID. When it breaks, three effects compound: 1. **Silent queue divergence.** The owning replica buffers events no consumer will read; memory grows to the hard cap, then events are dropped. The client's requests time out with no error from the server — the worst failure mode, because it looks like latency, not loss. 2. **Retry amplification under saturation.** Client retries land on the same saturated replica (the directory still points there) or on shadow replicas (which 404 and re-trigger). Load peaks exactly when the system is least able to absorb it. 3. **Shadow-session ghost streams.** Lazily created sessions on non-owning replicas hold SSE connections open indefinitely, consuming connection slots and LB capacity with zero useful work. These are invisible to per-replica health checks because the replica is "healthy" — it just has a stream attached to nothing. The guardrail is structural: **session-keyed affinity plus an authoritative session directory plus cross-replica drain signaling.** Backpressure is only a bound when the consumer and the producer are provably on the same replica or provably sharing a drain counter. ```python import hashlib from dataclasses import dataclass, field from typing import Optional class SessionAffinityError(RuntimeError): """Raised when a session's POST and GET streams resolve to different replicas without an authoritative directory or drain signal to reconcile them.""" @dataclass class SessionState: session_id: str owner_replica: str get_stream_attached: bool = False get_stream_replica: Optional[str] = None pending_events: int = 0 drain_rate: float = 0.0 hard_cap: int = 10_000 @dataclass class Replica: name: str sessions: dict = field(default_factory=dict) def route_get_stream(session: SessionState, replica: Replica, directory_authoritative: bool) -> None: """Attach a GET SSE stream to a replica, enforcing the affinity invariant.""" if session.session_id not in replica.sessions: # Replica does not own this session. Lazy shadow creation is forbidden. if not directory_authoritative: raise SessionAffinityError( f"replica {replica.name} received GET for session {session.session_id} " f"owned by {session.owner_replica}; directory is non-authoritative so " f"a shadow session would diverge silently" ) # Authoritative directory: must redirect to owner, not create a shadow. raise SessionAffinityError( f"replica {replica.name} is not the owner of session {session.session_id}; " f"redirect to {session.owner_replica} via 421 Misdirected Request" ) if session.get_stream_attached and session.get_stream_replica != replica.name: raise SessionAffinityError( f"session {session.session_id} already has GET stream on " f"{session.get_stream_replica}; second attach on {replica.name} " f"would split the event queue" ) session.get_stream_attached = True session.get_stream_replica = replica.name def apply_backpressure(session: SessionState, replica: Replica, cross_replica_drain: Optional[float]) -> bool: """Return True if the session may accept another request under backpressure.""" if session.pending_events >= session.hard_cap: # At cap; only proceed if the consumer is draining. effective_drain = cross_replica_drain if cross_replica_drain is not None else session.drain_rate if effective_drain <= 0.0: raise SessionAffinityError( f"session {session.session_id} at hard cap ({session.hard_cap}) with " f"zero drain signal; consumer may be on {session.get_stream_replica} " f"while producer is on {replica.name}" ) return True return True def issue_request(session: SessionState, replica: Replica, directory_authoritative: bool, cross_replica_drain: Optional[float]) -> None: if session.session_id not in replica.sessions: raise SessionAffinityError( f"POST for session {session.session_id} landed on non-owner {replica.name}" ) apply_backpressure(session, replica, cross_replica_drain) session.pending_events += 1 if session.get_stream_replica != replica.name and session.get_stream_replica is not None: # Event will be queued on a replica whose GET stream is elsewhere. if cross_replica_drain is None: raise SessionAffinityError( f"session {session.session_id}: event queued on {replica.name} but GET " f"stream is on {session.get_stream_replica} with no cross-replica drain " f"counter; queue will grow unobserved" ) ```