SDSystem DesignConcepts to case studies
System DesignDSA
x
0/311
Part 1: Foundations
Part 2: APIs and Communication
  • Long Polling
  • Server-Sent Events (SSE)
  • WebSockets
  • Webhooks
  • WebRTC
  • Short Polling
  • Push Notifications
  • MQTT
Part 3: Caching
Part 4: Data and Storage
Part 5: Architecture
Part 6: Distributed Systems
Part 7: Advanced Data Topics
Part 8: Operations and Security
Part 9: Estimation and Interview Method
Part 10: Case Studies
System Design/APIs and Communication/Real-Time Communication

WebSockets

A two-way phone call between browser and server.

โฑ 14 min readIntermediateMust KnowInterview FavouriteHas visualizer
SummaryConceptReal-Life ExampleWhy?Where?How It WorksStepsKey TermsPros & ConsMistakesReal WorldRead NextInterview Q&ACheat-Sheet

01Quick Summary

A WebSocket is a two-way connection between a browser and a server that stays open. Either side can send a message at any time, with no new request.

  • It starts as a normal HTTP request, then โ€œupgradesโ€ to the WebSocket protocol.
  • Messages are small and cheap, so it is great for chat, games, live editing and trading screens.
  • The server must remember every open connection. That makes scaling harder than normal HTTP.

02Concept: What is it?

With HTTP, the browser must ask first, every time. A WebSocket removes that rule. After one handshake, the pipe stays open and both sides can talk freely.

HTTP vs WebSocket
HTTP
๐Ÿ“ฑClient
โ†“request
๐Ÿ–ฅ๏ธServer
โ†‘response (then closed)
Server cannot speak first.
WebSocket
๐Ÿ“ฑClient
โ†•messages, any time, both ways
๐Ÿ–ฅ๏ธServer
Connection stays open.
Request / response Open two-way line
HTTP: a new question for every answer. WebSocket: one open line, both ways.
๐Ÿง Remember
The URL starts with ws:// (plain) or wss:// (encrypted with TLS). Always use wss:// on the real internet.

03Real-Life Example

๐ŸตThe phone call
HTTP is sending letters. You write, wait for a reply, write again. WebSocket is a phone call. You dial once (the handshake). Then both of you can speak at any time, until someone hangs up.
Phone call
WebSocket
Dialling the number
HTTP request with Upgrade header
โ€œHello, I can hear youโ€œ
101 Switching Protocols
Talking, both ways
Messages (frames) in both directions
โ€œAre you still there?โ€œ
Ping and pong
Hanging up
Close frame
Operator holds a line for each caller
Server keeps each connection in memory
A chat app
๐Ÿ‘ฉAsha
โ†’โ†“'Hi!'
๐Ÿ–ฅ๏ธChat serverholds both connections
โ†’โ†“'Hi!' pushed
๐Ÿ‘จRavi
Asha sends once. The server pushes it to Ravi right away.

04Why Do We Need It?

Some products need fast, frequent, two-way messages. HTTP is too slow and heavy for them:

๐ŸชถSmall messages
After the handshake, a message has only 2 to 14 bytes of extra header. HTTP repeats hundreds of bytes every time.
โšกLow delay
No new connection, no new request. A message goes out at once.
โ†”๏ธBoth ways
The server can push without being asked.
๐Ÿ“ฆText and binary
Send JSON, images, audio chunks or game data.
๐Ÿ”Many messages per second
Fine for typing indicators, cursors and games.
๐ŸงฉFewer hacks
No polling loops, no held requests.
Use WebSockets when both sides talk often and speed matters.

05Where Do We Use It?

๐Ÿ’ฌChat apps
Messages, typing indicators, read receipts.
๐ŸŽฎOnline games
Player moves and game state many times a second.
๐Ÿ“Shared editing
Several people edit one document at the same time.
๐Ÿ“ˆTrading screens
Live prices and order updates.
๐Ÿ“Live location
A cab moving on a map.
๐Ÿ””Live dashboards
Two-way control panels, IoT devices.

06Types / Parts / How It Works

Step 1: the handshake

Press Next to see how a normal HTTP connection becomes a WebSocket.

