Search code examples
spring-bootwebsocketserver-sent-events

Why is sse widely used even though there is a limit to the number of connections?


I created a New Year countdown service using SSE in spring framework.

The server sends the countdown time via an event stream, allowing all users accessing a specific link to see the same countdown clock.

However, I discovered that SSE has a limit on the number of connections. As a result, my service is limited to 6 users on HTTP/1 and 100 users on HTTP/2. This has led me to consider switching to WebSockets.

This raises a question: why would someone use SSE, which has a limit on the number of connections? Is there a way to make the number of connections effectively unlimited that I might not be aware of?


Solution

  • However, I discovered that SSE has a limit on the number of connections.

    There are two types of limit, and as you mention six as the limit, I think you are talking of the browser limit. This is an arbitrary limit, and can vary from browser to browser, and over time. If you hack and recompile your browser you could remove it.

    But don't do this. Instead design your application so a user only needs one connection, and all events are pushed over it. There is the event: xxx header your SSE server can send to distinguish different types of events. Or, if you are sending back a JSON message, you can simply use a field there to describe what type of event.

    I created a New Year countdown service

    My guess is you only expect a browser to only connect to this once. In which case the limit you might hit is not the 6 (or 100) one, but one on server resources: each SSE connection needs a dedicated TCP/IP socket.

    There is no particular limit, but web servers often define one to avoid denial of service attacks. Each socket also needs some memory, so there is a limit there, and there might also be an OS limit on the number of open sockets.

    Note: if you switch to websockets you still need a dedicated socket for each.

    To avoid the need for a socket per client, switch from a data push design to a data pull design. So have your clients poll every N seconds to get their update. Choose N based on the trade-off between how much load the server can take against allowable latency.

    Of course, for a countdown to a fixed point in time you don't need a server connection at all ;-)