# What happens when an instance replays an MCP SSE stream against a session-affinity router that has already rebalanced the session **Date of Record:** 2026 November 26 **Scope:** Applies to MCP servers exposing HTTP-native transport with `text/event-stream` responses, `Last-Event-ID` resumption, and a load balancer enforcing session affinity keyed on the `Mcp-Session-Id` header. Does not apply to stdio transports, to stateless JSON-RPC-over-HTTP without SSE, or to deployments where session state is externally materialized (e.g., Redis-backed event logs shared across replicas). ## Core Distinction The failure is not "the SSE connection dropped." Disconnects are routine and the protocol explicitly anticipates them: the client reconnects with `Last-Event-ID`, the server replays from its per-session event log, and the stream continues. The failure is a **resumption that succeeds at the transport layer while silently violating session continuity at the semantic layer** — the reconnect lands on a *different* backend replica that either (a) has no event log for that session and fabricates a fresh one, or (b) has a divergent event log because the session was forked by a prior affinity miss. In both cases the client receives a `200 OK` with a well-formed `text/event-stream`, and the MCP client library reports the transport as healthy. The corruption is invisible until a tool result references an event ID that the new replica never issued, or a `notifications/tools/list_changed` notification is replayed twice with different payloads. The invariant that breaks: **event IDs are only meaningful within the session-replica pair that minted them.** The MCP spec treats `Last-Event-ID` as opaque, and the transport layer treats `Mcp-Session-Id` as opaque, but neither layer binds them together. Affinity routing binds the *session* to a replica at connection time; resumption assumes that binding still holds. When the router rebalances between the drop and the reconnect, the two opacities compose into a continuity gap. ## What Was Observed A long-running agent task (a multi-step code-migration workflow) held an MCP session against a 4-replica deployment behind an L7 router with cookie-and-header affinity. The stream had been idle for 90 seconds (server sent keepalive comments every 15s, so no idle timeout on the client side). At T+91s the router's health check marked replica-2 as degraded due to a GC pause exceeding the probe threshold, and the router drained it — including its active SSE connection. The client's transport received a clean `close`, and the MCP client library initiated resumption per spec: ``` GET /mcp Mcp-Session-Id: 8f3a...c21 Last-Event-ID: 4471 Accept: text/event-stream ``` The router's affinity table had already evicted the `8f3a...c21 → replica-2` mapping during the drain. The request hashed to replica-3. Replica-3 had never seen session `8f3a...c21`; its session store was process-local. Rather than returning `404` (which the spec permits for unknown sessions and which the client would surface as a hard failure), the server's session middleware **lazily initialized** a new session record for the unknown ID — a defensive pattern intended to tolerate server restarts — and began a fresh event log at ID `1`. The client, having sent `Last-Event-ID: 4471`, received events starting at `1`. Because the MCP client library's resumption logic only checks *that* events arrive, not that the first received ID is `> Last-Event-ID`, it accepted the replay. The agent's in-flight `tools/call` for `read_file` (event 4471) had been issued against replica-2's state; replica-3 had no record of it, so the response never arrived. The agent's tool-call timeout fired at 30s, it retried `read_file`, and replica-3 executed it against a *fresh* session whose tool registry had not yet been populated by the earlier `notifications/tools/list_changed`. The retry hit a `MethodNotFound` for a tool that existed — because the list-changed notification had been minted on replica-2 and replayed nowhere. Net effect: three tool calls executed twice (side-effecting `write_file` among them), one tool call failed spuriously, and the agent's local task state diverged from server state by one file write. No error was surfaced to the orchestrator; the transport reported `connected` throughout. ## Condition of Validity This failure requires the conjunction of four conditions. Remove any one and the mode does not occur: 1. **Process-local session and event-log state.** If event logs are externalized (shared store keyed by session ID), replica-3 can serve the replay correctly regardless of affinity. The failure is specific to in-memory session stores. 2. **Lazy session initialization on unknown IDs.** If the server returns `404` for an unknown `Mcp-Session-Id` (the spec-sanctioned behavior), the client surfaces a hard failure and the orchestrator can restart the task with a clean session. The lazy-init pattern converts a detectable failure into an undetectable one. 3. **Affinity eviction during connection lifetime.** Affinity tables with TTLs shorter than the maximum SSE stream lifetime, or affinity entries dropped on health-check transitions, create the window. A router that pins affinity for the full stream duration (or that drains by *closing* streams only after affinity is re-established) does not. 4. **Client resumption that does not validate monotonicity.** A client that rejects any replayed event with `id <= Last-Event-ID` catches the case where replica-3 starts at `1`. A client that additionally validates that the first replayed event's ID is exactly `Last-Event-ID + 1` (or that a gap is explicitly signaled) catches the forked-log case. The condition is *not* satisfied by: stateless MCP servers (no session state to lose), servers that reject unknown sessions, or clients that treat any resumption gap as a fatal session error. ## Decision Boundary The architectural decision is where to place the continuity check. Three viable boundaries, in increasing cost: - **Router-side:** Bind affinity to the session ID for the lifetime of the SSE stream, and on drain, hold the affinity entry until the stream closes and a configurable grace window (≥ client reconnect backoff) elapses. This prevents the rebalance-during-resume window entirely. Cost: drain latency; a degraded replica keeps its sessions until they reconnect elsewhere or the grace expires. - **Server-side:** Reject unknown `Mcp-Session-Id` with `404` and a `Mcp-Session-Expired` error code rather than lazy-initializing. This makes the failure detectable at the cost of forcing client-side task restart on any affinity miss. Cost: task restart on every rebalance; unacceptable for long-running agent tasks without externalized state. - **Client-side:** On resumption, require that the first event ID received is strictly greater than `Last-Event-ID`, and treat any regression or fork (same ID, different payload hash) as a fatal session discontinuity requiring task restart. This is the cheapest boundary and the only one that catches forked logs, but it requires the client library to expose event-ID monotonicity to the agent layer — which most do not. The recommended boundary is **server-side rejection plus client-side monotonicity check**, with router-side affinity pinning as defense in depth. The lazy-init pattern must be removed: it is the single decision that converts a recoverable transport event into silent state corruption. ## Operational Effect When the boundary is correctly placed, an affinity miss during resumption produces a `404 Mcp-Session-Expired`, the MCP client surfaces a `SessionDiscontinuity` error to the agent, and the agent's checkpoint/resume logic (which should already exist for cold-start amnesia) restarts the task from its last durable checkpoint rather than from a corrupted in-memory continuation. The cost is a task restart; the benefit is that the restart is *observable* and *idempotent* rather than a silent double-write. When the boundary is misplaced (lazy init, no monotonicity check), the failure is silent, non-deterministic, and correlated with replica health events — meaning it clusters during exactly the periods when the system is already under stress, and its symptoms (duplicate side effects, spurious `MethodNotFound`, divergent tool registries) are attributed to the agent's reasoning rather than to the transport. The diagnostic signature to watch for: a `tools/call` that succeeds on retry but whose `notifications/tools/list_changed` predecessor was never observed on the current session — that is the fingerprint of a forked event log. ```python import hashlib from dataclasses import dataclass class SessionDiscontinuity(RuntimeError): """Raised when an MCP SSE resumption violates session continuity.""" pass @dataclass(frozen=True) class ReplayEvent: event_id: int payload: bytes def payload_hash(self) -> str: return hashlib.sha256(self.payload).hexdigest() def validate_resumption( last_event_id: int, replayed: list[ReplayEvent], prior_hashes: dict[int, str], ) -> None: """ Enforce the continuity invariant on an SSE resumption. prior_hashes maps event_id -> payload_hash for events already observed on the pre-disconnect stream. Any replayed event whose ID is <= last_event_id with a *different* payload hash indicates a forked event log (affinity rebalanced to a divergent replica). Any replayed event whose ID is strictly less than the first expected ID indicates a restarted log (lazy-init replica). """ if not replayed: raise SessionDiscontinuity( f"empty replay after Last-Event-ID={last_event_id}; " "server likely initialized a fresh log" ) first = replayed[0].event_id if first <= last_event_id and first != last_event_id + 1: # Server restarted its log at 1, or jumped backward. raise SessionDiscontinuity( f"replay began at id={first} after Last-Event-ID={last_event_id}; " "monotonicity violated — session forked or log restarted" ) for ev in replayed: prior = prior_hashes.get(ev.event_id) if prior is not None and prior != ev.payload_hash(): raise SessionDiscontinuity( f"event id={ev.event_id} replayed with divergent payload " f"(prior={prior[:12]} now={ev.payload_hash()[:12]}); " "affinity miss to a replica with a forked event log" ) def resume_session( session_id: str, last_event_id: int, fetch_replay, prior_hashes: dict[int, str], ) -> list[ReplayEvent]: replayed = fetch_replay(session_id, last_event_id) if replayed is None: raise SessionDiscontinuity( f"server returned 404 for session {session_id[:8]}...; " "task must restart from last durable checkpoint" ) validate_resumption(last_event_id, replayed, prior_hashes) return replayed ```