WebSocket: Full-Duplex Bidirectional Communication
WebSocket creates a persistent bidirectional channel between client and server after an initial HTTP upgrade handshake. Both sides can send messages at any time without waiting for a request-response cycle. This makes WebSocket essential for use cases where the client frequently sends data to the server in real time — not just receives updates from it.
- Protocol independent of HTTP after the initial handshake
- Full-duplex: client and server send at any time without waiting
- Low latency: no HTTP overhead after connection is established
- Requires Socket.io or the ws library in Node.js
- Challenges: harder to load balance, requires sticky sessions or Redis Pub/Sub
- Binary support: can transmit binary data directly — useful for audio/video streaming
- Heartbeat mechanism: send ping frames periodically to detect dead connections
- Reconnection logic: client must implement reconnection on disconnect — Socket.io handles this automatically
Server-Sent Events: Simple and Reliable One-Way Broadcast
SSE is a one-way channel from server to client over a regular HTTP connection. The simplicity is its strength: it uses standard HTTP, so it works transparently with every proxy, load balancer, and CDN without special configuration. The browser's EventSource API handles automatic reconnection, making SSE robust by default.
- Regular HTTP 1.1: no new protocol, works with every proxy and load balancer
- Built-in browser auto-reconnect: if disconnected, reconnects automatically
- Text only: JSON added as text (sufficient for most cases)
- EventSource API in the browser — very simple
- Doesn't support client-to-server data — if you need that, use a regular HTTP POST
- Last-Event-ID header: browser sends this on reconnect — server can resume from last event
- Named events: EventSource supports different event types (progress, alert, message) on one connection
- HTTP/2 multiplexing: multiple SSE streams share one TCP connection on HTTP/2
Detailed Comparison
| Criterion | WebSocket | SSE |
|---|---|---|
| Direction | Bidirectional (client↔server) | Unidirectional (server→client) |
| Protocol | ws:// independent | Regular HTTP |
| Load Balancing | Needs sticky sessions | Easy — regular HTTP |
| Browser Support | Excellent | Excellent (except old IE) |
| Complexity | Higher | Much simpler |
| Best for | Chat, collaboration | Notifications, progress |
Use Cases in LMS Platforms: Which to Choose
The right choice for each real-time use case in an educational platform is determined by one question: does the client need to send real-time data to the server, or only receive it? Lesson completion, progress tracking, and instructor alerts are all server-to-client. Chat and live whiteboard are bidirectional. Map your features to this criterion before choosing a technology.
- SSE ✓: progress notifications (student completed lesson), teacher alerts, dashboard updates
- SSE ✓: streaming quiz results to students, content upload status updates
- SSE ✓: AI tutor streaming responses — tokens arrive progressively from server to client
- WebSocket ✓: interactive whiteboard for live classes, student-to-student chat
- WebSocket ✓: real-time document collaboration, screen sharing
- Recommendation: start with SSE — add WebSocket only when you genuinely need bidirectional
- Hybrid approach: SSE for server notifications + regular HTTP POST for client actions
- Long polling fallback: for environments where SSE is blocked by corporate firewalls
SSE Implementation in Node.js + React
SSE implementation is straightforward: the server sets the correct Content-Type header and writes events in the SSE format. The client uses the browser's built-in EventSource API. The most common production issues are authentication (EventSource doesn't support custom headers) and connection cleanup on unmount. Both have straightforward solutions.
- Server: res.setHeader('Content-Type', 'text/event-stream'); res.write(`data: ${JSON.stringify(event)}\n\n`);
- Client: const source = new EventSource('/api/events'); source.onmessage = (e) => { ... }
- Authentication: send token as query param (EventSource doesn't support custom headers)
- Keepalive: send a comment (: keepalive) every 30 seconds to prevent timeout
- Cleanup: source.close() on unmount to prevent memory leaks
- Error handling: source.onerror fires on disconnection — decide whether to reconnect manually
- Server cleanup: req.on('close') detects client disconnect — release resources immediately
- Encoding: always UTF-8 for SSE data — avoid non-UTF-8 content in event payloads
Scaling: Handling Thousands of Open Connections
Both SSE and WebSocket hold persistent connections, which requires different scaling consideration than stateless HTTP. Each connection consumes a file descriptor and memory. The key scaling mechanism for both is Redis Pub/Sub: each server process maintains its own connection registry and subscribes to Redis channels, forwarding messages to locally connected clients. This pattern scales horizontally to any number of server instances.
- SSE with Redis Pub/Sub: each server listens to Redis and publishes to its connected clients
- WebSocket with Socket.io + Redis Adapter: same principle — library abstracts the complexity
- Connection limits per process: an SSE connection consumes a file descriptor
- Nginx: increase worker_connections and add timeout for long SSE connections
- Rule: 10,000 concurrent SSE connections on a 2GB RAM server is possible with optimization
- ulimit -n: increase open file descriptor limit per process — default is often too low
- Connection backpressure: detect slow clients and close connections that can't keep up
- Dedicated SSE server: consider a lightweight SSE-only service for very high connection counts
The Decision Framework: SSE vs WebSocket
Use this framework to make the right choice for each real-time feature without over-engineering. The common mistake is defaulting to WebSocket because it feels more capable — but capability you do not need costs you in complexity, infrastructure, and debugging time. SSE's simplicity is a genuine advantage for most LMS real-time features.
- Start with this question: does the client send real-time data to the server?
- If no: use SSE — simpler, no sticky sessions, works behind any proxy
- If yes (chat, whiteboard, collaboration): use WebSocket with Socket.io
- Mixed features: SSE for notifications + standard HTTP for client actions — a valid hybrid
- High-volume streaming (AI tokens, video): SSE is purpose-built for this pattern
- Corporate environment: SSE survives HTTP proxies better — WebSocket can be blocked
- Testing: SSE is easier to test — it's just an HTTP endpoint that keeps the connection open