Handshake in 3 lines
๐Ÿ“ฑClientGET + Upgrade: websocket
โ†’โ†“1. please upgrade
๐Ÿ–ฅ๏ธServer
โ†2. 101 Switching Protocols
๐Ÿ“ฑOpen line3. messages both ways

Step 2: messages (frames)

  • Text frame: a string, usually JSON.
  • Binary frame: raw bytes.
  • Ping / Pong: a heartbeat to check the other side is alive.
  • Close: a polite goodbye with a status code (1000 means normal).

Client code

JavaScript (browser)
const ws = new WebSocket("wss://chat.example.com/chat");

ws.onopen    = () => ws.send(JSON.stringify({ type: "hello", user: "asha" }));
ws.onmessage = (e) => show(JSON.parse(e.data));
ws.onclose   = () => reconnectWithBackoff();   // YOU must write this
ws.onerror   = (e) => console.log("socket error", e);
๐Ÿ“No auto-reconnect
Unlike SSE, the browser does not reconnect or resume a WebSocket for you. You write that logic (with backoff and a way to ask for missed messages).
VisualizerThe upgrade handshakeStep through how HTTP becomes a WebSocket, and what the heartbeat does.
๐Ÿ“ฑBrowser
โ†”nothing open
๐Ÿ–ฅ๏ธServer
Step 1 of 5
Before: no connection
A normal website uses HTTP: the browser asks, the server answers, and the conversation ends. The server cannot start a chat by itself.
VisualizerTwo clients chatting through one serverSend messages, disconnect a user, and compare with plain HTTP.
How do they talk?
๐Ÿ‘ฉAshaconnected
โ†”open socket
๐Ÿ–ฅ๏ธServer2 open connections
โ†”open socket
๐Ÿ‘จRaviconnected
Message log
  • ServerAsha and Ravi are connected.
Open connections
2
held by the server
Messages sent
0
HTTP requests used
0
2 per message
With a WebSocket the server remembers each open connection. A message from Asha goes straight to Ravi. Try disconnecting Ravi, then send from Asha.

07How to Use It / Steps / Implementation

Using WebSockets in a real system

  1. 1
    Authenticate on connect
    Check a cookie or short-lived token during the handshake. Do not trust later messages blindly.
  2. 2
    Define a message format
    For example { type, id, payload }. Version it so you can change it later.
  3. 3
    Send heartbeats
    Ping every 20 to 30 seconds. Close and reconnect if no pong arrives.
  4. 4
    Reconnect with backoff and jitter
    Wait 1 s, 2 s, 4 s... plus a random bit, so a restart does not cause a stampede.
  5. 5
    Catch up after reconnecting
    Send the last message id you saw. The server replays what you missed.
  6. 6
    Limit and validate
    Cap message size, rate-limit senders, and validate every message.

Scaling stateful connections

A WebSocket server remembers its connections. If Asha is connected to Server A and Ravi to Server B, Server A cannot reach Ravi directly. The common answer (general idea):

Scaling WebSockets
๐Ÿ‘ฉAsha
๐Ÿ‘จRavi
โ†’โ†“wss://
โš–๏ธLoad balancerlong timeouts, sticky if needed
โ†’โ†“
WebSocket servers
๐Ÿ–ฅ๏ธServer AAsha
๐Ÿ–ฅ๏ธServer BRavi
โ†”publish / subscribe
๐Ÿ“ฃPub/sub (Redis, Kafka...)
Balancer Servers Message bus
  • Pub/sub fan-out: Server A publishes Asha's message. Server B is subscribed and pushes it to Ravi.
  • Sticky sessions: keep the same client on the same server, mainly during the handshake or with older fallbacks.
  • Connection limits: each open socket uses memory and a file descriptor. One server can hold many thousands, but you must tune and test it.
  • Deploys: closing a server drops all its users. Drain gradually and let clients reconnect with jitter.

08Key Terms to Know

