# Why does an instance lose its MCP session when SSE resumption crosses a load-balanced boundary? **Date of Record:** 2026 December 1 **Scope:** Applies to MCP servers exposed over HTTP-native transport with `streamable` SSE and `Last-Event-ID` resumption, fronted by any stateless L7 load balancer or multi-replica deployment. Does not apply to single-process stdio transports, or to SSE deployments that pin a session to a single connection with no resumption contract. ## Core Distinction The MCP streamable HTTP transport treats a *session* and a *stream* as two different lifetimes. The session is identified by the `Mcp-Session-Id` header and is expected to survive across many HTTP requests. The SSE stream is identified by an event ID sequence and is expected to survive a *single* request's disconnection, resumable via `Last-Event-ID`. The failure mode lives at the seam: resumption is defined at the *stream* layer, but the server reconstructs the stream's continuation from *session* state. When a load balancer routes the resuming request to a replica that does not hold that session's event buffer, the server cannot distinguish "this event ID was never emitted" from "this event ID was emitted by a different replica." Both look like an unknown cursor. The transport spec does not require the server to fail loudly in that case, and many implementations silently start a fresh stream from the current head, dropping every event between the client's `Last-Event-ID` and the replica's present. The client sees a valid 200, a valid `text/event-stream`, and a gap it cannot detect. This is not a load-balancing bug. It is a *replay-identity* bug: the event ID namespace is per-replica but is consumed by the client as if it were per-session. ## What Was Observed A tool-calling agent was driving a long-running MCP server operation (a multi-page document index build) over streamable HTTP. The server emitted progress events and a final `tools/call` result as SSE events on a single POST-initiated stream. Between events 441 and 442 the client's TCP connection was reset (idle timeout at an intermediate NAT). The client reconnected with `Last-Event-ID: 441` and the same `Mcp-Session-Id`. The load balancer, configured with least-connections rather than session affinity, routed the reconnect to replica B. Replica B had the session in its shared session store (so the `Mcp-Session-Id` validated) but had never emitted event 441 — its local event ring buffer only contained events from its own streams. Replica B's resumption handler did this: ```python last = request.headers.get("Last-Event-ID") # local buffer lookup if last is not None and last in self._event_buffer: yield from self._event_buffer.resume_after(last) else: # unknown cursor: treat as fresh subscription yield from self._event_buffer.from_head() ``` Because `"441"` was not in replica B's buffer, the `else` branch fired. The client received a fresh stream beginning at replica B's head — which was event 1 of a *different* concurrent stream, then nothing, because replica B had no active task for this session. The client's stream reader blocked until its own read deadline fired, then the agent concluded the tool call had stalled and issued a *retry* of `tools/call`. The original operation on replica A was still running. The server executed the index build twice, and the agent's downstream state recorded two divergent results for one logical call. The tell was in the logs: replica A emitted `event: 442, data: {"progress": 0.71}`; replica B emitted `event: 1, data: {"progress": 0.02}` on the same session ID. The client never compared them because both were syntactically valid resumption responses. ## Condition of Validity The silent-gap behavior is *valid* (i.e., the server is not violating the transport contract) under all of the following: 1. The server treats `Last-Event-ID` as an *optional hint* rather than a hard cursor, and the spec text permits falling back to a fresh stream when the cursor is unknown. 2. The event ID namespace is scoped to the replica's stream buffer, not to the session. 3. The client does not independently track expected sequence continuity (it trusts the server's cursor). Remove any one of these and the failure either cannot occur or becomes loud. In particular, if the server scopes event IDs to the session (e.g., a monotonic counter persisted with the session record, not with the stream), then replica B *can* detect that `441` is a legitimate prior cursor even though it lacks the payload — and must then either fetch the payload from shared state or return a resumption error rather than a fresh head. The invariant is: **the resumption cursor must be validated against session-scoped state, not stream-local state, before any fallback is permitted.** ## Decision Boundary The architectural choice is where to put the reconnection contract: - **Stream-local cursor (observed, broken):** cheap, no shared state, but a cursor is only meaningful on the replica that minted it. Any non-affine routing silently loses events. - **Session-scoped cursor with shared event log:** the session record carries `last_emitted_id` and a durable or replicated event log keyed by `(session_id, event_id)`. Resumption on any replica validates the cursor against `last_emitted_id`; if `cursor < last_emitted_id` but the payload is absent, the server returns a resumption error (not a fresh stream). This is the correct boundary for any multi-replica deployment. - **Sticky affinity (mitigation, not fix):** pin the session to one replica. This hides the bug until a replica restarts or the pin table is evicted, at which point it returns as a cold-start amnesia event rather than a routing event. Affinity is not a substitute for session-scoped cursor validation; it only reduces the trigger rate. The decision boundary is therefore: *if the deployment can route two requests of one session to two replicas, the cursor must be session-scoped.* If it cannot (single replica, or guaranteed affinity with durable pin state), stream-local cursors are acceptable — but the affinity guarantee becomes a hard dependency that must be monitored, because its failure mode is silent. ## Operational Effect The downstream effect is not "a dropped event." It is **duplicate execution under a divergent cursor.** Because the client cannot distinguish a legitimate fresh stream from a gap, its only recovery move on stream stall is to retry the originating request. The retry is a new `tools/call` on a session whose original call is still in flight on another replica. The server, seeing a valid session and no idempotency key, executes again. The agent now holds two results for one logical operation, and — because the retry's stream is on replica B while the original's is on replica A — the two results arrive on different event sequences that the agent's episodic log interleaves in arrival order, not causal order. Distillation of that episode into semantic memory records the *later-arriving* result as authoritative, which may be the stale one. The guardrail is twofold. First, the server must treat an unknown-but-plausible `Last-Event-ID` as a resumption *error* (`409` or a transport-level `resumption_failed` event), never a silent head reset. Second, the client must attach an idempotency key to every `tools/call` and the server must dedupe on it, so a retry after a resumption failure returns the original result rather than re-executing. Without both, the failure is not a gap in a stream — it is a fork in the agent's memory that no later verification pass can detect, because both branches are individually well-formed. ```python import hashlib from dataclasses import dataclass, field class ResumptionCursorError(RuntimeError): """Raised when a Last-Event-ID cannot be validated against session-scoped state.""" @dataclass class SessionRecord: session_id: str last_emitted_id: int = 0 # event_id -> payload, replicated across replicas (durable or shared cache) event_log: dict = field(default_factory=dict) # idempotency_key -> result, for dedupe of retried tools/call idempotency: dict = field(default_factory=dict) class McpReplica: def __init__(self, replica_id: str, store): self.replica_id = replica_id self.store = store # shared session store, keyed by session_id def resume_stream(self, session_id: str, last_event_id: str | None): sess = self.store.get(session_id) if sess is None: raise ResumptionCursorError( f"unknown session {session_id} on replica {self.replica_id}" ) if last_event_id is None: # fresh subscription is legitimate only when no cursor was sent return self._from_head(sess) try: cursor = int(last_event_id) except ValueError: raise ResumptionCursorError( f"non-numeric Last-Event-ID {last_event_id!r} on session {session_id}" ) # Invariant: cursor is validated against SESSION state, not stream-local state. if cursor > sess.last_emitted_id: raise ResumptionCursorError( f"cursor {cursor} ahead of session head {sess.last_emitted_id}; " f"client is desynchronized, refusing to reset to head" ) if cursor < 0: raise ResumptionCursorError(f"negative cursor {cursor}") # Replay from shared event log; if any event in (cursor, head] is missing # from this replica's view, fail loudly rather than emit a gap. missing = [eid for eid in range(cursor + 1, sess.last_emitted_id + 1) if eid not in sess.event_log] if missing: raise ResumptionCursorError( f"session {session_id} cursor {cursor} has unreplayable events " f"{missing[:5]}...; replica {self.replica_id} cannot serve a " f"gap-free resumption — client must not retry tools/call blindly" ) return [sess.event_log[eid] for eid in range(cursor + 1, sess.last_emitted_id + 1)] def _from_head(self, sess: SessionRecord): return [] # no cursor: subscribe from current head, no replay def call_tool_idempotent(replica: McpReplica, session_id: str, tool: str, args: dict, idempotency_key: str): sess = replica.store.get(session_id) if sess is None: raise ResumptionCursorError(f"no session {session_id} for tools/call") key = hashlib.sha256( f"{session_id}:{tool}:{idempotency_key}".encode() ).hexdigest() if key in sess.idempotency: # retried call after a resumption failure: return original result return sess.idempotency[key] result = {"tool": tool, "args": args, "replica": replica.replica_id} sess.idempotency[key] = result sess.last_emitted_id += 1 sess.event_log[sess.last_emitted_id] = { "event": sess.last_emitted_id, "data": result } return result ```