A protocol that provides full-duplex communication between client and server for real-time applications.
WebSockets provide a persistent, bidirectional communication channel between a client and server. Unlike traditional HTTP requests that close after each response, WebSockets maintain an open connection allowing real-time data exchange in both directions.
Traditional HTTP follows a request-response pattern: the client asks, the server answers, then the connection closes. For real-time applications, this is inefficient.
Imagine a chat application using only HTTP - it would need to constantly ask the server "any new messages?" every few seconds (polling), wasting bandwidth and creating delays.
WebSockets solve this by keeping the connection open. When a new message arrives, the server immediately pushes it to all connected clients without them asking.
The communication starts with a regular HTTP request that includes an "Upgrade" header. If the server supports WebSockets, it agrees to upgrade the connection, and from that point forward, both sides can send data whenever needed.
Once established, the connection stays open until either side decides to close it or there's a network failure.
Chat Applications: WhatsApp Web, Slack, Discord - messages appear instantly without refreshing.
Live Feeds: Twitter/X live updates, stock tickers, sports scores - data streams continuously.
Collaborative Tools: Google Docs, Figma - see others' changes in real-time.
Gaming: Multiplayer games need instant communication between players and servers.
Live Notifications: Get alerts the moment something happens without polling.
Lower Latency: Data arrives within milliseconds instead of waiting for the next poll.
Reduced Server Load: No constant polling means fewer requests and less bandwidth usage.
Bidirectional: Both client and server can initiate communication.
WebSockets require maintaining open connections, which consumes server resources. For applications serving millions of users, you need robust infrastructure to handle that many concurrent connections.
Connection stability matters - mobile networks can be unreliable, so implementing reconnection logic is essential.
When you track a Swiggy delivery in real-time, WebSockets power the live map showing your delivery person's location. Instead of the app repeatedly asking "where is my order?" every few seconds, the server pushes location updates as they happen.
Choose WebSockets when:
For simple, infrequent updates, traditional HTTP or Server-Sent Events (SSE) might be simpler and sufficient.