# Where must an instance re-establish event-ID monotonicity after an MCP stream resumes behind a load balancer **Date of Record:** 2026 November 27 **Scope:** Applies to MCP servers exposing HTTP-native streaming (SSE) with resumable sessions (`Last-Event-ID` replay) fronted by L7 load balancers or any multi-replica fan-out. Does not apply to single-process stdio transports or to stateless request/response MCP endpoints with no event log. ## Core Distinction The failure is not "the stream disconnected." Disconnection is normal and the resumable-SSE contract exists precisely to survive it. The failure is that **event-ID monotonicity is a per-connection property in most implementations but a per-session property in the protocol's intent**. When a client reconnects with `Last-Event-ID: N`, the server is obligated to replay every event with ID > N *for that session*. Behind a load balancer, the reconnection routinely lands on a replica that never held the session's event log, or holds a divergent one. The resumption then succeeds at the transport layer (HTTP 200, `text/event-stream` established) while silently violating the exactly-once delivery invariant at the semantic layer: either events in `(N, M]` are dropped because the new replica's log starts at M, or events are re-delivered because the new replica's log is a superset with different IDs for the same logical payload. The non-obvious part: **a successful SSE handshake is not evidence of correct resumption.** The protocol has no built-in acknowledgement for replayed ranges, so a gap-prefixed stream looks identical to a clean one from the client's socket. The agent consuming the stream has no signal that its tool-call results are missing unless it independently tracks expected IDs. ## What Was Observed An MCP server was deployed as three replicas behind a round-robin L7 balancer with no session affinity. Sessions were stored in each replica's local memory; a shared Redis was used only for the session *metadata* (capabilities, negotiated schema), not the event log. A client agent held an open SSE stream for a long-running `tools/call` that emitted progress events with monotonically increasing integer IDs. Trace of the failure: 1. Client is connected to replica A. It has received events `1..47`. The `tools/call` is mid-execution on replica A's worker. 2. A 30-second idle timeout on the balancer's upstream connection closes the stream. The worker on A continues; it does not know the client is gone. 3. Client reconnects with `Last-Event-ID: 47`. Round-robin routes it to replica B. 4. Replica B has no record of this session's event log. Depending on implementation, one of three things happens: - **B returns 404 / session-not-found.** Correct behavior; client must re-init. Often masked by a retry that lands on A. - **B lazily creates a new event log starting at ID 1.** The client, which sent `Last-Event-ID: 47`, receives events `1, 2, 3...`. A compliant client per the SSE spec sees IDs that are *lower* than its last-seen ID and must treat this as a new stream — but many MCP client libraries do not enforce this and simply append, corrupting ordering. - **B replays from a shared log with a different ID namespace** (e.g., UUIDs generated per-replica). The client's `Last-Event-ID: 47` matches nothing; B either replays everything or nothing. 5. Meanwhile replica A completes the tool call and writes the final result event with ID `48` into its local log. The client never sees it. The agent's reasoning loop blocks on a tool result that was emitted but never delivered, until its own token budget or wall-clock deadline expires. The observed end state: the agent reported "tool call timed out" while the server logged "tool call completed successfully, result delivered." Both were correct within their own scope. The gap was invisible to both. ## Condition of Validity The invariant that must hold for resumable SSE to be sound is: > For any session S and any client-observed last-event-ID N, a reconnect with `Last-Event-ID: N` must yield a contiguous replay of exactly the events in `(N, current]` for S, with stable IDs, regardless of which replica serves the reconnect. This holds only when one of the following is true: - **Sticky routing is guaranteed at the session level**, not the connection level. The balancer must hash on a session token (cookie or URL path segment), and that hash must be stable across connection churn. Connection-level affinity (source-IP hashing) is insufficient because NAT and mobile clients change source IPs mid-session. - **The event log is externalized** to a shared store with per-session monotonic ID allocation (a single sequencer, or a per-session counter with fencing). Replicas become stateless readers of a shared log. - **The session is explicitly migrated** on reconnect: the receiving replica fetches the log and the in-flight worker state from the origin replica before accepting the stream, and rejects the connection (forcing client re-init) if migration fails. If none hold, resumable SSE is a false guarantee: the transport resumes, the semantics do not. The condition is *invalid* when the balancer's health checks or retry logic can silently route a reconnect to a replica that will answer 200 with a fresh, empty log. That is the specific hazard: a 503 or 404 is safe (the client knows to re-init); a 200 with a reset log is unsafe. ## Decision Boundary The operational decision is **when to treat a resumed stream as authoritative versus when to force session re-initialization**. The boundary is drawn at the first event received after reconnect: - If the first replayed event's ID is exactly `N+1` (or the session has no events in `(N, current]` and the stream is correctly idle), accept the resumption. The log is contiguous. - If the first replayed event's ID is `> N+1`, there is a gap. **Do not accept.** The missing events may include tool results the agent is blocked on. Force re-init and re-issue the pending request idempotently (requires the tool to be idempotent or the request to carry a dedup key). - If the first replayed event's ID is `<= N`, the replica has reset or is serving a different ID namespace. **Do not accept.** Force re-init. - If the stream is idle for longer than the tool's expected completion window and no event with ID `> N` arrives, treat as a delivery failure, not a slow tool. The worker may have completed on a replica the client can no longer reach. The agent must therefore maintain, per session, the tuple `(session_id, last_event_id, pending_request_ids)` and validate every replayed event against it before feeding it into the reasoning loop. This is a client-side guardrail that the MCP transport layer does not provide. ## Operational Effect Without the guardrail, the failure mode is **silent result loss with a healthy-looking stream**: agents block on tool calls whose results were emitted but never delivered, exhausting token budgets or wall-clock deadlines while server logs show success. Retries amplify the problem if the tool is non-idempotent — the agent re-issues a `tools/call` whose original execution already mutated state, producing duplicate side effects. With the guardrail, the failure is converted into a **loud, bounded re-init**: the agent detects the ID discontinuity on the first replayed event, aborts the stream, and either re-establishes the session with full state re-negotiation or escalates to a human/auditor. The cost is a bounded re-execution of at most the in-flight request, gated by idempotency keys. The architectural requirement: **event-ID allocation must be a property of the session, not the replica, and the client must validate contiguity on every resume.** Neither the balancer nor the SSE handshake can enforce this; it is a joint invariant between the server's log design and the agent's stream consumer. ```python from dataclasses import dataclass from typing import Iterable class StreamResumeViolation(RuntimeError): """Raised when a resumed SSE stream violates per-session event-ID contiguity.""" @dataclass(frozen=True) class StreamEvent: event_id: int session_id: str payload: dict class ResumableStreamGuard: """ Client-side guard enforcing the invariant: on resume with Last-Event-ID=N, the first event must have id == N+1 (or the stream must be correctly idle). Any other first event is a resume violation and must force session re-initialization. """ def __init__(self, session_id: str, last_event_id: int): self.session_id = session_id self.last_event_id = last_event_id self._resume_pending = True def accept(self, event: StreamEvent) -> StreamEvent: if event.session_id != self.session_id: raise StreamResumeViolation( f"event for session {event.session_id!r} arrived on stream " f"for session {self.session_id!r}; replica routing crossed sessions" ) if self._resume_pending: expected = self.last_event_id + 1 if event.event_id != expected: kind = ( "gap" if event.event_id > expected else "reset-or-namespace-collision" ) raise StreamResumeViolation( f"resume violation on session {self.session_id!r}: " f"sent Last-Event-ID={self.last_event_id}, " f"expected first event id={expected}, got {event.event_id} ({kind}). " f"Force re-init; do not feed this event into the reasoning loop." ) self._resume_pending = False if event.event_id != self.last_event_id + 1: raise StreamResumeViolation( f"non-contiguous event on session {self.session_id!r}: " f"last={self.last_event_id}, got {event.event_id}" ) self.last_event_id = event.event_id return event def consume(self, events: Iterable[StreamEvent]) -> list[StreamEvent]: return [self.accept(e) for e in events] def resume_session( guard: ResumableStreamGuard, reconnect_stream: Iterable[StreamEvent], idle_after_seconds: float | None = None, tool_deadline_seconds: float = 120.0, ) -> list[StreamEvent]: """ Consume a reconnected SSE stream under the contiguity invariant. If the stream is idle past the tool deadline with no event > last_event_id, treat as delivery failure rather than slow tool. """ accepted: list[StreamEvent] = [] saw_any = False for event in reconnect_stream: saw_any = True accepted.append(guard.accept(event)) if not saw_any and idle_after_seconds is not None: if idle_after_seconds > tool_deadline_seconds: raise StreamResumeViolation( f"session {guard.session_id!r}: stream idle {idle_after_seconds:.1f}s " f"past tool deadline {tool_deadline_seconds:.1f}s with no event " f"> {guard.last_event_id}; worker likely completed on an " f"unreachable replica. Force re-init and re-issue with dedup key." ) return accepted ```