Video in progress

When an SSE connection drops, how does EventSource reconnect, and what is Last-Event-ID for?

If the connection drops, EventSource reconnects automatically and sends the id of the last event it received in the Last-Event-ID header. The server can use that value to resend the events that were missed, but the server has to do that itself; it isn't automatic.

📖 Answer

The server gives every event an id:

emitter.send(SseEmitter.event()
        .id(String.valueOf(event.getSeq()))
        .name("notification")
        .reconnectTime(5_000)   // how many ms the client waits before reconnecting
        .data(event));

On reconnect the browser sends this by itself:

GET /api/notifications/stream
Last-Event-ID: 1842

On the server side:

@GetMapping(value = "/stream", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
public SseEmitter stream(@RequestHeader(value = "Last-Event-ID", required = false) Long lastId) {
    SseEmitter emitter = register();
    if (lastId != null) {
        repository.findAfter(lastId).forEach(e -> sendQuietly(emitter, e));
    }
    return emitter;
}

A trap: if events live only in memory (say they're broadcast and stored nowhere), a client that reconnects still loses the messages in between. The id only says where to resume; it doesn't keep the data.

One more nuance: if the server returns 204 No Content, EventSource stops reconnecting. That's how you say "no longer needed".