Search code examples
javascriptserver-sent-eventseventsource

Some of Server Sent events lost while EventSource reconnecting


In our application we have SSE connection with living time 5 minutes, after 5 minutes server closes the connection and client reconnect automatically.

But here the problem: while client reconnecting, there might some event happened on backend and it will not be passed to SSE connection, because it’s not established yet.

So there are some time slots 1-2sec when we may loose events.

How we can handle this case ? What is your opinion ?

From my vision we only have one choice: after every SSE reconnect do additional GET requests on server to refresh data.


Solution

  • This is exactly what the Last-Event-ID HTTP header in the SSE protocol is designed for.

    On the server side you should look for that header when you get a new connection. If it is set, stream the missing data gap to them, immediately. And you should set the id header for each message you push out, to some unique identifier.

    On the client side, for your particular use case, you do not need to do anything: when SSE reconnect runs it sends that header automatically, using the id of the last data it had received.

    In chapter 5 of my book Data Push Apps with HTML5 SSE, I argue you should also include that same unique id, explcitly, in the JSON data packet you push out, and you should support the Last-Event-ID being given as a POST/GET argument as well. This gives you the flexibility to work with the long-polling alternative approaches to SSE, and also means it can work if the reconnect came from the client-side rather than the server-side. (The former would be for supporting older browsers, though that matter less and less as IE dies out; the latter would be needed if you implement your own keep-alive mechanism.)