# Reconnection and Last-Event-ID — WebSockets & Server-Sent Events

Source: https://www.skillbyai.com/en/realtime-web/rt-sse-reconnect

> Make an SSE stream resumable so a client that drops and reconnects misses no events.

## How resumption works

When an SSE connection breaks, the browser waits for the reconnection delay (a few seconds by default, or whatever the last `retry:` field set) and sends a fresh GET. If any event so far carried an `id:`, the new request includes the header `Last-Event-ID` with that value. The server's job is to read the header and **replay every event after that id** before streaming live ones. That requires two things you design yourself. Ids must be **ordered**, such as a database sequence, a Redis stream id or a monotonic counter per topic; random UUIDs cannot answer "what came after this?". And the server must **keep recent history** long enough to cover typical outages, perhaps the last few minutes in Redis or the last N rows in a table. If the requested id is older than your history, send a special event telling the client to refetch a full snapshot instead of pretending nothing was lost.

## The reconnect cycle

A drop is not an error to show the user; it is a normal step in the stream's life that the protocol already handles.

![Four connected stages in order: connection drops, browser waits the retry delay, browser reconnects sending Last-Event-ID, server replays missed events.](assets/figures/realtime-web/section-3-map.svg) — Figure 3.1: disconnect -> wait retry delay -> reconnect with Last-Event-ID -> replay missed events

## Replaying from Last-Event-ID

The server filters its history by the header. The demo sends the header the way a reconnecting browser would, after it had already seen event 1.

```js
import http from 'node:http';

const history = [
  { id: 1, data: 'order placed' },
  { id: 2, data: 'payment received' },
  { id: 3, data: 'out for delivery' },
];

const server = http.createServer((req, res) => {
  const lastId = Number(req.headers['last-event-id'] ?? 0);
  res.writeHead(200, { 'Content-Type': 'text/event-stream' });
  for (const e of history.filter((e) => e.id > lastId)) {
    res.write(`id: ${e.id}\ndata: ${e.data}\n\n`);
  }
  res.end();
});

server.listen(3001, async () => {
  // Simulate a browser reconnecting after it already saw event 1.
  const resp = await fetch('http://localhost:3001/', {
    headers: { 'Last-Event-ID': '1' },
  });
  console.log(await resp.text());
  server.close();
});
```

Output:

```
id: 2
data: payment received

id: 3
data: out for delivery
```

## Return 204 to stop retries for good

EventSource retries forever on network errors. When a stream is permanently over (the order was delivered, the job finished), respond with `204 No Content` or send an event that tells your code to call `close()`. A non-200 status makes the browser stop reconnecting.

**Quiz:** Why are random UUIDs a poor choice for SSE event ids when you need resumption?

- [ ] They are too long for the `id:` field
- [x] The server cannot tell which events came after a given UUID without extra ordering data
- [ ] Browsers reject ids containing hyphens
- [ ] UUIDs disable automatic reconnection

*Answer:* The server cannot tell which events came after a given UUID without extra ordering data. Resumption means "send everything after X". That needs an ordering; a UUID alone does not say what came before or after it.
