๐ ๐ฅ๐ฒ๐ฎ๐น-๐ง๐ถ๐บ๐ฒ ๐๐ฒ๐ฎ๐๐๐ฟ๐ฒ ๐ ๐๐๐ถ๐น๐ ๐ง๐๐ถ๐ฐ๐ฒ
I built the same feature two times.
The first time, I used WebSockets. I wanted a dashboard to update without a page refresh. I followed the common advice. WebSockets are the standard for real-time updates.
But WebSockets required a lot of extra work. I had to write code for:
- Reconnection logic with backoff and jitter.
- Heartbeat pings to check if the connection stayed alive.
- Complex authentication because you cannot easily set headers.
It worked, but it felt fragile.
Then I found EventSource.
EventSource is much simpler. The server keeps an HTTP response open. The browser treats it as a stream of events.
The browser handles the hard parts for me:
- It reconnects automatically if the connection drops.
- It tracks the last event ID so you do not lose data.
- It uses standard cookies for authentication.
My hundreds of lines of WebSocket code became five lines of code.
I learned a hard lesson about choosing tools. Before you start, ask yourself one question:
Which direction is the data flowing?
If the server only needs to send updates to the client, do not use WebSockets. WebSockets are for two-way communication like chat apps or multiplayer games.
If you only need one-way updates like notifications or logs, use EventSource.
Stop building complex systems for simple problems. Spend ten minutes thinking about your data flow before you write a single line of code.
Source: https://dev.to/dip_032d2fe1959e1990ddbb1/a-real-time-feature-i-built-twice-4l6d