Resume Cursors Without Duplicate Text
Design resumable token streams with durable event identity, explicit replay boundaries, and client checkpoints that survive disconnects without duplicated text.
The browser reconnects after receiving half a sentence. The server resumes from its last successful write, and the interface displays the final three words twice. Neither endpoint necessarily violated its local contract. The server observed a transport write; the browser observed and rendered an event. Those observations are not the same acknowledgement boundary.
A resumable token stream needs an application protocol layered over its transport. That protocol must define event identity, replay retention, ordering, and the point at which a consumer considers an event applied. Server-sent events provide useful reconnect machinery, but the application still owns the meaning of a cursor and the durability of the content behind it.
Name events before sending them
Assign each generation a unique identifier and each committed event a monotonically increasing sequence number. The pair is the event identity. A sequence number alone is unsafe if reconnecting accidentally starts a new generation whose numbering begins again at zero. Include a protocol version as well, so an older client does not interpret a revised event envelope incorrectly.
Persist an event before making it eligible for replay or live delivery. Otherwise a client can receive an event that disappears after the server restarts. The append log becomes the authoritative stream, while the network connection becomes a delivery mechanism. This distinction also makes it possible to attach a second viewer without starting another generation.
The event envelope should distinguish text deltas, metadata changes, recoverable notices, and terminal states. A terminal event is a real log entry with an identity. An empty network read is not proof that generation completed successfully; it may indicate a failed intermediary, a canceled request, or a lost connection.
Choose the cursor boundary explicitly
The HTML Standard defines how EventSource reports its last event identifier through the Last-Event-ID header during reconnection. That identifier reflects the event-stream mechanism. It should not be assumed to prove that the application durably stored its transcript or finished rendering an event before a tab crashed.
For an ephemeral chat view, in-memory duplicate suppression may be sufficient. For a durable transcript, save the accumulated state and applied sequence checkpoint atomically in the client's persistence layer where available. On reload, request events after that checkpoint. If the transcript and cursor are stored separately, a crash between writes can produce either repeated text or a missing suffix.
The server should interpret cursor N as “deliver committed events with sequence greater than N,” not “deliver starting with N unless convenient.” Inclusive versus exclusive replay is a small ambiguity with a large debugging cost. Specify it in protocol documentation and encode it in fixtures that include reconnects at the first event and the terminal event.
Expect duplicates at the delivery boundary
Assume event 42 was delivered, but the connection failed before the consumer recorded its checkpoint. Replaying event 42 is reasonable. The consumer should identify it as already applied when its transcript state proves that fact, or safely apply it once if the state was not committed. This is easier when rendering is a projection of an event log than when every network callback directly appends arbitrary text.
Figure 1 — Event 42 arrives at steps three and four; the durable applied checkpoint stays at 41 at step three and reaches 42 at step four. The repeated delivery is harmless when event identity controls application. Illustrative model — not measured data.
Do not deduplicate by text content. Two consecutive events may legitimately contain the same word, punctuation mark, or whitespace. Hashing the text and dropping repeated hashes changes the answer. Identity belongs to the generation and sequence, not to the visible characters.
Ordering needs an equally explicit rule. If event 45 arrives while the consumer expects 44, stop advancing the applied checkpoint. Buffer within a small bound or request a repair. Continuing to render and later inserting event 44 can corrupt structured output and make the stored transcript differ from what the reader saw.
In this timeline, delivery steps one through six carry sequences 40, 41, 42, 42, 43, and 44. The durable checkpoints are 40, 41, 41, 42, 43, and 44. At the interruption, the uncommitted projection is discarded; replay applies event 42 to the state saved through 41. If the client instead retains a visible but uncommitted projection, it must reconcile that projection before appending redelivery. A transport event identifier alone cannot resolve the difference between those client persistence states.
Retention is part of the public contract
A reconnect cursor cannot work after its corresponding history has been discarded. Define retention by time and size, then communicate the earliest available sequence. A request older than that boundary needs a distinct response: either a compatible snapshot plus subsequent events, or an explicit instruction to restart with a new generation.
For a hypothetical stream producing 80 events per second with 200 bytes per event, ten minutes of raw replay payload occupies 9.6 megabytes. One thousand simultaneously retained streams would require 9.6 gigabytes before metadata and replication. Coalescing reduces event overhead, but longer retention and large metadata events can dominate the result.
Figure 2 — At the assumed fixed rate, retention cost grows linearly. Operational storage must additionally account for indexes, replication, and event-size variation. Illustrative model — not measured data.
A snapshot should identify the sequence through which it is complete. The consumer replaces its projected state with the snapshot and resumes after that sequence. Do not combine an unversioned transcript snapshot with a current replay cursor; the gap between their creation times can silently omit content. Snapshot publication needs the same disciplined boundary as event publication.
Keep authorization outside the cursor
A cursor is a position, not permission to read. Reconnecting must authenticate the viewer and authorize access to the generation again. Avoid putting secrets or raw user identifiers into a cursor that may appear in logs. An opaque token can carry a signed position reference, but the server must still evaluate the current access policy.
Shared generations complicate cancellation. One viewer closing a tab should usually detach that viewer rather than cancel computation for everyone. Distinguish subscriber cancellation from generation cancellation, and require appropriate authority for the latter. Persist generation cancellation as a terminal state so a later reconnect does not wait indefinitely for events that will never arrive.
There is also a cost boundary. If every reconnect restarts upstream generation, a flaky network can multiply inference work while producing several incompatible continuations. Reuse the durable generation identity and append history. When resumption is impossible, label the replacement generation clearly and avoid presenting it as a continuation of the old byte stream.
Heartbeat frames should not advance the content checkpoint unless the application protocol deliberately gives them durable event identity. A transport keepalive establishes that a connection path is responsive; it does not establish that new content has been committed. Mixing the two can create cursors that refer to nothing in the replay log. Keep liveness monitoring and transcript progress separate in both the event format and the operational dashboard.
Build tests around interruption points
Use a deterministic source that emits a short sequence containing repeated words, empty text deltas, multibyte characters, metadata, and a terminal event. Disconnect before persistence, after persistence but before write, during delivery, after client application, and before checkpoint persistence. Each interruption exercises a different boundary and should end with the same projected transcript or an explicit unrecoverable state.
Test expired cursors, unknown generations, future sequence numbers, and revoked access separately. A future cursor should not cause the server to skip valid output indefinitely. An expired cursor should not produce a successful empty stream. Ambiguous success responses are particularly damaging because monitoring sees healthy connections while readers lose content.
Track replayed events, duplicate suppressions, sequence gaps, cursor expiry, and generation restarts as separate metrics. A high duplicate count may simply reflect unstable connections handled correctly; a single unexplained sequence gap is a stronger integrity signal. Resumability is successful when the transcript remains coherent across failures, not merely when the browser reconnects quickly.