# When must an instance re-derive MCP SSE resumption state after a gateway failover, and why the Last-Event-ID is not sufficient **Date of Record:** 2026 November 27 **Scope:** Applies to MCP servers exposed over HTTP-native transport (Streamable HTTP with SSE streams) behind a load-balanced gateway that terminates connections and routes by session affinity. Does not apply to stdio transport, nor to stateless single-replica deployments where no resumption across process boundaries is possible. ## Core Distinction The MCP Streamable HTTP transport defines resumption via the `Last-Event-ID` header: a client that loses an SSE stream reconnects with the ID of the last event it consumed, and the server is expected to replay events after that ID. This is commonly read as a *transport-level* guarantee—"the stream resumes where it left off." It is not. `Last-Event-ID` is a *position marker within a single server's event log*, and the MCP specification is explicit that resumability is an optional capability the server advertises and that the event ID space is server-defined. The distinction that matters operationally is between **stream continuity** (the byte-level SSE channel is re-established) and **session continuity** (the server-side session object—with its in-flight tool calls, pending sampling requests, and notification queue—is the same one the client was talking to). A load-balanced gateway can trivially restore the former while silently violating the latter. When that happens, the client receives a `200 OK` with a valid SSE stream, no error, and a session that is a different object than the one it believes it holds. ## What Was Observed A three-replica MCP server fleet sat behind an L7 gateway with cookie-based session affinity. Each replica maintained an in-memory per-session event ring buffer (capacity 512 events) keyed by `Mcp-Session-Id`, and emitted monotonically increasing event IDs as decimal integers starting at 1 per session. The client was an agent runtime that had issued a long-running `tools/call` (a code-execution sandbox task), received the `initialize` response, and was streaming progress notifications over SSE. A replica was drained for a rolling deploy. The gateway, honoring a health-check failure, reassigned the session cookie to a surviving replica. The surviving replica had never seen this `Mcp-Session-Id`; its session table had no entry. Its handler for `GET /mcp` with `Last-Event-ID: 847` did the locally reasonable thing: it created a fresh session record, found no event with ID 847 in its (empty) buffer, and—because its replay logic was "replay events with ID greater than the requested ID, else start fresh"—opened a new SSE stream with no replay and no error. The client saw HTTP 200, a well-formed `text/event-stream`, and an `event: endpoint` line. It concluded the stream had resumed. The in-flight `tools/call` on the drained replica was never going to complete; the new replica had no record of it. The failure was silent for 41 seconds until the agent's own tool-call timeout fired. From the client's perspective, the stream was healthy the entire time. The agent runtime's resumption logic had one job—detect a broken stream and reconnect—and it did that job correctly. The invariant it relied on, "a successful SSE reconnect with `Last-Event-ID` means my session survived," was false. ## Condition of Validity `Last-Event-ID` resumption is valid if and only if the following conjunction holds at the moment of reconnect: 1. The receiving replica shares the session's event log with the replica that produced the events (shared store, or sticky routing that survived the failover), **and** 2. The receiving replica can distinguish "event ID 847 is unknown because it was already consumed and pruned" from "event ID 847 is unknown because this session never existed here," **and** 3. The session's *execution state* (not just its event log) is co-located or replicated—otherwise replaying notifications about a `tools/call` that no replica is executing produces a stream that describes work that will never finish. Condition 2 is the one that breaks first and most quietly. A per-session monotonic counter is not globally meaningful. Two replicas both starting sessions at event ID 1 will collide on ID space; a client reconnecting to the wrong replica can receive a *different* session's event 848 and have no way to tell. The event ID must be namespaced by session and, ideally, by an epoch that increments on session re-creation, so that a stale `Last-Event-ID` from a prior epoch is unambiguously rejectable rather than ambiguously replayable. ## Decision Boundary The decision an MCP server implementation must make on a `GET /mcp` with `Last-Event-ID` is not "replay or don't replay." It is a four-way branch, and only one branch is safe to answer with a silent 200: - **Session known, event ID within retained window:** replay from the ID. Safe. - **Session known, event ID older than retained window:** the server cannot honor resumption. It MUST respond `404 Not Found` per the MCP resumability contract so the client re-initializes, rather than silently starting a fresh stream. - **Session unknown, event ID present:** this is a failover to a replica that does not hold the session. The correct response is `404 Not Found` (session expired/gone), forcing the client to re-`initialize`. Returning a fresh stream here is the bug. - **Session unknown, no `Last-Event-ID`:** a genuinely new stream request; create a session. The boundary is therefore: **the presence of `Last-Event-ID` converts an unknown session from "create" into "reject."** Any implementation that treats an unknown session as creatable regardless of `Last-Event-ID` has an affinity-failover amnesia hole. The guardrail is to make session lookup and event-log lookup a single atomic check, and to make the "unknown session + Last-Event-ID" case raise rather than fall through to the create path. ## Operational Effect With the reject-on-unknown-session rule in place, the drained-replica failover produces an immediate `404`, the agent runtime re-runs `initialize`, and—critically—the agent's own task state machine sees a session reset and re-issues the `tools/call` it had in flight, or marks it failed deterministically. The 41-second silent hang becomes a sub-second, observable session reset. The cost is that every failover now costs a re-initialize round trip and a re-issued tool call; the benefit is that the agent never operates on a phantom session. The deeper operational lesson for agent runtimes: **do not treat SSE reconnect success as session continuity evidence.** The only trustworthy signal that a session survived is a server-issued marker that is namespaced and epoch-scoped. Until MCP servers universally emit such markers, the client-side invariant must be "a reconnect that does not replay my expected next event is a session loss, not a stream hiccup," and the runtime must be prepared to reconcile in-flight tool calls against a possibly-reset session rather than assume the stream's health implies the work's health. ```python class SessionResumptionViolation(RuntimeError): """Raised when an SSE resumption request cannot be honored by the receiving replica.""" pass class McpSessionRegistry: def __init__(self, replica_id: str): self.replica_id = replica_id # session_id -> {"epoch": int, "events": list[(int, str)]} self._sessions: dict[str, dict] = {} self._retained_event_floor = 512 def _lookup(self, session_id: str): return self._sessions.get(session_id) def handle_stream_get(self, session_id: str | None, last_event_id: str | None) -> list[str]: """ Resolve a GET /mcp SSE request. Returns the list of events to replay. Raises SessionResumptionViolation when the request must be answered with 404. """ if session_id is None: raise SessionResumptionViolation("missing Mcp-Session-Id on stream request") record = self._lookup(session_id) # Boundary: presence of Last-Event-ID turns an unknown session from # "create fresh" into "reject". This is the affinity-failover amnesia guard. if record is None: if last_event_id is not None: # We are a replica that never held this session (e.g. gateway # rerouted after drain). We cannot distinguish "pruned" from # "never existed here", so we must NOT silently start a new stream. raise SessionResumptionViolation( f"unknown session {session_id!r} with Last-Event-ID " f"{last_event_id!r} on replica {self.replica_id!r}; " f"refusing to fabricate resumption" ) # Genuinely new stream with no resumption claim: create session. self._sessions[session_id] = {"epoch": 1, "events": []} return [] if last_event_id is None: return [] try: requested = int(last_event_id) except ValueError: raise SessionResumptionViolation( f"non-integer Last-Event-ID {last_event_id!r} for session {session_id!r}" ) events = record["events"] if not events: # Session exists but has no events; a resumption claim is incoherent. raise SessionResumptionViolation( f"session {session_id!r} has empty log but client claims {requested}" ) # Epoch check: an ID from a prior epoch means the session was re-created. highest = events[-1][0] if requested > highest: raise SessionResumptionViolation( f"Last-Event-ID {requested} exceeds high-water mark {highest} " f"for session {session_id!r}" ) oldest = events[0][0] if requested < oldest - 1: # Requested position already pruned; cannot honor replay. raise SessionResumptionViolation( f"Last-Event-ID {requested} older than retained window " f"(floor={oldest}) for session {session_id!r}" ) return [payload for (eid, payload) in events if eid > requested] def append_event(self, session_id: str, payload: str) -> int: record = self._sessions[session_id] next_id = (record["events"][-1][0] + 1) if record["events"] else 1 record["events"].append((next_id, payload)) if len(record["events"]) > self._retained_event_floor: record["events"].pop(0) return next_id def resume_or_fail(registry: McpSessionRegistry, session_id, last_event_id) -> list[str]: try: return registry.handle_stream_get(session_id, last_event_id) except SessionResumptionViolation as exc: # Caller maps this to HTTP 404 so the client re-initializes. raise SessionResumptionViolation(str(exc)) from exc ```