Skip to content

WebSockets

A protocol that provides persistent, full-duplex communication between client and server over a single TCP connection.

  • Normal HTTP — client always initiates, server can't push.
  • WebSocket — both sides can send anytime.

HTTP vs WebSocket

HTTP (request-response):

Client --- request ---> Server
Client <-- response --- Server
(connection closes)

WebSocket (persistent):

Client <===> Server (both send anytime, connection stays open)

WebSocket Handshake

Starts as HTTP, then upgrades:

Client --- HTTP GET /chat
           Upgrade: websocket
           Connection: Upgrade

Server --- 101 Switching Protocols
           Upgrade: websocket

Now it's a WebSocket connection ✓

Uses HTTP only for the initial handshake — after that it's raw TCP frames.

Full Duplex vs Half Duplex

DirectionExample
SimplexOne way only — TV broadcast
Half DuplexBoth ways, not simultaneously — walkie talkie
Full DuplexBoth ways simultaneously — phone call, WebSocket

WebSocket vs Alternatives

WebSocketHTTP PollingSSE
DirectionFull duplexClient onlyServer → Client only
ConnectionPersistentNew each timePersistent
OverheadLowHighLow
Use caseChat, gamingSimple updatesLive feed, notifications
  • HTTP Polling — client asks server every X seconds "anything new?" — wasteful.
  • SSE (Server Sent Events) — server pushes to client only, simpler than WS, good for notifications/feeds.

Use Cases

  • Real-time chat (WhatsApp Web)
  • Multiplayer games
  • Collaborative editing (Google Docs)
  • Live stock/crypto prices
  • Live sports scores

Key Concepts

Heartbeat / Ping-Pong

  • Both sides send periodic pings to keep connection alive.
  • If no response → connection is dead, reconnect.

Reconnection

  • Network drops → client must reconnect manually.
  • Libraries like socket.io handle this automatically.

Scaling WebSockets

  • Problem — connections are stateful, sticky to one server.
  • Solution — Redis Pub/Sub to broadcast messages across multiple servers.
Server 1 (user A connected)
Server 2 (user B connected)

A sends message → Server 1 → Redis → Server 2 → B

socket.io vs Raw WebSocket

  • socket.io — fallback to polling if WS not supported, rooms, reconnection built in.
  • Raw WebSocket — lighter, standard, no extra features.