WebSocket
What is it?
WebSocket is a protocol that keeps a persistent two-way connection open between a browser and server so they can send messages instantly in both directions.
Explain like I'm 5
Why was it created?
HTTP requires the client to ask before the server can respond, which is clumsy for live updates. WebSocket was created for true real-time, server-can-push communication.
Where is it used?
- Chat and messaging apps
- Live dashboards and tickers
- Multiplayer games
- Collaborative editing
Why should developers care?
Chat, live dashboards, multiplayer features, and notifications often rely on WebSockets. Front-end and back-end developers build with them.
How does it work?
The connection starts as an HTTP request that 'upgrades' to a WebSocket. After that, the single connection stays open and either side can send messages at any time with low overhead.
Real-world example
In a chat app, the server pushes new messages to all connected clients instantly over their open WebSocket connections, with no polling.
Common use cases
- Real-time chat
- Live notifications and feeds
- Collaborative tools
- Streaming live data to dashboards
Advantages
- Instant, low-latency two-way messaging
- Server can push without a request
- Less overhead than repeated polling
- Persistent connection
Disadvantages
- Connections consume server resources
- Harder to scale than stateless HTTP
- Needs reconnection handling
When should you use it?
When you need live, bidirectional updates with low latency.
When should you avoid it?
For simple request/response data where regular HTTP is simpler and cacheable.
Alternatives
Related terms
Interview questions
Beginner
- What problem does WebSocket solve over HTTP?
- What is a real-time use case for it?
Intermediate
- How does the WebSocket handshake start?
- Why is polling less efficient?
Senior
- How would you scale WebSocket connections across many servers?
- How do you handle reconnection and missed messages?
Common misconceptions
- "WebSocket replaces HTTP" — it complements it; most apps use HTTP for normal requests and WebSocket only for live updates.
- "WebSockets are always the answer for updates" — Server-Sent Events or polling can be simpler for one-way data.
Fun facts
- A WebSocket connection begins life as an HTTP request before upgrading.
- Server-Sent Events offer a simpler one-way alternative for server-to-client streams.
Timeline
- 2011 — WebSocket protocol standardized
Learning resources
Quick summary
WebSocket keeps a persistent two-way connection open so servers and clients can exchange messages in real time.
Cheat sheet
- Persistent two-way connection
- Server can push to client
- Starts as an HTTP upgrade
- Great for chat and live data