Topic 6.5
WebSocket
In one line
A persistent, bidirectional, message-oriented connection for low-latency push — chat, live cursors, trading feeds.
Think of it like this
A phone call, once connected, either person can speak whenever they want without hanging up and redialing. This is different from calling someone, saying one thing, and hanging up (that's traditional HTTP).
Key ideas
- 01
Upgrade dance: HTTP GET with Upgrade: websocket → 101 Switching Protocols → both sides keep one TCP socket open.
- 02
Server can push unsolicited — the reason it beats short polling for real-time UI.
- 03
Frames are lightweight; ordering guaranteed per-connection (TCP underneath).
- 04
Operational cost: connections are stateful — load balancing must be sticky (or LB-aware), connection counts drive memory.
- 05
At HLD scale, one WebSocket per user accumulates on a fleet of gateway nodes behind a load balancer.
- 06
Fallbacks: if the corporate proxy blocks websockets, SSE or long-poll degrade gracefully — design the fallback.
Java / Spring map
- →
Spring WebSocket + STOMP; SockJS fallback; javax.websocket (Jakarta).
Code & diagrams
One HTTP request 'upgrades' into a completely different kind of connection that stays open.
Explain without notes
Why is a WebSocket server 'stateful' from a load balancer's point of view — and what breaks?
Practice
Design the chat flow: connect (handshake + auth via token), join room, receive broadcast, reconnect with resume.
Trade-offs
- ↔
Persistent sockets = great push, but memory per socket and sticky LB complicate scaling.
Run it in production
You've designed it. Now build, operate, and break the same idea hands-on in the DevOps courses:
Completion checklist
I can contrast WebSocket vs polling vs SSE on latency and server cost.