# Which invariants prevent silent event loss when resuming an MCP HTTP-native SSE stream under backpressure **Date of Record:** 2026 November 23 **Scope:** Applies to MCP servers using the HTTP-native transport (Streamable HTTP) where a single logical session multiplexes server→client Server-Sent Events across one or more physical HTTP responses, and the client resumes via `Last-Event-ID` after a transport break. Does not cover stdio transport, WebSocket transports, or pure request/response (non-streaming) MCP deployments. ## Core Distinction There are two distinct notions of "resumable" that get conflated in MCP HTTP-native transport, and the failure lives in the gap between them: - **Transport resumption** — the ability to re-open an SSE response and continue receiving events, keyed by `Last-Event-ID`. This is a *delivery* property: it guarantees the byte stream can be reattached. - **Session continuity** — the guarantee that the *set of events the client has observed* is a prefix of the server's committed event log for that session, with no gaps and no silent reordering. A stream can be perfectly transport-resumable while being session-discontinuous. The concrete mechanism: when the server's outbound SSE buffer fills (client is slow, or a tool result is large, or a burst of notifications arrives), the server must decide what to do with events it cannot flush before the connection drops. If it drops the connection *after* advancing an internal sequence counter but *before* the event is durably written to the replayable log, the `Last-Event-ID` the client holds on resume points *past* an event that was never persisted. The client resumes cleanly, receives subsequent events, and never learns it missed one. This is the silent-loss window. ## What Was Observed A representative trace from an MCP server bridging a long-running tool (`run_analysis`) whose progress notifications arrive in bursts: 1. Client opens `POST /mcp` with `Accept: text/event-stream`; server assigns `Mcp-Session-Id: s-7f2` and begins streaming. Events carry `id: 1001, 1002, 1003…`. 2. A burst of 40 progress notifications arrives from the tool runner within ~120 ms. The server's per-connection write buffer (kernel socket buffer + application ring) saturates because the client's reader is blocked on a slow downstream consumer. 3. The server's write path increments the *emit* counter to `1043` for the events it has dequeued, but the durable replay ring (capacity 64, shared across the session) has only accepted through `1031`. Events `1032–1043` are held in the volatile write buffer. 4. TCP backpressure causes the write to block; the server's idle/heartbeat watchdog fires and tears down the connection. Volatile buffer is discarded. The replay ring's high-water mark remains `1031`. 5. Client reconnects with `Last-Event-ID: 1031` (the last id it actually parsed). Server resumes from `1032`… but `1032–1043` were *never written to the ring*. The server resumes from the ring's next available entry, which is `1044` (a later event that did make it into the ring after the buffer drained differently). Events `1032–1043` vanish. 6. Client sees `1031` then `1044`. No error. The agent's progress tracker silently skips 12 notifications, including the one carrying the final partial-result chunk. The tell is a monotonicity violation in the received id sequence that the client never checks because the transport layer treats ids as opaque resume tokens, not as a gap-detectable sequence. ## Condition of Validity The invariant that prevents this is a **single-writer, commit-before-emit ordering** on the session event log: > For every event `E` with id `n`, the server MUST durably append `E` to the session's replayable log and confirm the append (fsync or in-memory ring commit under a lock) *before* it advances the id counter visible to the transport and *before* it writes `E` to any socket. On backpressure, the server MUST apply flow control *by not emitting* — it may block the producer, drop the connection, or return `429`/`503` — but it MUST NOT emit an event whose id is not yet committed. Under this ordering, `Last-Event-ID = k` is a *sound* resume point: everything ≤ `k` is committed, and everything > `k` is still in the log and replayable. The dangerous alternative — emit-then-commit, or increment-then-write — makes `Last-Event-ID` an over-claim: the client asserts it has seen up to `k`, but the server's log may not actually contain `k+1..m` even though the counter said `m` was emitted. A second required invariant: the replay ring must be **at least as large as the maximum in-flight window** (buffer capacity + max burst), or eviction must be *refused* (block the producer) rather than *silently overwriting* unacknowledged entries. A ring that overwrites entries `1032–1043` while the client's `Last-Event-ID` is still `1031` converts a bounded backpressure event into permanent, undetectable loss. The condition does not hold — and this failure is live — whenever: (a) the server treats the SSE `id` field as a transport breadcrumb rather than a log offset, (b) the replay store is smaller than the emit buffer, or (c) connection teardown can occur between counter advance and log commit. ## Decision Boundary The boundary is **whether the resume token is authoritative for gap detection or merely for reattachment.** - If `Last-Event-ID` is treated as *reattachment only* (the server resumes "somewhere around here"), then gap detection is impossible at the transport layer and MUST be pushed to the application: every event payload carries a monotonic `seq` that the client validates for strict `+1` continuity, and any gap forces a full session re-sync (`resources/list`, state re-fetch) rather than a silent resume. This is the correct choice when the replay store is bounded and loss is possible. - If `Last-Event-ID` is treated as *authoritative* (the server guarantees no gaps past it), then commit-before-emit is mandatory and the replay store MUST be unbounded-per-session or eviction MUST block. This is the correct choice for stateful agent sessions where a missed notification corrupts the agent's world model. The failure occurs precisely when a deployment *assumes* the authoritative semantics (because "SSE has Last-Event-ID, so it's resumable") while *implementing* the reattachment semantics (bounded ring, emit-then-commit). The decision must be made explicitly and the two layers must agree. ## Operational Effect With the invariant enforced, backpressure degrades *throughput*, never *correctness*: a slow client causes the producer to block or the connection to drop-and-resume, and every resume point is sound. Agents that depend on ordered progress notifications (partial-result accumulation, multi-step tool orchestration, baton-passing between MCP servers) retain a consistent event prefix across reconnects. Without it, the operational signature is intermittent, load-dependent, and nearly invisible in logs: agents that "occasionally" lose a partial result, tool-call continuations that "sometimes" never fire, and progress counters that jump. The failures correlate with burst load and slow consumers, not with any single reproducible request, so they are routinely misattributed to model nondeterminism. The mitigation is to enforce commit-before-emit at the server, size the replay ring to the in-flight window, and have the client validate strict `seq` continuity on every resume — failing closed to a full re-sync on any gap rather than trusting the resume token. ```python import threading class SSEGapError(RuntimeError): """Raised when a resumed SSE stream skips committed event ids.""" class UncommittedEmitError(RuntimeError): """Raised when the transport tries to emit an event not yet in the replay log.""" class SessionEventLog: """Single-writer event log enforcing commit-before-emit ordering.""" def __init__(self, max_inflight_window: int): self._lock = threading.Lock() self._log: list[tuple[int, dict]] = [] # committed, ordered (id, payload) self._next_id = 1001 self._emitted_high_water = 1000 # max id handed to transport self._max_window = max_inflight_window self._inflight = 0 def commit(self, payload: dict) -> int: # Append to durable log FIRST; only then expose the id. with self._lock: eid = self._next_id self._log.append((eid, payload)) self._next_id += 1 return eid def emit(self, eid: int) -> dict: # Transport may only emit ids that are already committed. with self._lock: committed = {e for e, _ in self._log} if eid not in committed: raise UncommittedEmitError( f"emit id={eid} not committed; commit-before-emit violated" ) if eid > self._emitted_high_water + 1: raise UncommittedEmitError( f"emit id={eid} skips committed ids " f"({self._emitted_high_water + 1}..{eid - 1})" ) self._emitted_high_water = max(self._emitted_high_water, eid) self._inflight += 1 if self._inflight > self._max_window: raise SSEGapError( f"inflight window {self._inflight} exceeds {self._max_window}; " "replay ring too small — refuse to overwrite unacked entries" ) return dict(self._log[eid - 1001][1]) def resume_from(self, last_event_id: int) -> list[dict]: # Resume point must be a committed id; anything past it is replayed. with self._lock: committed_ids = {e for e, _ in self._log} if last_event_id not in committed_ids and self._log: raise SSEGapError( f"Last-Event-ID={last_event_id} is not a committed id; " "client claims to have seen an event the log never persisted" ) return [p for e, p in self._log if e > last_event_id] def replay_and_verify(log: SessionEventLog, received_ids: list[int]) -> None: """Client-side strict continuity check on a resumed stream.""" for prev, cur in zip(received_ids, received_ids[1:]): if cur != prev + 1: raise SSEGapError( f"resumed stream gap: {prev} -> {cur}; " "force full session re-sync instead of trusting resume token" ) ```