TermMeaning in easy words
WebSocketA two-way connection that stays open between client and server
HandshakeThe HTTP request and 101 reply that start the WebSocket
Upgrade headerTells the server the client wants to switch protocol
101 Switching ProtocolsThe server's yes to the upgrade
ws:// and wss://Plain and TLS-encrypted WebSocket URLs
FrameOne piece of a WebSocket message
Ping / PongSmall heartbeat messages to check the connection is alive
Sticky sessionSending a user to the same server every time
Fan-outDelivering one message to many connected users
BackpressureA slow reader that cannot keep up with a fast sender
SubprotocolAn agreed message format on top of WebSocket (for example STOMP)

09Pros, Cons and Trade-offs

โœ… Pros
  • True two-way, low-delay messaging
  • Very small overhead per message
  • Text and binary data
  • No polling loops
  • Great for games, chat and live collaboration
โš ๏ธ Cons
  • The server holds state for every connection, which makes scaling and deploys harder
  • No built-in reconnect, resume or message ids
  • Some proxies, firewalls and old networks block or time out WebSockets
  • Harder to debug, cache, and rate-limit than normal HTTP
  • Security needs care: authentication, origin checks, input validation

Which real-time tool?

Long pollingSSEWebSockets
DirectionServer to clientServer to clientBoth ways
DataAnything over HTTPTextText + binary
ReconnectDIYBuilt inDIY
Overhead per messageHighLowLowest
Scales howMany held requestsMany held responsesStateful connections + pub/sub
Best forFallbackOne-way feedsChat, games, collaboration

10Common Problems and Mistakes

Common mistakes

  1. No heartbeat. A silent dead connection looks alive for minutes. Use ping and pong.
  2. No reconnect plan. Mobile networks drop all the time. Add backoff, jitter and catch-up.
  3. Using WebSockets for everything. If only the server talks, SSE is simpler. For normal request and response, use HTTP.
  4. Trusting the client. Validate every message. Check the user is allowed to do that action.
  5. Skipping the Origin check. Another website can open a socket to your server using your user's cookies (cross-site WebSocket hijacking).
  6. No limits. Huge messages or message floods can crash a server. Set size and rate limits.
  7. Ignoring slow clients. A reader that cannot keep up fills memory. Drop or close it.
  8. Plain ws:// in production. Always wss://.
๐ŸงฏThundering herd
A server restart drops 100,000 sockets and they all reconnect at once. Use jitter and gradual drain.
๐Ÿ”€Messages out of sync
After a reconnect the client missed events. Use message ids and a catch-up request.

11Real-World Examples

๐Ÿ’ฌChat and messaging
Web chat apps use WebSockets for live messages and typing signals (general idea).
๐Ÿ“Collaborative documents
Live cursors and edits are sent as small messages.
๐ŸŽฎBrowser games
Position updates many times a second.
๐Ÿ“ˆMarket data
Exchanges and crypto sites stream prices over WebSocket APIs.
Choose WebSockets when...
  • Both sides send often
  • You need very low delay
  • You send binary data
  • You can build reconnect and scaling
Choose something simpler when...
  • Only the server talks: use SSE
  • Updates are rare: use long polling or webhooks
  • Plain request and response: use HTTP

12Related Topics to Read Next

Server-Sent Events (SSE)โ†’

A simpler one-way option with automatic reconnect.

Long Pollingโ†’

The most compatible fallback.

WebRTCโ†’

Direct peer-to-peer media and data, often using WebSockets to set up.

HTTP / HTTPSโ†’

The handshake starts as HTTP.

Pub/Subโ†’

How many servers deliver one message to the right users.

What are Load Balancers?โ†’

They need long timeouts and care with stateful connections.

13Interview Questions with Short Answers

14Quick Revision Cheat-Sheet

  • โœ”What: a two-way connection that stays open after an HTTP upgrade.
  • โœ”Handshake: GET with Upgrade: websocket, then 101 Switching Protocols.
  • โœ”URLs: ws:// and wss://. Always use wss:// in production.
  • โœ”You must build: heartbeats, reconnect with backoff and jitter, catch-up, limits.
  • โœ”Scale with: pub/sub fan-out, long timeouts, connection tuning, gradual drains.
  • โœ”Pick it for: chat, games, shared editing, live trading. Not for simple one-way feeds.
  • โœ”One line: โ€œA WebSocket is a phone call between browser and server.โ€
โ† Previous
Server-Sent Events (SSE)
Next โ†’
Webhooks