Video in progress

A client drops for 20 seconds and reconnects. What do you design so the messages from that time aren't lost?

WebSocket itself doesn't store messages, so every message gets a monotonic seq within the channel, and messages are stored (DB, Redis Stream, Kafka). On reconnect the client says "the last one I saw was N", the server sends everything after N, then switches the client to the live stream.

📖 Answer

In a simple chat example:

  1. A message is first written to the database and gets a room_seq, and then it's broadcast over WebSocket.
  2. The client remembers the seq of every message it receives.
  3. On reconnect:
client.subscribe(`/user/queue/room.${roomId}`, onMessage);
client.publish({ destination: '/app/room.resume',
                 body: JSON.stringify({ roomId, afterSeq: lastSeq }) });
@MessageMapping("/room.resume")
@SendToUser(destinations = "/queue/room.resume", broadcast = false)
public List<ChatMessage> resume(ResumeRequest r, Principal p) {
    access.checkMember(p, r.roomId());
    return messageRepo.findByRoomAfter(r.roomId(), r.afterSeq(), PageRequest.of(0, 500));
}

The delicate part is the gap between "history" and the "live stream". If you fetch history first and subscribe afterward, a message in between can be lost. So the order is: subscribe first (buffering live messages), then request the history, then merge the two by seq and drop duplicates.

If the gap is very large (the client was offline for a day), it's better to cap it at 500 messages and leave "load more" to REST. You shouldn't flood WebSocket with 50,000 old messages.

In SSE the same mechanism is standardized with id: and Last-Event-ID; with WebSocket you build it yourself.