# Your stream resume fires before it knows the server restarted

> After a server restart, a WebSocket resume sent on socket open replays stale cursors and silently drops text. The fix: resume only after the handshake names the process.

- Author: Chad Priest
- Published: 2026-10-11
- Canonical URL: https://blog.awe.run/your-stream-resume-fires-before-it-knows-the-server-restarted/
- Tags: websockets, javascript, debugging, distributedsystems

---

I restarted the gateway with a chat tab open. The next reply showed up with roughly its first 150 characters missing. Nothing threw an error, and the database had the whole message. The client had decided the start of the reply was a duplicate and thrown it away.

I [wrote up the root cause last week](https://blog.awe.run/stream-resume-cursors-dont-survive-a-server-restart/): the cursors outlived the process that numbered them. This post covers the smaller mistake I made in the client. It took me longer to see than it should have, and I'd bet your code has it too.

## The `open` handler resumed before the server had said anything

The client kept a map from conversation id to the last seq it had seen. When the socket opened, it sent a resume for every entry. Every incoming event then went through one dedupe guard:

```js
// before
ws.addEventListener('open', () => {
  for (const [conversationId, lastSeq] of lastSeqByConv)
    ws.send(JSON.stringify({ type: 'resume', conversationId, lastSeq }));
});

ws.addEventListener('message', (e) => {
  const msg = JSON.parse(e.data);
  const prev = lastSeqByConv.get(msg.conversationId) || 0;
  if (msg.seq <= prev) return;            // "duplicate"
  lastSeqByConv.set(msg.conversationId, msg.seq);
  render(msg);
});
```

Look at when that resume goes out. `open` means the TCP connection and the WebSocket upgrade worked. It tells the client nothing about *which* process answered.

Here is the numbering rule I had to go and read, because my first explanation of it was wrong. The gateway keeps a seq counter for each conversation. On a new process, the counter is seeded the first time that conversation streams, from the highest seq in a persisted event table. A janitor deletes rows older than 10 minutes from that table. So a quick restart continues the old numbering and does no harm. A restart after the conversation has been idle for 10 minutes finds no rows, and the counter starts again from 0.

At that point the client still holds its old high-water mark, call it H. The next reply arrives numbered 1, 2, 3…, and the guard drops every event up to H. The reply loses its first H events, or all of them if it is shorter than H. I didn't log H that afternoon, so I can't show you exactly how H events became ~150 characters. An earlier draft of this post said "seq 412". That number was an illustration, not a logged value, and I shouldn't have written it as if it were real. The mechanism is the overlap: whatever the client's old mark was, that many events disappear from the next reply.

## Moving `resume` from `open` to the handshake

The gateway already sent a `connected` message on every socket. It now includes `epoch`, which is `Date.now()` captured once at process start. The client waits for that message before deciding anything:

```js
// after
let serverEpoch = null, pendingResume = false;

ws.addEventListener('open', () => {
  pendingResume = lastSeqByConv.size > 0;  // decide later
});

ws.addEventListener('message', (e) => {
  const msg = JSON.parse(e.data);
  if (msg.type === 'connected') {
    if (serverEpoch && msg.epoch !== serverEpoch) {
      lastSeqByConv.clear();               // new process: its seqs start over
    } else if (pendingResume) {
      for (const [conversationId, lastSeq] of lastSeqByConv)
        ws.send(JSON.stringify({ type: 'resume', conversationId, lastSeq }));
    }
    pendingResume = false;
    serverEpoch = msg.epoch;
    return;
  }
  // ...same dedupe as before
});
```

When the epoch changes, the client sends no resume at all. Asking a process to replay events it never numbered is exactly how the text got eaten. History reloads from the database, which had the right answer all along.

This is a client-side fix, and it's the one I shipped. The server still trusts the client to compare epochs. A cursor that carried its generation (`epoch:seq`) would let the server reject a foreign cursor itself. I haven't built that yet.

## Cursors that outlive the process that numbered them

None of this is specific to WebSockets or LLMs. A server hands out positions from state that lives only in that process. The client keeps those positions across a restart or failover and sends them back to a process that never issued them.

The SSE version is the most common one: a `let id = 0` counter, an in-memory ring buffer, and `Last-Event-ID` sent back after a deploy. Socket.IO's connection state recovery avoids the trap, and it's a good model. Recovery is keyed to a session id the server issued. A restarted server using the default in-memory adapter doesn't recognise that session, so the client gets `socket.recovered === false` instead of a replay. That is the same generation check I added by hand. (An earlier draft also named Kafka and Redis Streams. I couldn't build a concrete case where either one silently accepts a stale position, so I took them out.)

