Core Concepts
Live Updates and Reconnects
Resume a streamed reply after a dropped connection and repair client state when replay runs out.
A live connection carries updates as they happen. When it closes, the client needs a way to catch up. The client can send the ID of the last update it applied. If the server still has the later updates, it can send the missing ones.
Keep the reply open
The browser submits the prompt with an HTTP request. The app saves it as turn 17, one prompt and its reply, and returns a link the browser can open to listen. The gateway, the HTTP server the browser talks to, keeps the new response open while it sends text. The worker saves each displayable piece of the reply in a reply log, an ordered list of events the gateway can read.
With Server-Sent Events (SSE), the gateway sets the response type to text/event-stream and sends events as text. Each update can include an id, an event name, and data. An empty line ends the update. For example, the second chunk looks like this on the wire. HTML Standard on parsing an event stream
id: 1700-2
event: text
data: {"text":" change"}
The browser's EventSource reads the response and gives the page each complete event. An event called text adds a chunk to the reply. A final finished event tells the page it can close the stream. The application chooses those event names. If the user presses Stop, the browser can send a separate HTTP request while the reply stream is open. HTML Standard on the EventSource interface
Resume from the last applied event
Gateway A forwards 1700-1 ("Leaves") and 1700-2 (" change"). The browser applies both and remembers 1700-2. This ID is a cursor, the point in the reply after which it needs more events. The connection drops. The worker adds 1700-3 (" color.") to the same reply log.
On automatic reconnect, EventSource includes its last event ID in the Last-Event-ID header when that ID is nonempty. Here the page had already applied that event. The new connection reaches Gateway B. B checks that the account can read turn 17, then reads events after 1700-2 from the shared log. It sends 1700-3 so the page can complete the reply. The browser can reconnect through whichever gateway handles the request because the replay history lives in the shared log. HTML Standard on the Last-Event-ID header
During a reconnect, the worker may keep generating text. If B reads the log once and then subscribes to a separate live feed, an event can land between those steps. B can instead run one loop against the log. Read after the last ID sent, forward the available entries in order, and wait for later entries in that same log. In the ChatGPT walkthrough, the gateway uses Redis Streams. Its XREAD command returns entries with IDs greater than the supplied ID. Use a finite wait. On timeout, check the durable turn status. If the turn is finished and the terminal event was lost, send a snapshot of the saved result. Redis XREAD
Keep the cursor with the displayed text
Suppose the browser still shows "Leaves change color." but reconnects using an older saved cursor, 1700-2. The gateway sends 1700-3 again. The page already applied it, so it compares the incoming ID to its last applied ID and skips the repeated chunk. This comparison works for IDs that increase in one verified log. In Redis Streams the IDs have two numeric parts, so compare those parts in order. Redis Streams entry IDs
The header tracks what EventSource has parsed, and it can advance before the page applies an event. If the page applies events in order and keeps that applied prefix in memory through a reconnect, the gateway can prefer the header on that instance. If application work is pending or uncertain at disconnect, close that instance and resume from the last safely applied cursor.
To recover across reloads, save the text and its last applied ID together as one checkpoint. Open a fresh EventSource with a query cursor such as ?after=1700-2 only when the matching text was restored. A fresh instance has no previous header, so the gateway uses the query cursor. If only the cursor survived, rebuild the prefix from the beginning of the reply when the log still has it. Use the recovery path below if that history is unavailable. HTML Standard on dispatching SSE events
Replace the view when history runs out
We can keep reply events for a fixed period after a turn finishes. That gives reconnecting browsers a window in which they can replay them and bounds how long the log occupies storage. Once the log expires, Gateway B may still have a cursor from the browser, but it has no events to send from that position.
A snapshot is a complete version of the state the user needs. When turn 17 has finished, B can fetch the full saved reply from the Results DB, the durable store for completed turns. B sends "Leaves change color." as a snapshot. The browser replaces "Leaves change" with the full text and closes the stream. If the turn is still active and the log is unavailable, the gateway reports that it cannot resume live delivery. The app can show the existing prefix as incomplete and check for a saved result later.
Check that the log still has the missing history
A larger ID gives the event an ordering position. Consider a Redis primary that reported 1700-3 saved, then died before copying that entry to its replacement. The browser last applied 1700-2. The replacement can append a newer ID, yet the browser would miss " color." if it just took the next available entry. Redis Cluster's asynchronous replication leaves such a loss window. Redis Cluster write safety
The ChatGPT design records which Redis server and ownership version opened each reply log. If a restart, change of owner, or missing log breaks the continuity check, the gateway falls back to the durable turn. If your design also trims the front of a live log, track how far back uninterrupted replay is still possible. A cursor outside that range needs the same recovery path. Redis stream trimming
Keep slow connections from holding unlimited work
A stream can be open while the browser stops reading. If the gateway keeps queuing every new event in memory, one slow connection can hold a growing buffer. Put a limit on queued bytes per connection and close a connection that exceeds it. The app can reconnect and catch up as far as the retained log allows. If we promise a replay window during traffic spikes, the log also needs room for the events a turn can produce in that window.
The gateway can send occasional SSE comments to keep an idle connection active. Configure intermediaries to pass updates through as they arrive. A proxy that collects bytes before forwarding them can make every chunk appear at once. HTML Standard authoring notes · nginx response buffering
Carry live commands over a WebSocket
For the streamed reply, one direction carries most of the ongoing traffic. In Online Chess, players frequently send moves and the server sends both players updates. A WebSocket gives the app one open connection for messages in both directions. The connection carries a command such as "move this piece" and messages from the server such as a move acknowledgment or a new board. WebSocket Protocol
A player sees the board at server sequence 7 and sends move 8. The game service validates and applies the move, advancing its sequence to 8. The socket drops before the player receives the acknowledgment. From the disconnect alone, the player cannot tell whether the server applied the move or never saw it.
The client opens a new socket. In the Online Chess design, the gateway routes to the service responsible for the game. The server sends a game_state snapshot with the board, clocks, and current serverSeq. Here that sequence is 8 and the board includes the move. The player replaces the local board, including any move the page had shown before confirmation. If a retry of move 8 arrives, the server sees that 8 already passed and rejects it before changing the board. The server accepts a legal move only at the next sequence number.
For a general command that may race with other users' actions, use an operation ID and remember its outcome so the client can check that specific command.
The browser's WebSocket app opens its own new connection and decides what to send or restore. After unexpected closures, spread reconnect attempts over time with short random delays and longer waits after repeated failures. This keeps a fleet of clients from rushing back at once. Each new connection still needs permission to receive the stream or join the game. WebSocket recovery after abnormal closure
See also
- Idempotency explains how a server can act on the same command identity on a retry.
- Redis compares live Pub/Sub with a retained Redis Stream.
- Messaging and Work Queues follows retries and replay through different delivery models.
- Backpressure and Load Shedding covers what happens when new work arrives faster than it can finish.
Used in
- ChatGPT uses an SSE reply, a short-lived replay log, and a saved final reply for recovery.
- Online Chess uses WebSockets for live moves and sends an authoritative board snapshot on reconnect.
Done reading? Mark it so it sticks in your dashboard.