"WebSocket is not REST's replacement. It's the answer to one specific question REST can't answer well: 'I need both sides to send messages at any time.' Knowing where that line falls keeps you from over-engineering and from under-engineering."
The Spectrum from REST to WebSocket
From least to most real-time:
- REST request/response — client asks, server answers, done. Best for CRUD and ad-hoc queries.
- Polling — REST repeated. Tolerable latency, simple.
- Long-polling — REST that holds the response. Lower latency, more server cost per pending client.
- SSE — one-way streaming over HTTP. Server pushes; client receives. AI tokens, notifications, real-time logs.
- WebSocket — full-duplex persistent connection. Both sides send messages at any time, independent of each other.
Each step trades simplicity for capability. WebSocket is the most capable AND the most expensive operationally — choose it when you actually need it.
The Three Tests for Choosing WebSocket
1. Bidirectionality. Does the CLIENT also need to push messages to the server in real-time, beyond regular requests? Chat "is typing..." indicators, multiplayer game inputs, collaborative cursor positions — yes. AI chat (user sends one message, server streams a response, repeat) — no, SSE plus normal POST suffices.
2. Latency budget. Is your acceptable end-to-end latency below ~100ms? Trading platforms, live cursor tracking — yes. Most chat UI — no, SSE + POST is fine.
3. Message frequency. Are you sending many small messages per second per client? Game state updates at 30Hz — yes. Notifications a few per minute — no, SSE wins.
If you can answer NO to all three, REST + SSE is almost always the right choice. If you answer YES to any one, WebSocket starts looking attractive.
How WebSocket Sets Up Over HTTP
A WebSocket connection starts as a normal HTTP/1.1 request with an upgrade header. The server, if willing, responds with 101 Switching Protocols, after which the underlying TCP connection becomes a WebSocket frame stream:
GET /ws/chat HTTP/1.1
Host: example.com
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==
Sec-WebSocket-Version: 13
HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=
After the 101, both sides exchange WebSocket frames — small binary headers + payload. The connection stays open until either side closes it.
The Common Hybrid
Many production apps use both REST and WebSocket: REST for state management and queries (login, fetch history, save a draft), WebSocket for the live channel (chat messages, live edits, presence). The state and history live in REST-accessible resources; the WebSocket carries the events that mutate them. Each side updates the REST view; the WebSocket announces what changed for everyone listening.