Which invariants prevent SSE event-ID replay from corrupting resumable MCP sessions across stateless HTTP servers

**Date of Record:** 2026 December 1 **Scope:** Applies to MCP servers exposing the HTTP-native transport (Streamable HTTP / SSE streaming) where clients may reconnect with `Last-Event-ID` and the server is horizontally scaled or otherwise stateless. Does not apply to stdio transport or to single-process servers holding session state in memory for the process lifetime.

Core Distinction

The failure is not "the SSE connection dropped." Drops are expected and survivable. The failure is that a *resume* request (`GET` with `Last-Event-ID: N`) is answered by a *different* server instance that never produced event `N+1`, so it either (a) fabricates a plausible continuation from whatever it can reconstruct, or (b) silently restarts the stream from event `0`, which the client interprets as a continuation. The distinction that matters: **event IDs are a durability contract, not a cursor hint.** A stateless server that treats `Last-Event-ID` as advisory — "resume from the latest thing I have" — violates the contract while remaining protocol-conformant on the wire. The client cannot distinguish a correct resume from a fabricated one, because both are well-formed SSE frames with monotonically increasing IDs.

What Was Observed

A tool-calling MCP server is deployed behind a round-robin load balancer across three replicas. A single `tools/call` streams progress notifications as SSE events: `event: progress`, `data: {"tool":"fetch","pct":20}`, `id: 1` … `id: 47`, terminating with `id: 48` carrying the final result. The client's connection drops at event `id: 31` (mobile network handoff). The client reconnects per spec:

GET /mcp/session/{sid}
Last-Event-ID: 31

The load balancer routes this to replica B. Replica B holds no memory of session `{sid}` beyond a Redis entry recording `{sid → active}` — a liveness flag, not a replay buffer. Replica B has two defensible-looking options, and both are wrong:

  1. **Replay from zero.** It restarts the stream at `id: 1`. The client, honoring SSE semantics, appends events `1..N` after `31`. The client's progress handler now sees `pct` go 100 → 20 → 100. More damaging: if the terminating event `id: 48` carried a tool result, the client executes the tool-call completion callback *twice*, because it saw two terminal frames. This is the **duplicate-terminal** failure: idempotency of the *tool* was assumed, but the *stream* delivered the result twice.
  1. **Synthesize a "resume."** Replica B, lacking a buffer, emits a single synthetic event: `event: progress, data: {"pct": 100, "note": "resumed"}, id: 32`. The client accepts it as the missing event `32` and then waits forever for `33`. The stream stalls with no error, because SSE has no "I don't have that event" signal. The session hangs until a client-side timeout, and the tool result — which was produced on replica A and stored only in replica A's in-memory buffer — is lost.

Both failures are silent. Neither produces a non-200 response. Neither is visible in the server's error logs, because from the server's perspective nothing errored: it answered a GET with a valid SSE stream.

The root cause is a **statelessness/durability mismatch**: the transport layer (HTTP) is stateless and the LB is free to route anywhere, but the resumability contract (`Last-Event-ID` → exact continuation) requires per-session append-only durability that a stateless replica cannot provide. The invariant that was violated is not "the server must be stateful." It is: **an event ID may only be issued if the issuing server can guarantee that any future resume to that ID, on any replica, either delivers the exact successor or fails loudly.** Issuing `id: 31` without that guarantee is the defect.

Condition of Validity

`Last-Event-ID` resumption is only sound when all of the following hold for every event ID the server emits:

When any of these is absent, the deployment is in a state where resumption *appears* to work — the happy path (reconnect to the same replica, buffer still warm) passes — but fails under the exact condition resumption exists to handle: replica change, process restart, or buffer eviction.

Decision Boundary

The architect must choose, explicitly, between two regimes and must not straddle them:

The boundary is crossed the moment a server emits an `id:` field it cannot honor on an arbitrary replica. That single act converts a request-layer idempotency problem (solved by client keys) into a stream-layer durability problem (requiring server infrastructure) — while leaving the client believing it is in the cheap regime. The decision boundary is therefore: **emit `id:` only inside the durable-resume regime; otherwise omit it and require client-side request idempotency.**

Operational Effect

