Stage 3 · Build
HTTP, HTTP/2 & gRPC
WebSockets and Server-Sent Events
When to use streaming, upgrade handshake, and connection management.
WebSockets Overview
WebSockets provide a full-duplex, persistent connection between client and server. Unlike HTTP request-response, either side can send messages at any time. WebSockets are ideal for chat, real-time collaboration, live dashboards, and gaming.
| Feature | HTTP Polling | WebSocket | SSE |
|---|---|---|---|
| Direction | Client -> Server | Bidirectional | Server -> Client |
| Protocol | HTTP | ws:// or wss:// | HTTP |
| Data format | Any | Any (text/binary) | Text (UTF-8) |
| Connection | New per request | Persistent | Persistent |
| Reconnect | Manual | Manual | Automatic |
The Upgrade Handshake
WebSockets start as an HTTP connection. The client sends an Upgrade request, and if the server supports WebSockets, it responds with 101 Switching Protocols. After that, the connection is a raw WebSocket — no more HTTP.
Client Request:
GET /chat HTTP/1.1
Host: example.com
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==
Sec-WebSocket-Version: 13
Server Response:
HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=The Sec-WebSocket-Key is a random nonce. The server computes Sec-WebSocket-Accept using a specific SHA-1 hash. This prevents HTTP proxies from accidentally caching the WebSocket upgrade as a normal HTTP response.
# Install websocat
brew install websocat
# Connect to a WebSocket server
websocat ws://echo.websocket.org
# Connect with headers
websocat -H "Authorization: Bearer token" wss://example.com/ws
# Send a message
echo "Hello" | websocat ws://echo.websocket.orgwebsocat is a command-line WebSocket client. It is the curl of WebSockets — useful for testing, debugging, and scripting WebSocket connections.
Server-Sent Events (SSE)
SSE is a simpler alternative to WebSockets for server-to-client streaming. It uses a standard HTTP connection with Content-Type: text/event-stream. The server sends events as text lines. The browser automatically reconnects on disconnection.
HTTP/1.1 200 OK
Content-Type: text/event-stream
Cache-Control: no-cache
Connection: keep-alive
data: {"price": 42.50, "symbol": "AAPL"}
data: {"price": 42.55, "symbol": "AAPL"}
event: trade
data: {"price": 42.60, "symbol": "AAPL", "quantity": 100}
id: 12345
retry: 5000
data: {"price": 42.65, "symbol": "AAPL"}Each event is prefixed with 'data:'. Events can have an 'event' type, an 'id' for resumption, and a 'retry' interval. The browser's EventSource API handles reconnection and event parsing automatically.
Scaling WebSockets
WebSockets are stateful — the server maintains a persistent connection. This complicates scaling because you cannot randomly route requests. Sticky sessions or a pub/sub layer are required.
Sticky sessions:
Load balancer routes same client to same server
Simple but server failure drops all connections
Pub/Sub (Redis, NATS):
Each server publishes to a shared channel
Messages broadcast to all subscribers
Allows any server to send to any client
Connection registry:
Client connects to server A
Server A registers connection in Redis
To send to client, look up which server holds the connectionFor production WebSocket systems, a pub/sub layer is essential. When server A receives a message destined for a client connected to server B, it publishes to a channel that server B subscribes to. Redis Pub/Sub or NATS handle this well.
For many use cases (notifications, live feeds, dashboards), SSE is simpler and more reliable than WebSockets. It uses standard HTTP, works through proxies, reconnects automatically, and requires no special server framework. Consider SSE first.
Choosing the Right Protocol
Need bidirectional?
Yes -> WebSocket
No -> Continue
Need server -> client only?
Yes -> SSE (simple) or WebSocket (if you already use it)
No -> Continue
Need binary data?
Yes -> WebSocket
No -> SSE (text only)
Need to go through corporate proxies?
SSE (uses standard HTTP)
WebSocket (may be blocked)
Simple real-time feed?
SSE (built-in reconnect, simpler API)SSE is the right choice for 80% of real-time use cases. Use WebSocket only when you need bidirectional communication or binary data. The EventSource API is simpler and more robust than WebSocket's manual reconnection logic.
Mark this lesson complete to store local progress and unlock a cleaner resume path the next time you visit.