# In what scenarios must an instance treat MCP Streamable HTTP session affinity as a resumption invariant rather than a routing hint **Date of Record:** 2026 November 24 **Scope:** Applies to MCP clients and servers using the Streamable HTTP transport (POST for requests, optional GET-initiated SSE stream for server→client messages) with `Last-Event-ID` resumption and multi-replica deployment behind a load balancer. Does not apply to stdio transport, nor to single-replica deployments where session state is co-located with every possible handler. ## Core Distinction The Streamable HTTP spec makes the `Mcp-Session-Id` header the unit of state, and the `Last-Event-ID` header the unit of resumption. These are two different invariants that deployments routinely conflate. Session affinity is usually treated as a *routing optimization*: "send the client back to the replica that holds its session so we avoid a state rebuild." Resumption is treated as a *recovery feature*: "if the SSE stream drops, replay from the last event ID." The boundary failure occurs when the two are composed. `Last-Event-ID` is only meaningful to the *specific replica* that minted that event ID, because the event ID is a per-stream monotonic cursor over an in-memory replay buffer. If the load balancer routes a resumption GET to a different replica — because the original replica was scaled down, restarted, or the affinity cookie expired — the new replica receives a syntactically valid `Last-Event-ID` it has never issued. The spec does not define a rejection path for this. The result is a silent, well-formed replay from the wrong cursor, or a fresh stream with a gap the client cannot detect. The invariant that must be enforced, and which affinity-as-hint violates: **a `Last-Event-ID` is valid only within the (session, replica-instance, stream) triple that issued it, and any replica receiving a foreign event ID MUST fail the resumption explicitly rather than serve a stream.** ## What Was Observed A three-replica MCP server behind an L7 proxy with cookie-based sticky sessions and a 15-minute affinity TTL. Sessions were minted at `initialize` and stored in a per-replica LRU. The SSE GET handler kept a ring buffer of the last N events per stream, each tagged with a monotonically increasing integer event ID scoped to the replica process (a counter, not a UUID). Trace of the failure: 1. Client `initialize` → replica A. Session `S` minted, `Mcp-Session-Id: S` returned. Affinity cookie pinned to A. 2. Client issues a long-running `tools/call` (e.g., a code-search tool) via POST. Response is `202`-style ack; the actual result will arrive on the SSE stream. Replica A emits events `1001..1043` on the stream, client processes through `1038`. 3. Client's network blips. SSE connection drops. Client has `Last-Event-ID: 1038`. 4. During the blip, replica A is evicted by the autoscaler (scale-down on low QPS). Affinity cookie still points at A's address, but A is gone. 5. Client reconnects with `GET /mcp` + `Mcp-Session-Id: S` + `Last-Event-ID: 1038`. Proxy health-checks A, finds it dead, re-pins to replica B. 6. Replica B receives session `S` (unknown to it — its LRU has no entry) and `Last-Event-ID: 1038`. B's own event counter for new streams starts wherever it happens to be — say `7`. B has no buffer entry for `1038`. 7. B's handler, written defensively, treats an unknown `Last-Event-ID` as "replay from beginning of my buffer," which is empty, and opens a fresh stream. The client sees a live stream with no backfill. Events `1039..1043` — including the `tools/call` result — are never delivered. The client hangs on a tool call that has already completed server-side. The client cannot distinguish this from "no events occurred between 1038 and now." It has no way to know the cursor was foreign. The tool call deadlocks until the client's own timeout fires, at which point the agent either retries the tool (duplicate side effects) or abandons the task (lost work). A second observed variant: replica B was running a *different build* with a different event-ID scheme (UUIDs instead of integers). The client's `Last-Event-ID: 1038` was accepted as an opaque string, and B's comparison logic (`if last_event_id < next_id`) compared `"1038" < "f47ac10b..."` lexically, concluded the client was far behind, and replayed its *entire* buffer — including events for a different session that happened to be resident. ## Condition of Validity The failure is bounded by three preconditions, all of which must hold for the silent-gap behavior to occur: 1. **Event IDs are replica-local.** If event IDs are globally unique and the replay buffer is in shared storage (Redis stream, durable log), a foreign replica can serve the resumption correctly. The failure requires the cursor to be meaningful only to its issuer. 2. **Affinity can be violated without the client noticing.** If the transport layer surfaces a replica identity (e.g., a `Mcp-Instance-Id` response header, or the session ID is bound to an instance fingerprint), the client can detect the rebind. Without that, the rebind is invisible. 3. **The server does not reject unknown cursors.** If the GET handler validates `Last-Event-ID` against its own issued-ID set and returns `409 Conflict` or `410 Gone` on a miss, the client learns resumption failed and can fall back to a full session re-establishment. The failure requires the handler to be permissive — which is the common case, because "be liberal in what you accept" is the default posture and the spec does not mandate rejection. When any one of these is broken, the failure degrades to a detectable error or a correct replay, and this record does not apply. ## Decision Boundary The decision an implementer faces is whether to make `Mcp-Session-Id` carry replica identity or to keep it opaque. The boundary: - **Keep session ID opaque, enforce cursor validation.** The GET handler maintains the set of event IDs it has issued for the session. A `Last-Event-ID` not in that set → `410 Gone` with a body instructing the client to re-`initialize`. This is correct but forces full session re-establishment on every replica eviction, which discards conversation state the client may have built up. Acceptable when sessions are cheap to rebuild; wrong when the session holds distilled agent memory that is expensive to reconstruct. - **Bind session to replica identity, reject foreign sessions.** Include an instance fingerprint in the session record (not necessarily in the ID itself — a server-side `session → instance` map suffices). A GET for a session whose recorded instance ≠ current instance → `421 Misdirected Request` (or `409`), forcing the client to re-`initialize` *and* to re-fetch any in-flight tool results via a `tools/call` status query. This preserves the resumption invariant at the cost of a mandatory status-reconciliation step on rebind. - **Make event IDs global and buffers shared.** The cursor becomes portable; any replica can serve any resumption. This is the only option that preserves mid-stream continuity across replica loss, but it requires externalizing the replay buffer, which adds latency to every event emission and a new failure mode (buffer write succeeds, in-memory stream does not). The wrong choice — and the one that produces the observed failure — is to keep event IDs local *and* accept foreign cursors, treating affinity as a best-effort hint. That combination is only safe if the client can tolerate silent gaps, which an agent mid-tool-call cannot. ## Operational Effect The downstream effect on an agent is not a clean error but a *stalled reasoning loop with an ambiguous cause*. The agent's tool call is outstanding; its SSE stream is live but silent; its own timeout is the only signal. When the timeout fires, the agent faces a choice it cannot resolve from local state: did the tool fail, or did the result get lost in transport? Retrying risks duplicate side effects (a second file write, a second payment). Not retrying risks abandoning a completed action whose result is now unreachable. The guardrail is to make resumption failure *loud and typed*. The server must distinguish "no events since your cursor" from "your cursor is not mine," and the client must treat the latter as a hard signal to reconcile in-flight operations before resuming. The code below encodes the server-side check and the client-side reconciliation trigger. ```python class ForeignResumptionCursor(RuntimeError): """Raised when a Last-Event-ID cannot be attributed to this replica's stream.""" pass class StreamReplayBuffer: """Per-replica, per-session SSE replay buffer keyed by replica-local integer IDs.""" def __init__(self, instance_fingerprint: str): self.instance_fingerprint = instance_fingerprint self._issued: dict[str, set[int]] = {} # session_id -> issued event IDs self._events: dict[str, list[tuple[int, dict]]] = {} def emit(self, session_id: str, event_id: int, payload: dict) -> None: self._issued.setdefault(session_id, set()).add(event_id) self._events.setdefault(session_id, []).append((event_id, payload)) def resume(self, session_id: str, last_event_id: str) -> list[dict]: # A cursor from another replica (or another build) will not parse as # an int this replica ever issued. Reject rather than replay blindly. try: cursor = int(last_event_id) except (TypeError, ValueError): raise ForeignResumptionCursor( f"Last-Event-ID={last_event_id!r} is not an integer cursor; " f"replica {self.instance_fingerprint} cannot attribute it. " f"Client must re-initialize and reconcile in-flight tool calls." ) issued = self._issued.get(session_id) if issued is None: raise ForeignResumptionCursor( f"Session {session_id!r} unknown to replica {self.instance_fingerprint}; " f"affinity was violated. Reject resumption." ) if cursor not in issued: raise ForeignResumptionCursor( f"Last-Event-ID={cursor} was never issued for session {session_id!r} " f"on replica {self.instance_fingerprint}. Silent gap risk; reject." ) return [p for eid, p in self._events[session_id] if eid > cursor] def handle_sse_get(buffer: StreamReplayBuffer, session_id: str, last_event_id: str) -> list[dict]: try: return buffer.resume(session_id, last_event_id) except ForeignResumptionCursor as exc: # Surface a typed 410 so the client reconciles instead of hanging. raise ForeignResumptionCursor(str(exc)) from exc ```