# Why does an instance lose tool-call continuity when an MCP streamable-SSE session migrates between gateway replicas mid-resume? **Date of Record:** 2026 November 25 **Scope:** Applies to MCP clients and servers using the streamable HTTP transport with SSE resumption (`Last-Event-ID` replay) behind a load-balanced gateway that does not pin sessions to a replica. Does not apply to single-replica deployments, stdio transports, or stateless request/response MCP profiles that never open a resumable event stream. ## Core Distinction The distinction that matters is between **event replay** and **session replay**. Streamable SSE guarantees that a client reconnecting with `Last-Event-ID: N` receives every event numbered `N+1` onward *that the server still holds*. It does **not** guarantee that the server holding those events is the same server that holds the in-flight tool-call state those events describe. In a load-balanced gateway with no session affinity, the resumption request lands on a *different replica* whose event buffer may be empty past `N`, whose `Last-Event-ID` counter is a separate namespace, and whose session table has never seen this `Mcp-Session-Id`. The failure is not a dropped connection. It is a **successful resumption that silently returns a coherent-looking but causally disjoint event stream**, because the new replica either (a) has no events and returns `200` with an empty stream, or (b) has its own event IDs that happen to overlap numerically, so the client resumes at the wrong logical point. The agent then continues reasoning on a stream that no longer corresponds to the tool call it believes is pending. ## What Was Observed A three-replica gateway sat in front of an MCP server pool. Session IDs were issued by whichever replica first handled `initialize`, but the gateway used round-robin with no cookie or header affinity. The client held `Mcp-Session-Id: S1` and `Last-Event-ID: 42`. Trace of the failure: 1. Client calls `tools/call` for a long-running tool. Replica A accepts it, assigns the call an internal `request_id`, and begins streaming `notifications/progress` events numbered 40, 41, 42, 43... 2. The TCP connection drops at event 42. The client has received 40–42 and holds `Last-Event-ID: 42`. 3. Client reconnects with `GET /mcp` plus `Mcp-Session-Id: S1` and `Last-Event-ID: 42`. The gateway routes to **replica B**. 4. Replica B has no session `S1` in its session table. Per the spec's resumability rules, an unknown session should yield `404`, and the client should re-`initialize`. But replica B's implementation treated an unknown session as a *fresh* session and returned `200` with an empty SSE stream, holding the connection open. 5. The client's resumption logic saw `200`, concluded the stream was alive, and blocked waiting for event 43. Event 43 was being emitted by replica A into a buffer nobody was reading. The tool call on replica A eventually completed and its result event was written to A's buffer, then GC'd after the TTL. 6. The agent's execution loop timed out at the tool-call deadline with no result and no error. The tool *had* run — side effects committed on replica A — but the agent recorded the call as failed and, in a retry path, invoked it a second time. Duplicate side effect. The insidious part: steps 4–5 produced no error status. The client could not distinguish "replica B has no more events yet but will" from "replica B will never have events for this call." Both look like an open `200` stream. ## Condition of Validity The invariant that must hold for streamable-SSE resumption to be safe under a load balancer is: > **For any `Mcp-Session-Id`, the tuple (event-ID namespace, in-flight tool-call state, session table entry) must be co-located on the replica that answers the resumption request — or the resumption must be rejected with a status that forces re-initialization.** This holds only when one of: - **Session affinity** routes all requests for `S1` to replica A for the session's lifetime (sticky routing keyed on `Mcp-Session-Id`), *and* the affinity survives replica A's death by failing closed (evicting the session) rather than silently rerouting. - **Shared session/event store**: event buffers and session state are externalized (Redis, DB) so any replica can serve `Last-Event-ID: 42` from the same logical buffer, and event IDs are globally monotonic per session, not per replica. - **Fail-closed resumption**: a replica that does not own the session returns `404 Not Found` (or `410 Gone` for expired buffers), never `200` with an empty stream. The boundary is crossed the moment a replica answers a resumption for a session it does not own with a `2xx`. That is the validity-breaking condition. ## Decision Boundary The decision the server must make on every resumption request is binary and must be made *before* writing any response bytes: - **Own the session and hold events > `Last-Event-ID`** → replay them, continue streaming. Safe. - **Own the session but the buffer was GC'd past `Last-Event-ID`** → `410 Gone` (resumption impossible; client must re-`initialize` and reconcile). Never silently resume at a later point, because the client's reasoning state assumed event 43 would follow 42. - **Do not own the session** → `404 Not Found`. The client MUST treat this as "session is gone," re-run `initialize`, and — critically — **reconcile any in-flight tool calls by querying their status by a client-supplied idempotency key**, not by blindly retrying. The anti-pattern that breaks the boundary is treating "unknown session" as "new session" and returning `200`. This is a common implementation shortcut because it makes single-replica tests pass and makes the happy path look robust. Under a load balancer it converts a routing miss into a silent continuity break. A second boundary: event-ID namespacing. If each replica numbers events from its own counter (A emits 40, 41, 42; B's counter is also near 42 for a *different* session), a client that resumes on B with `Last-Event-ID: 42` may receive B's event 43 — a completely unrelated notification. Event IDs must be scoped to the session (e.g., `sessionId:seq` or a globally unique monotonic token), never a bare per-replica integer. ## Operational Effect When the boundary is crossed, the observable effect is **phantom tool-call loss with duplicate side effects**: the agent believes the call failed (timeout, no result event), the tool actually ran on the orphaned replica, and any retry double-executes. This is worse than a clean connection failure because: - No error is surfaced; the agent's retry logic is triggered by timeout, not by a `4xx`, so it cannot distinguish "tool never ran" from "tool ran and result was lost." - The orphaned replica's buffer holds the real result until TTL expiry, invisible to the client. - Progress notifications the agent *did* receive (40–42) are consistent, so the agent's partial state looks valid, deepening the divergence. The guardrail is a two-part invariant enforced at the transport layer: 1. **Fail-closed resumption**: any replica not owning the session returns `404`; any owner missing the requested event returns `410`. No `200`-with-empty-stream ever. 2. **Idempotency-keyed tool calls**: every `tools/call` carries a client-generated idempotency key; the server deduplicates on it across replicas via the shared store, so a retry after a broken resumption returns the original result instead of re-executing. Without both, session migration under a load balancer is a silent continuity break. The agent layer cannot detect it because the transport layer lied with a `200`. ```python import hashlib from dataclasses import dataclass, field class ResumptionContinuityError(RuntimeError): """Raised when a resumption request would silently break tool-call continuity.""" pass @dataclass class EventBuffer: session_id: str events: dict = field(default_factory=dict) # seq -> payload max_seq: int = 0 gc_floor: int = 0 # lowest seq still retained @dataclass class Replica: replica_id: str sessions: dict = field(default_factory=dict) # session_id -> EventBuffer def owns(self, session_id: str) -> bool: return session_id in self.sessions def emit(self, session_id: str, payload: str) -> int: buf = self.sessions.setdefault(session_id, EventBuffer(session_id)) buf.max_seq += 1 buf.events[buf.max_seq] = payload return buf.max_seq def handle_resumption(replica: Replica, session_id: str, last_event_id: int) -> list: """ Decide how to answer a streamable-SSE resumption request. Returns the list of events to replay. Raises on continuity break. """ if not replica.owns(session_id): # Boundary violation: do NOT return 200 with an empty stream. raise ResumptionContinuityError( f"replica {replica.replica_id} does not own session {session_id!r}; " f"must respond 404 and force re-initialize, not 200" ) buf = replica.sessions[session_id] if last_event_id < buf.gc_floor: # Requested event already garbage-collected; resumption is impossible. raise ResumptionContinuityError( f"session {session_id!r} requested Last-Event-ID {last_event_id} " f"but buffer floor is {buf.gc_floor}; must respond 410, not resume at a later point" ) if last_event_id > buf.max_seq: # Client claims to have seen events the server never emitted. raise ResumptionContinuityError( f"session {session_id!r} Last-Event-ID {last_event_id} exceeds " f"max_seq {buf.max_seq}; event-ID namespace mismatch across replicas" ) return [buf.events[seq] for seq in range(last_event_id + 1, buf.max_seq + 1)] def idempotency_key(session_id: str, tool_name: str, args_repr: str) -> str: return hashlib.sha256(f"{session_id}|{tool_name}|{args_repr}".encode()).hexdigest() # --- Demonstration of the failure trace --- replica_a = Replica("A") replica_b = Replica("B") sid = "S1" for p in ("progress:40", "progress:41", "progress:42"): replica_a.emit(sid, p) # Client reconnects with Last-Event-ID: 42, gateway routes to B (round-robin). try: handle_resumption(replica_b, sid, last_event_id=42) except ResumptionContinuityError as e: print("caught (correctly):", e) # Correct routing: B must fail closed; A replays 43.. only. print("A replay:", handle_resumption(replica_a, sid, last_event_id=42)) ```