Skip to main content
PreparationZone Logo
PrepZone

WebSocket and Real-Time Communication

Persistent connections for chat, live feeds and notifications when polling is too slow.

Pass checkpoint below

Read these first

Polling vs push

AspectShort pollingWebSocket
ConnectionNew HTTP request every N secondsOne long-lived TCP connection
LatencyUp to poll interval (e.g. 5s)Sub-second server push
OverheadHigh — repeated headersLow after handshake
Server loadScales with poll frequency × usersStateful connections per user
  • Connection

    Short pollingNew HTTP request every N seconds
    WebSocketOne long-lived TCP connection
  • Latency

    Short pollingUp to poll interval (e.g. 5s)
    WebSocketSub-second server push
  • Overhead

    Short pollingHigh — repeated headers
    WebSocketLow after handshake
  • Server load

    Short pollingScales with poll frequency × users
    WebSocketStateful connections per user

Long polling and SSE sit between these extremes; WebSocket wins for bidirectional real-time.

WebSocket handshake

WebSockets start as HTTP, then upgrade:

Java
GET /ws/live/chat HTTP/1.1
Host: live.streamhub.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 101, both sides send framed messages — text or binary — without new HTTP requests.

Client
Serverpersistent socket
Clientreal-time update
One persistent connection replaces repeated HTTP round-trips.

Message protocol design

Define a schema so clients and servers agree on event types:

Java
// Client → server: join live room
{ "type": "join", "room_id": "live_v_9182", "token": "eyJ..." }

// Server → client: viewer count update
{ "type": "viewer_count", "room_id": "live_v_9182", "count": 48291 }

// Server → client: new chat message
{ "type": "chat", "user": "creator_42", "text": "Thanks for watching!", "ts": 1712001234 }

Use JSON for readability in early products; protobuf or MessagePack at extreme scale.

The rest of this guide is part of Pro

Free covers every fresher guide in full. Pro unlocks Senior, Staff and Architect guides across every track.

Still to come · 4 sections

  • Scaling WebSocket servers
  • StreamHub live features
  • Alternatives worth mentioning
  • Reliability concerns

Test yourself

Answer these before moving on — recall is what makes it stick.