Context:
I’m developing a dashboard using ExpressJS and HTML that utilizes Server-Sent Events (SSE) for data streaming. Each time a page is opened, a new EventSource object is created. However, I’ve noticed that when the number of EventSource instances reaches 6, the application freezes.
Simplified Client-Side:
const eventSource = new EventSource("/api/data/stream/last");
eventSource.onmessage = function (event) {
const type = event.type;
const data = JSON.parse(event.data);
console.log("Received ", type, ": ", data);
};
eventSource.onerror = function (error) {
console.error("EventSource failed:", error);
};
Simplified Server-Side:
router.get("/all", function (req, res) {
/* Set response headers for Server-Sent Events */
res.setHeader("Content-Type", "text/event-stream");
res.setHeader("Cache-Control", "no-cache");
res.setHeader("Connection", "keep-alive");
/* Send all data */
sendData(err, res, data);
/* Handle client connection close event */
req.on("close", () => {
res.end();
});
});
Issue:
When I open multiple instances of this dashboard in different browser tabs or windows, everything works fine until I reach 6 open instances. At that point, the application freezes.
Possible Cause:
I suspect the issue is related to the way EventSource objects initiate new HTTP sessions and open new TCP/IP sockets. Since SSE keeps the connection open to push data from the server continuously, each socket remains active. Most web browsers have an upper limit on the number of simultaneous active HTTP/1 connections to the same server, which is typically in the range of 4 to 6 according to RFC 2616. This might be why my application freezes when reaching the 6th connection.
Questions:
-
How can I manage multiple SSE connections more efficiently to prevent the application from freezing?
-
Is there a way to increase the maximum number of simultaneous connections in modern browsers?
-
Are there alternative approaches to achieve real-time data streaming in this context without hitting these limits?
Any suggestions or solutions would be greatly appreciated!