"Make it real-time" is a common PM request. But "real-time" isn't a single technology; it's a spectrum of trade-offs. Should you open a persistent WebSocket? Is Long Polling good enough? What about Server-Sent Events (SSE)?
1. Short Polling (The "Are We There Yet?" Approach)
The client asks the server every X seconds: "Any new data?"
- →Pros: Dead simple. Works on every server.
- →Cons: Wasteful. 99% of requests return "no change." High load on the database.
2. Long Polling
The client asks "Any data?", and the server hangs until data arrives (or timeouts).
- →Pros: Near real-time latency.
- →Cons: Still requires re-establishing connections constantly.
3. WebSockets (The Two-Way Highway)
A persistent, bidirectional TCP connection.
- →Pros: Lowest latency. True full-duplex (server can push, client can push).
- →Cons: Stateful. Scaling WebSockets is hard because you need "sticky sessions" or a Pub/Sub backplane (like Redis) to route messages across server instances.
4. Server-Sent Events (SSE)
Standard HTTP connection where the server streams data to the client.
- →Pros: Native browser support (EventSource). Auto-reconnection. Simple HTTP.
- →Cons: Unidirectional (Server -> Client only).
Decision Matrix
- →Chat App / Game: WebSockets. You need high-frequency, bidirectional state.
- →Stock Ticker / Sports Score: SSE. Use data flows one way.
- →Email Inbox: Long Polling (or just Short Polling). A 30s delay is acceptable.
- →Notification Feed: SSE or WebSockets depending on scale.
Conclusion
Don't reach for WebSockets by default. They introduce stateful complexity to your backend. If your data only flows one way (Server -> Client), SSE is drastically simpler and more firewall-friendly. Use the right tool for the right latency requirement.