I'm trying to figure out the best way to handle message communication for two distinct use cases: one for receiving messages and another for sending messages. I don't require bidirectional communication, so each use case can be handled separately. My biggest concern is latency; I need the fastest possible message transfer since even a millisecond can make a difference in my application. Specifically, I'm curious: 1) Which method would be faster for receiving messages, websockets or server-sent events (SSE)? 2) What about for sending messages? I'm flexible with the method here, so if there's a better option out there, I'm open to suggestions. Additionally, are there other factors I should consider to optimize message speed?
5 Answers
For receiving events, SSE is generally faster because it’s optimized for that purpose. However, when it comes to sending messages, websockets are quicker since they maintain a persistent connection, reducing the need for new connections like in a traditional AJAX call. Just keep in mind that websockets have a bit of overhead due to the handshake process.
Factors like network hops, server processing times, TLS handshakes, and how you serialize/deserialize messages will impact your latency. You might want to look into using UDP for your socket communications if speed is key.
SSE works great for broadcasting messages from your backend, but if you have a lot of subscribers, it might slow down over time. If your use case requires users to send responses, then websockets are definitely the better choice.
Websockets are typically faster due to their underlying protocol and the persistent connection they create, which avoids the repeated overhead of setting up new connections. However, scaling is easier with SSE if that becomes important for your project.
It's true, but the overhead in websockets can also come from the package/frame handling. Doesn't that make SSE faster for certain scenarios?
If you really want the lowest latency, consider using WebRTC. It can significantly improve speed, especially if you can handle UDP traffic. Just make sure it fits your use case!

Could you clarify what you mean by emitting SSE events from your server?