WebSocket
A protocol for full-duplex communication over a single TCP connection. Unlike HTTP, the server can push data to the client without being asked.
What is WebSocket?
In short
A WebSocket is a protocol that opens a single, long-lived TCP connection between a browser and a server and keeps it open so both sides can send messages at any time. Unlike a normal HTTP request where the client always asks first, a WebSocket lets the server push data to the client the instant something happens, which is why it powers chat, live scores, trading tickers, and multiplayer apps.
What a WebSocket actually is
Standard HTTP works in one direction at a time. The browser sends a request, the server sends a response, and the connection is done. If you want fresh data you have to ask again. That model is fine for loading a page, but it falls apart when the server is the one with news to share, like a new chat message or a stock price tick.
A WebSocket fixes this by upgrading a normal HTTP connection into a persistent, two-way channel. Once it is open, either side can send a message whenever it wants without starting a new request. This is called full-duplex communication, the same way a phone call lets both people talk at once instead of mailing letters back and forth.
The protocol is defined in RFC 6455 and uses the ws:// scheme for plain connections and wss:// for encrypted ones over TLS. It runs over the same ports as the web, 80 and 443, so it passes through most firewalls and proxies that already allow web traffic.
How it works under the hood
Every WebSocket starts life as an ordinary HTTP request. The browser sends a GET with the header Upgrade: websocket and Connection: Upgrade, plus a random Sec-WebSocket-Key. If the server agrees, it replies with status 101 Switching Protocols and a hashed Sec-WebSocket-Accept value that proves it understood the request. This exchange is called the handshake.
After the 101 response, the connection stops speaking HTTP. The same TCP socket now carries lightweight WebSocket frames. Each frame has only a few bytes of overhead compared to the hundreds of bytes of headers a fresh HTTP request would need, so high-frequency updates stay cheap.
Frames can carry text (usually JSON) or binary data, and there are control frames for ping, pong, and close. The ping and pong frames act as a heartbeat so each side can tell the connection is still alive and clean up dead sockets. To detect broken connections faster, servers commonly send a ping every 20 to 30 seconds.
On the server you are now holding one open connection per client. A server keeping 100,000 live chat users connected is holding 100,000 sockets in memory, which is a very different scaling shape from stateless HTTP where connections come and go in milliseconds.
When to use it and the trade-offs
Reach for WebSockets when the server needs to push data without being asked and updates are frequent: chat, collaborative editing, live dashboards, multiplayer games, and trading feeds. They beat the old trick of polling, where the client asks every few seconds and mostly gets back nothing, which wastes requests and adds delay.
The cost is that connections are stateful. A crashed server drops every socket it was holding, and load balancers must be configured for sticky sessions or for proxying the upgrade, since a connection is pinned to one backend. Scaling out means a shared layer like Redis pub/sub so a message arriving on server A reaches a user connected to server B.
If the data only flows one way, server to client, Server-Sent Events (SSE) are simpler because they run over plain HTTP and reconnect automatically. If updates are rare, ordinary polling or a request when the user acts is cheaper than holding an idle socket open. Use WebSockets when you genuinely need low-latency two-way traffic, not by default.
A concrete example
Picture a live football score page. With polling, the browser hits the server every 5 seconds asking has the score changed, and 99 percent of the time the answer is no. That is thousands of wasted requests and a goal might still show up to 5 seconds late.
With a WebSocket, the browser opens one connection when the page loads and then waits. The moment a goal is scored, the server pushes a single small frame like {"home":2,"away":1} to every connected viewer at once. Latency drops to tens of milliseconds and the server does almost no work while nothing is happening.
Slack works the same way for messages, Figma uses the pattern to sync cursors and edits between collaborators in real time, and trading platforms stream price ticks this way. In each case the value comes from the server being able to speak first.
Where it is used in production
Slack
Keeps a WebSocket open to each client so new messages, typing indicators, and presence updates appear instantly without refreshing.
Figma
Streams cursor positions and document edits over WebSockets so multiple designers see each other's changes in the same file live.
Binance
Exposes public WebSocket streams that push order book and trade ticks to clients in real time instead of making them poll the REST API.
Discord
Uses a persistent WebSocket gateway to deliver messages, voice state, and notifications to millions of concurrently connected users.
Frequently asked questions
- What is the difference between WebSocket and HTTP?
- HTTP is request-response: the client always asks first and the connection closes after the reply. A WebSocket starts as an HTTP request but upgrades into one long-lived connection where both the client and server can send messages at any time, so the server can push data without being asked.
- Is WebSocket better than polling?
- For frequent real-time updates, yes. Polling makes the client ask repeatedly and usually get nothing back, which wastes requests and adds delay. A WebSocket pushes data the instant it changes over a single connection. But if updates are rare, simple polling can be cheaper because you are not holding an idle connection open.
- When should I use Server-Sent Events instead of WebSockets?
- Use Server-Sent Events when data only needs to flow one way, from server to client, like a notification feed or live log. SSE runs over plain HTTP, reconnects automatically, and is simpler to operate. Choose WebSockets when you need true two-way traffic, such as chat or collaborative editing.
- Do WebSockets work through firewalls and proxies?
- Mostly yes. WebSockets use ports 80 and 443 and begin as a normal HTTP upgrade request, so they pass through environments that already allow web traffic. Some older corporate proxies strip the Upgrade header, in which case the connection fails to establish and you fall back to long polling.
- How do WebSockets scale across multiple servers?
- Because each connection is stateful and pinned to one server, you need a shared message bus such as Redis pub/sub or a broker like Kafka so a message arriving on one server reaches users connected to another. Load balancers also need to support sticky sessions or proxy the WebSocket upgrade correctly.
Learn WebSocket hands-on
This page explains the idea. The full lesson lets you step through the ring as servers join and leave, read the implementation, and check yourself with a quiz. It is one of 760+ lessons in the System Design Masterclass, from your first API call to distributed consensus. Eleven Foundation lessons are free, no signup. Lifetime access is ₹499 in India or $7.99 worldwide, one payment, no subscription.
Related lessons
Lessons that touch on WebSocket as part of a larger topic.
WebSockets
Full-duplex, persistent connections, how the real-time web actually works
intermediate · messaging event systems
Design a Chat System like WhatsApp
Design a real-time messaging system - WebSockets, message ordering, end-to-end encryption, presence, and group chats at billion-user scale
capstone · capstone
Design a Real-Time Analytics Dashboard
Design a real-time analytics system - stream processing, WebSocket-powered dashboards, aggregation pipelines, and windowed computations at scale
capstone · capstone
Server-Sent Events (SSE)
One-way server push over HTTP, real-time updates without the complexity of WebSockets
intermediate · messaging event systems
See also
Related glossary terms you might want to look up next.
SSE
Server-Sent Events: a one-way channel where the server pushes updates to the client over HTTP. Simpler than WebSockets when you only need server-to-client streaming.
HTTP
The protocol powering the web. A request-response model where clients ask for resources and servers respond. Stateless by design.
TCP
A reliable transport protocol that guarantees data arrives in order and without errors. It uses a three-way handshake to establish connections.
Rate Limiting
Controlling how many requests a client can make in a given time window. Protects your API from abuse and ensures fair usage.
GraphQL
A query language for APIs where the client specifies exactly what data it needs. No over-fetching, no under-fetching. One endpoint to rule them all.
gRPC
A high-performance RPC framework by Google using Protocol Buffers and HTTP/2. Much faster than REST for service-to-service communication.