# Which invariants prevent MCP streamable-HTTP session resumption from silently duplicating tool effects under backpressure **Date of Record:** 2026 November 21 **Scope:** Applies to MCP servers and clients using the streamable-HTTP transport (single POST endpoint, optional SSE upgrade, `Last-Event-ID` resumption, session ID via `Mcp-Session-Id`) where tool calls are non-idempotent and the server applies backpressure by delaying SSE emission. Does not apply to stdio transport, nor to servers that fully materialize every response before emitting the first event. ## Core Distinction The distinction that matters is between **transport-level resumption** and **effect-level replay**. The streamable-HTTP spec lets a client reconnect with `Last-Event-ID` to resume an interrupted SSE stream. This is a *byte-stream* guarantee: the server replays events after the given ID. It is **not** an *effect* guarantee: the server does not know, and the spec does not require it to know, whether the client already *acted on* the events it received before the disconnect. When backpressure causes the server to buffer events (because the client is slow to read, or a proxy applies flow control), a disconnect can occur with events *emitted into the socket buffer but never acknowledged by the client*. On resume, the server replays from `Last-Event-ID`, and the client — which never saw those events — may now execute a tool effect that the server's own execution already committed. The invariant that fails here is not "events are delivered once"; it is "**event ID monotonicity is not equivalent to effect idempotency across a resumption boundary**." ## What Was Observed A tool-calling agent issued `tools/call` for a `transfer_funds` operation over streamable-HTTP. The server executed the tool, committed the ledger mutation, and began emitting the JSON-RPC response as SSE events `id=41`, `id=42`. The client's TCP receive window was saturated (the agent's event loop was blocked on a synchronous model inference step). The server's `write()` succeeded into the kernel socket buffer for both events, but the client's read loop had not yet consumed them. The connection was reset (idle timeout at an intermediary LB, 30s). The client reconnected, sent `Last-Event-ID: 40` (the last ID it had *processed*, not the last ID the server had *emitted*). The server, honoring the resume contract, replayed `41` and `42`. The client processed them and — because the response payload carried a fresh `request_id` mapping it had regenerated on resume — issued a second `tools/call` for the same logical transfer. The ledger committed twice. Server logs showed one execution; client logs showed two calls; the audit trail diverged. The failure is *silent*: neither side violates its own contract. The server honored `Last-Event-ID`. The client honored "process every event you receive." The duplication emerges from the gap between the two contracts, widened by backpressure-induced buffering. ## Condition of Validity The invariant "resumption is safe" holds *only* when all of the following are true simultaneously: 1. **The client's `Last-Event-ID` reflects the last event it has durably processed and its side effects committed**, not the last event it received into memory. If the client advances the cursor before committing the effect, a crash between receive and commit causes replay-into-duplicate. 2. **The server assigns event IDs at emission into the durable outbox, not at `write()` time.** If IDs are assigned lazily at flush, a backpressure stall can cause IDs to be assigned out of order relative to execution, and replay ranges become non-contiguous with execution order. 3. **The server's execution is keyed to a client-supplied idempotency key** (e.g., `params._meta.idempotency_key`) that survives transport reconnects. Without this, the server cannot distinguish "replay of an already-executed call" from "a genuinely new call." 4. **Backpressure is expressed as a bounded, observable signal** (e.g., server refuses to emit beyond N unacked events, or returns `429` with `Retry-After` on the POST), *not* as unbounded kernel-buffer buffering. Unbounded buffering is what makes the client's "last processed" cursor lag arbitrarily far behind the server's "last emitted" cursor. When condition 3 is absent — which is the common case for MCP servers that treat `tools/call` as fire-and-forget — the system is *only* safe if the client never reconnects mid-call, i.e., if the transport is effectively non-resumable for that call. Attempting to add resumption without idempotency keys converts a transport feature into a duplication vector. ## Decision Boundary The boundary is whether **the resumption cursor and the effect-commit cursor are the same cursor**. They are, in a correct implementation, if and only if the client persists `Last-Event-ID` *after* committing the effect derived from that event, and the server assigns IDs at outbox-append (post-execution, pre-flush). If they are two different cursors — the common case when the client advances the ID on receipt and commits later — then resumption is unsafe for any non-idempotent tool, and the correct decision is to **refuse resumption** for in-flight calls: on reconnect, the client must send a `tools/call` with the same `idempotency_key` and let the server dedupe, rather than rely on `Last-Event-ID` replay to reconstruct the response. Concretely: if the server cannot prove `idempotency_key` uniqueness within the session's TTL, it must not allow `Last-Event-ID` resumption on streams that carry non-idempotent tool responses. It should instead respond to the resume with a `409 Conflict`-equivalent JSON-RPC error (`-32001 Session state unrecoverable`) forcing the client to re-issue with an idempotency key. This is the safe side of the boundary. ## Operational Effect The observable effect of getting this wrong is **double-execution under load**, and it is load-correlated: it appears precisely when backpressure is highest, because that is when the client's processed-cursor lags the server's emitted-cursor by the most events. It is invisible in unit tests (no backpressure), invisible in low-traffic staging (buffer never fills), and appears in production under burst. The mitigation is architectural: **(a)** server-side idempotency keyed on a client-generated UUID that is stable across reconnects and persisted in the session store; **(b)** event IDs assigned at durable outbox append, with the outbox row carrying the idempotency key so replay can be deduped; **(c)** bounded outbox depth with explicit `429`/`Retry-After` backpressure instead of unbounded socket buffering; **(d)** client-side cursor advance only after effect commit, with the cursor and the idempotency key co-persisted. The invariant to enforce is: *for any event ID e, at most one effect is committed whose provenance is e, across all reconnects within the session TTL.* ```python import hashlib import time from dataclasses import dataclass, field from typing import Optional class ResumptionDuplicationError(RuntimeError): """Raised when a resume would replay an event whose effect is already committed.""" @dataclass class OutboxEntry: event_id: int idempotency_key: str payload: dict committed: bool = False @dataclass class SessionOutbox: session_id: str ttl_seconds: float = 3600.0 entries: dict = field(default_factory=dict) # event_id -> OutboxEntry by_key: dict = field(default_factory=dict) # idempotency_key -> event_id created_at: float = field(default_factory=time.time) def append(self, event_id: int, idempotency_key: str, payload: dict) -> OutboxEntry: if idempotency_key in self.by_key: # A replay of the same logical call: do not append a second effect. existing = self.entries[self.by_key[idempotency_key]] if existing.payload != payload: raise ResumptionDuplicationError( f"idempotency_key {idempotency_key} reused with divergent payload" ) return existing entry = OutboxEntry(event_id=event_id, idempotency_key=idempotency_key, payload=payload) self.entries[event_id] = entry self.by_key[idempotency_key] = event_id return entry def resume_from(self, last_event_id: int) -> list: if time.time() - self.created_at > self.ttl_seconds: raise ResumptionDuplicationError( f"session {self.session_id} TTL expired; resumption unsafe" ) replayed = [e for eid, e in sorted(self.entries.items()) if eid > last_event_id] # Invariant: replay must not include an event whose effect is already committed # unless the client's request carries the same idempotency_key (dedupe path). return replayed def handle_resume(outbox: SessionOutbox, last_event_id: int, client_idempotency_key: Optional[str]) -> list: replayed = outbox.resume_from(last_event_id) for entry in replayed: if entry.committed and client_idempotency_key != entry.idempotency_key: raise ResumptionDuplicationError( f"event {entry.event_id} effect already committed under key " f"{entry.idempotency_key}, but resume carried " f"{client_idempotency_key!r}; refusing to replay into duplicate effect" ) return replayed ```