Server-Sent Events
Problem
Applications that need real-time updates often resort to polling, repeatedly asking the server for new data at fixed intervals. This wastes bandwidth, increases server load, and introduces latency since updates only arrive when the next poll happens. For one-way data streams like live notifications or stock prices, polling is inefficient compared to having the server push updates as they occur.
Solution
Stream updates from server to client over a persistent connection. This enables real-time updates with simpler infrastructure than WebSockets.
Example
This demonstrates using Server-Sent Events to receive real-time updates from the server over a persistent HTTP connection, providing a simpler alternative to WebSockets for one-way data streaming.
// Establish persistent connection to server event stream
const eventSource = new EventSource('/api/events');
// Handle incoming messages from server
eventSource.onmessage = (event) => {
const data = JSON.parse(event.data);
updateUI(data); // Update UI with new data
};
// Handle connection errors and cleanup
eventSource.onerror = () => {
eventSource.close(); // Close connection on error
};
Benefits
- Provides real-time updates without polling overhead.
- Simpler than WebSockets for one-way server-to-client communication.
- Works over standard HTTP/HTTPS, making it firewall-friendly.
- Automatically reconnects on connection loss.
Tradeoffs
- Only supports server-to-client communication, not bidirectional.
- Requires holding connections open, which can strain server resources.
- May not work through some corporate proxies or firewalls.
- Browser limits on concurrent connections can be restrictive.