[Ikoma's write-up on resumable streams](https://blog.yusukeikoma.com/posts/resumable-streams-cursors-last-event-id-snapshots/) gets most of this right: a cursor, a bounded log, a snapshot fallback, and an in-band `reset` event, because a non-200 response kills a native `EventSource`. The usual advice is to send `reset` when a cursor is too old. That doesn't cover a cursor that is *foreign*. After a restart, an old cursor doesn't look too old. It looks like the future, or it collides with a real new id, and an age check can't tell either way.

**Resume only after a handshake that identifies the process. If the identity changed, drop your cursors and reload. Never replay.**

## Three checks: two for your server, one for a resume sent on `open`

Three checks. The first two test your server. A server that passes them still doesn't prove your client is safe, because the bug I hit was in the client: the resume went out on `open`, and the dedupe ate the chunks. The third check tests the client.

**SSE server.** Replace the URL with your own.

```bash
# 1. Let a few events go by; ends on its own after 5s and prints the last id
curl -sN --max-time 5 http://localhost:3000/stream | grep --line-buffered '^id:' | tail -n1
#    -> id: 47
# 2. Restart the server process (not the client)
# 3. Resume with the old cursor
curl -sN --max-time 5 -H 'Last-Event-ID: 47' http://localhost:3000/stream | head -n 20
# PASS: first event is a reset/snapshot, or ids carry a generation ("id: 9f3a:1")
# FAIL: ids restart at 1 with no reset, or nothing until the counter passes 47
```

**WebSocket server.** Use [wscat](https://www.npmjs.com/package/wscat) and substitute your own resume frame.

```bash
# 1. Connect, trigger a stream, note the last seq you see
npx wscat -c ws://localhost:3000/ws
# 2. Restart the server process
# 3. Reconnect and send the resume with the old seq, then wait 5s
npx wscat -c ws://localhost:3000/ws -w 5 \
  -x '{"type":"resume","conversationId":"c1","lastSeq":47}'
# PASS: the handshake carries a process identity (epoch, boot id) that differs
#       from step 1, or the server answers the resume with a reset/snapshot frame
# FAIL: same handshake as before the restart, no reset, then data frames
#       numbered from 1 (or silence)
```

**Your client.** This test is the one that matters for the bug in the title. A fake server sends 20 events and "restarts". A new fake server then numbers a 30-chunk reply from 1. The assertion fails if any chunk goes missing. The stand-in client is my old code. Replace `startClient` with yours.

```js
// node resume-restart.test.mjs         (stand-in resumes on open: FAILS)
// node resume-restart.test.mjs fixed   (stand-in resumes on handshake: PASSES)
// needs Node 22+ (global WebSocket) and `npm i ws`
import { WebSocketServer } from 'ws';
import assert from 'node:assert/strict';

const PORT = 8099, URL = `ws://localhost:${PORT}`;
const reply = (n) => Array.from({ length: n }, (_, i) => `w${i} `);
const REPLY_2 = reply(30);

function boot(chunks, delayMs) {         // one fake process, seq from 1
  const wss = new WebSocketServer({ port: PORT });
  const epoch = Date.now() + Math.random();
  let seq = 0;
  wss.on('connection', (ws) => {
    ws.send(JSON.stringify({ type: 'connected', epoch }));
    setTimeout(() => {
      for (const text of chunks)
        ws.send(JSON.stringify({ conversationId: 'c1', seq: ++seq, text }));
    }, delayMs);
  });
  return wss;
}

function startClient(onText, fixed) {   // replace with your client
  const lastSeq = new Map();
  let epoch = null, pending = false, ws, stopped = false, hadSocket = false;
  const open = () => {
    ws = new WebSocket(URL);
    ws.onopen = () => {
      if (!fixed && hadSocket)
        for (const [conversationId, s] of lastSeq)
          ws.send(JSON.stringify({ type: 'resume', conversationId, lastSeq: s }));
      pending = hadSocket && lastSeq.size > 0;
      hadSocket = true;
    };
    ws.onmessage = (e) => {
      const msg = JSON.parse(e.data);
      if (msg.type === 'connected') {
        if (fixed && epoch !== null && msg.epoch !== epoch) lastSeq.clear();
        else if (fixed && pending) { /* send resume frames here */ }
        pending = false; epoch = msg.epoch;
        return;
      }
      const prev = lastSeq.get(msg.conversationId) || 0;
      if (msg.seq <= prev) return;
      lastSeq.set(msg.conversationId, msg.seq);
      onText(msg.text);
    };
    ws.onclose = () => { if (!stopped) setTimeout(open, 50); };
  };
  open();
  return { close: () => { stopped = true; ws.close(); } };
}

const got = [];
let server = boot(reply(20), 0);
const client = startClient((t) => got.push(t), process.argv[2] === 'fixed');
await new Promise((r) => setTimeout(r, 300));
for (const c of server.clients) c.terminate();   // restart
await new Promise((r) => server.close(r));
got.length = 0;
server = boot(REPLY_2, 200);
await new Promise((r) => setTimeout(r, 800));
client.close(); server.close();

assert.equal(got.join(''), REPLY_2.join(''),
  `dropped ${REPLY_2.length - got.length} of ${REPLY_2.length} chunks after restart`);
console.log('PASS: no chunk dropped across a restart');
```

When I ran it as written, it failed with `dropped 20 of 30 chunks after restart`. The client received `w20` through `w29` and nothing earlier. With `fixed` it passed.

Last, find where your client resumes. These are the usual places a reconnect hook lives:

```bash
grep -rnE "onopen|addEventListener\(['\"]open|\.on\(['\"](open|connect)['\"]|new EventSource" src/
```

`onopen` and `addEventListener('open'` cover browser WebSockets. `.on('open'` covers the Node `ws` library, and `.on('connect'` covers Socket.IO. A native `EventSource` sends `Last-Event-ID` on its own when it reconnects, before your code runs. If that's your stack, there's no client handler to fix, and the server check above is the whole defence. For everyone else: if the resume goes out from an open/connect handler, and you also have a `seq <= last` dedupe, then the next time your server restarts at the wrong moment, a user loses text and nothing reports an error.

---

Source: [Your stream resume fires before it knows the server restarted](https://blog.awe.run/your-stream-resume-fires-before-it-knows-the-server-restarted/) by Chad Priest, from Building awe in Public.
