Theory
Server-Sent Events (SSE)
📋 Overview
Server-Sent Events (SSE) is a standard allowing servers to push real-time data to web pages over a single, long-lived HTTP connection. Unlike WebSockets, which offer full-duplex communication, SSE is unidirectional (Server-to-Client), making it highly efficient for scenarios where the client primarily consumes updates.
🏗️ Core Principles & Characteristics
- One-Way Data Flow: Data travels exclusively from the server to the client.
- HTTP Based: Uses standard HTTP protocols, meaning it works through most firewalls and proxies without special configuration.
- Text-Stream Format: Data is transmitted as a stream of
text/event-streamencoded messages. - Automatic Reconnection: Browsers natively handle reconnections if the stream is interrupted, with support for tracking the last event ID to prevent data loss.
- Lightweight: Lower overhead than WebSockets as it doesn't require a protocol upgrade handshake.
⚖️ Trade-offs: Pros & Cons
Pros
- Simplicity: Extremely easy to implement on both server and client (native
EventSourceAPI). - Efficiency: Low battery and CPU usage on mobile devices compared to long-polling.
- Resilience: Built-in retry logic and event ID tracking.
- Firewall Friendly: Since it's just HTTP, it rarely gets blocked by corporate filters.
Cons
- Unidirectional: Cannot send data from client to server over the same connection (requires separate AJAX/Fetch calls).
- Connection Limits: Browsers often limit the number of concurrent SSE connections to the same domain (usually 6), which can be an issue without HTTP/2.
- Text Only: Primarily designed for UTF-8 text data; binary data requires Base64 encoding, increasing payload size.
🌍 Real-World Implementation
- Social Media Feeds: Pushing new posts or notifications to a user's timeline.
- Financial Dashboards: Real-time stock tickers and currency exchange rates.
- Live Sports Scores: Updating match progress and scores instantly.
- Monitoring Tools: Streaming server logs or infrastructure health metrics to a devops dashboard.
💡 Interview "Gotchas" & Tips
- SSE vs. WebSockets: The most common question. Use SSE for one-way updates (notifications, tickers) and WebSockets for interactive apps (chat, gaming).
- HTTP/2 is Key: Mention that HTTP/2 eliminates the 6-connection limit per domain, making SSE much more scalable for modern web apps.
- Last-Event-ID: Explain how the
Last-Event-IDheader allows the server to resume the stream from exactly where it left off after a reconnection.
📐 Suggested Architecture Primitives
- EventSource API: The standard browser interface for consuming SSE.
- Pub/Sub Broker: (e.g., Redis Pub/Sub) To broadcast messages from backend services to the SSE handler.
- Load Balancer Sticky Sessions: Often required if using SSE without a shared state backend, though less critical with a proper Pub/Sub architecture.
text/event-streamMIME Type: The essential header for establishing the persistent stream.
Canvas