--- name: sse-reconnect-replay-testing description: "Test Server-Sent Events (SSE) reconnect, Last-Event-ID replay, duplicate/gap/order defects, cursor expiry, HTTP 204 termination, and frame edge cases locally." category: testing risk: safe source: self source_type: self date_added: "2026-12-01" author: Koushik-Katkam tags: [sse, server-sent-events, eventsource, replay, testing, reliability] --- # SSE Reconnect and Replay Testing ## Overview Verify Server-Sent Events (**SSE**) stream correctness from the client perspective using deterministic loopback fixtures and a real WHATWG `EventSource` client (`eventsource` in Node.js or browser `window.EventSource`). This workflow isolates reconnect transport mechanics (`Last-Event-ID`, `retry:`, HTTP `204 No Content`, frame parsing) from application-level acknowledgment and deduplication. Distinction from existing streaming skills: - `neon-functions` ([references/sse.md](https://github.com/sickn33/agentic-awesome-skills/blob/e4dcf3977b6d1e18a2539f630bd82c2433d283e2/skills/neon-functions/references/sse.md)) builds Hono/`ReadableStream` SSE endpoints and Postgres `LISTEN/NOTIFY` fan-out, noting that replay must be implemented separately without providing a reconnect/replay test harness. - `embedded-agents-agent-sdk` and `embedded-agents-messages-api` wire Claude Agent SDK / Anthropic Messages API tool runners inside Next.js App Router streams rather than validating low-level SSE cursor resume, duplicate/gap defects, or frame termination. - `backend-architect` and `fastapi-pro` provide high-level API/SSE architecture and FastAPI async streaming guidance without executable protocol replay suites. ## When to Use - Auditing an SSE backend's `Last-Event-ID` resume handler before shipping live feeds, notifications, or LLM token streams. - Reproducing reconnect bugs: missing `Last-Event-ID` replay (`1,2,1,2,3,4` duplicates), dropped events (`1,2,4`), out-of-order replay (`1,2,4,3`), stale cursor handling, broken multiline payloads, or infinite reconnect storms after `204 No Content`. - Confirming that empty `id:` resets clear `lastEventId` and truncated trailing frames before socket drops are discarded rather than committed. - Do **not** use this skill to design Postgres/Redis pub-sub fan-out (`neon-functions`) or Claude SDK wrappers (`embedded-agents-messages-api`). ## Prerequisites - Node.js 22.12.0+ (tested on Node.js `v24.21.0`) with the `eventsource` package pinned to **`eventsource@5.1.6`** (`npm install --ignore-scripts --save-exact eventsource@5.1.6`; `eventsource@5.1.6` is the tested runtime) or an authorized browser `EventSource` runtime. - Loopback-only (`127.0.0.1:0`) test execution with no external network requests or production credentials. ## How It Works ### 1. Separate transport delivery from application guarantees - **SSE does not guarantee exactly-once delivery.** Network drops after server enqueue or unindexed replay windows can cause duplicates (`at-least-once` when replaying safely) or missed events (`at-most-once` when buffers expire). - **Event IDs are opaque strings on the wire** per WHATWG HTML §9.2.6; sequence checks verify delivered positions against expected cursor order without assuming numeric parsing unless the application explicitly assigns numeric IDs. - **Duplicate detection assumes unique application event identifiers.** SSE itself permits **repeated** `id:` values on distinct events and **inherited** ids (an event with no `id:` field keeps the current `lastEventId`; an empty `id:` resets `lastEventId` to `""`). Under repeated or inherited ids, `duplicates`/`outOfOrder`/`missing` results are not defects. Deduplicate on a unique application event identifier (not raw SSE `id`), with persistent offset checkpoints and idempotent processing in application storage. - Transport tests assert what `EventSource` observes on the wire (`Last-Event-ID` header, sequence order, `event: resync` notifications, `204` closure). Idempotent processing and persistent offset checkpoints belong in application storage. ### 2. Test reconnect, replay anomalies, and frame parsing edge cases Execute the loopback harness in [SSE replay harness](references/sse-replay-harness.md): 1. **Controlled disconnect & `Last-Event-ID` header assertion:** Drop the TCP socket immediately after sending event `id: 2`. Verify the reconnect HTTP request carries `Last-Event-ID: 2` and cleanly delivers `1, 2, 3, 4`. 2. **Broken replay vs. sequence anomalies:** Detect duplicate restarts (`1, 2, 1, 2, 3, 4` when a server ignores `Last-Event-ID`), gaps (`1, 2, 4`), and out-of-order delivery (`1, 2, 4, 3`). 3. **Expired replay cursor & explicit resync policy:** Requesting `Last-Event-ID: 1` when the server buffer retains only `>= 3` must follow the service's declared contract — either emitting an explicit `event: resync` frame before streaming `3, 4` (or terminating cleanly per policy) rather than silently hiding lost events. Verify **unified chronological order on one timeline** (ordinary messages + custom events interleaved by arrival): **Event 1 → Resync notification → Event 3 → Event 4**; a swapped order (Event 3 before the resync notification) must fail ordering assertions (negative ordering regression). 4. **Empty `id:` reset, multiline `data:`, incomplete trailing frame:** Verify `id:` with empty value resets `lastEventId` to `""` and omits `Last-Event-ID` on reconnect per WHATWG HTML §9.2.6; multiline `data:` lines join with `\n`; incomplete trailing `data:` frames before disconnect never dispatch to `onmessage` and never overwrite `lastEventId`. 5. **HTTP `204 No Content` & bounded cleanup:** Returning HTTP `204` must transition `EventSource.readyState` to `CLOSED` with zero subsequent reconnect attempts. **Capture the natural terminal state before manual cleanup and observe a bounded reconnect interval** (longer than `retry:`) *without* manually closing the client first, asserting no additional requests arrive; only then perform manual cleanup. Enforce per-test timeouts, request counters (`maxAttempts`), `es.close()`, `socket.destroy()`, and `server.closeAllConnections()` so tests never leak sockets or timers. ### 3. Verify and report client runtime boundaries Verify exact received `(id, event, data)` sequences and request headers. Disclose explicitly whenever verification used Node's `eventsource` package (`eventsource@5.1.6`) rather than native browser `window.EventSource`. ## Examples Run the self-contained loopback suite from [SSE replay harness](references/sse-replay-harness.md): ```text User request: "Test whether our SSE endpoint safely resumes after disconnect without duplicating or losing events." Inputs: Synthetic 127.0.0.1 loopback HTTP server + eventsource@5.1.6 client. Expected result: Correct replay asserts headers ['Last-Event-ID' == '2'] on reconnect and delivers [1, 2, 3, 4]; broken replay yields [1, 2, 1, 2, 3, 4] and flags duplicates; gap [1, 2, 4] and inversion [1, 2, 4, 3] fail monotonicity checks; expired cursor triggers explicit 'resync' event before [3, 4]; empty 'id:' omits Last-Event-ID; incomplete trailing frames do not dispatch; and HTTP 204 stops reconnection cleanly. ``` ## Limitations - **Client runtime disclosure:** Because Node.js v24 does not expose `globalThis.EventSource` by default in standard globals, the bundled harness uses the maintained `eventsource` (`eventsource@5.1.6`, pinned) WHATWG client library rather than browser `window.EventSource`. Browser-specific CORS enforcement, HTTP/2 connection coalescing, reverse-proxy response buffering, and background-tab timer throttling are not exercised in loopback Node tests. `eventsource@5.1.6` is the tested runtime; a Node 22.16.0 experimental `EventSource` run passed 6/7 tests but failed the empty-`id:` reset assertion, which is **not** a defect in `eventsource@5.1.6`. - **Unified timeline:** ordering checks use one chronological `timeline`; `messages`/`custom` are derived views, not the source of order. - Real distributed replay stores (Redis Streams, Kafka, Postgres WAL) and downstream consumer idempotency persistence must be tested against your target infrastructure. ## Safety and Side Effects - Runs exclusively against ephemeral `127.0.0.1:0` loopback sockets inside the local test runner. - No remote endpoints, credentials, cookies, or database writes are accessed; bounded request limits and timeouts prevent runaway reconnect loops. ## Sources and related skills - [WHATWG HTML Standard — Server-Sent Events](https://html.spec.whatwg.org/multipage/server-sent-events.html) - Related skills: [neon-functions SSE](https://github.com/sickn33/agentic-awesome-skills/blob/e4dcf3977b6d1e18a2539f630bd82c2433d283e2/skills/neon-functions/references/sse.md), [embedded-agents-messages-api](https://github.com/sickn33/agentic-awesome-skills/blob/e4dcf3977b6d1e18a2539f630bd82c2433d283e2/skills/embedded-agents-messages-api/SKILL.md), [embedded-agents-agent-sdk](https://github.com/sickn33/agentic-awesome-skills/blob/e4dcf3977b6d1e18a2539f630bd82c2433d283e2/skills/embedded-agents-agent-sdk/SKILL.md), [backend-architect](https://github.com/sickn33/agentic-awesome-skills/blob/e4dcf3977b6d1e18a2539f630bd82c2433d283e2/skills/backend-architect/SKILL.md), [fastapi-pro](https://github.com/sickn33/agentic-awesome-skills/blob/e4dcf3977b6d1e18a2539f630bd82c2433d283e2/skills/fastapi-pro/SKILL.md).