In the durable-resume regime, the operational cost is a write per event and a retention policy (how long can a client be offline before `resume_unavailable`?). The retention window is the real SLA: a client offline longer than retention must be told to restart the request, and the client must be built to accept that. In the no-resume regime, the cost moves entirely to the client, which must generate and persist an idempotency key per `tools/call` and must treat every reconnect as a fresh request, deduping results by key. The observed failure above — duplicate terminal execution and silent stalls — occurs only in the straddled regime, which is the default when a team adds SSE streaming to a stateless service without deciding which regime it is in. The guardrail that prevents it is a single assertion at the point of event emission: *if I cannot prove I can serve a resume to this ID from any replica, I must not emit it.* The code below encodes that assertion as a hard failure rather than a silent fallback.

import time
from dataclasses import dataclass, field
from typing import Optional


class ResumeContractViolation(RuntimeError):
    """Raised when a server attempts to emit or honor an event ID it cannot
    durably serve on an arbitrary replica. This is a hard failure by design:
    the alternative (silent restart or synthetic resume) corrupts the client's
    stream state invisibly."""
    pass


@dataclass
class SessionEventLog:
    """Append-only, replica-readable event log for one MCP session.
    In production this is Redis Streams / Kafka keyed by session_id; here it is
    an in-memory stand-in that enforces the same invariants."""
    session_id: str
    events: list = field(default_factory=list)   # [(event_id, payload)]
    durable: bool = True                          # set False to simulate a stateless replica
    retention_floor: int = 1                      # oldest event ID still replayable

    def last_id(self) -> int:
        return self.events[-1][0] if self.events else 0

    def append(self, payload: dict) -> int:
        # Invariant: write-then-flush. The ID is only returned (and thus only
        # emitted to the client) if the write succeeded durably.
        if not self.durable:
            raise ResumeContractViolation(
                f"replica cannot durably append for session {self.session_id}; "
                f"must not emit event IDs (no-resume regime requires omitting 'id:')"
            )
        next_id = self.last_id() + 1
        self.events.append((next_id, payload))
        return next_id

    def resume_from(self, last_event_id: int) -> list:
        """Return exact successors of last_event_id, or fail loudly. Never
        restart from zero, never synthesize."""
        if last_event_id > self.last_id():
            raise ResumeContractViolation(
                f"client claims Last-Event-ID {last_event_id} but server only "
                f"has up to {self.last_id()}; refusing to fabricate continuation"
            )
        if last_event_id < self.retention_floor - 1:
            raise ResumeContractViolation(
                f"Last-Event-ID {last_event_id} is below retention floor "
                f"{self.retention_floor}; must emit resume_unavailable error event"
            )
        return [e for e in self.events if e[0] > last_event_id]


def handle_resume(log: SessionEventLog, last_event_id: Optional[int]) -> list:
    """Entry point for GET /mcp/session/{sid} with Last-Event-ID header."""
    if last_event_id is None:
        # Client did not ask to resume: fresh stream, no contract to honor.
        return []
    try:
        return log.resume_from(last_event_id)
    except ResumeContractViolation as exc:
        # Do NOT fall back to replay-from-zero or synthetic resume. Surface a
        # terminal error event the client can act on (re-issue with idempotency key).
        raise ResumeContractViolation(
            f"session {log.session_id}: resume to {last_event_id} rejected; "
            f"client must re-issue tools/call with its idempotency key. cause: {exc}"
        ) from exc


# --- trace of the observed failure, now bounded -------------------------------
replica_a = SessionEventLog(session_id="sid-42", durable=True)
for pct in (20, 40, 60, 80, 100):
    replica_a.append({"tool": "fetch", "pct": pct})
# client saw through id=3 (pct=60), then reconnected to a stateless replica:
replica_b = SessionEventLog(session_id="sid-42", durable=False)
try:
    handle_resume(replica_b, last_event_id=3)   # replica B has no log
except ResumeContractViolation as e:
    print(f"BOUNDED: {e}")   # loud failure instead of silent stall / duplicate terminal

# correct path: resume against the durable log
successors = handle_resume(replica_a, last_event_id=3)
assert [e[0] for e in successors] == [4, 5], "gap-free exact continuation"