Skip to main content
AllDevToolsHub
Back to Glossary

WebSocket

A communications protocol that provides a persistent, full-duplex connection between a client and a server.

Detailed Explanation

Unlike standard HTTP (which is 'pull' based), WebSockets allow the server to 'push' data to the client at any time. This is essential for real-time apps like trading dashboards, chat systems, and collaborative editors. A WebSocket starts as an HTTP request and is 'upgraded' to a persistent TCP connection.

Quick Summary

WebSocket is a persistent, bidirectional connection between browser and server. Once established (via an HTTP upgrade), either side can send messages at any time, making it the go-to for chat, collaboration, and live data.

Key Takeaways

Key Takeaways

  • Begins as an HTTP request with `Upgrade: websocket`, then switches to a long-lived TCP framing protocol.
  • Bidirectional and message-oriented (not byte-stream): each `send()` is a discrete message on both ends.
  • Stateful, the server holds a connection per client; scaling requires sticky routing or a shared pub/sub layer.
  • Heartbeat / ping-pong frames are necessary to detect dead connections; intermediaries silently drop idle TCP.
  • Alternatives for one-way push: Server-Sent Events (simpler) or HTTP/2/3 streaming.
Use Cases

When to use it

  • Chat and messaging apps.
  • Collaborative editing (Google Docs, Figma) via document sync over WebSocket + CRDT/OT.
  • Live dashboards: trading, sports scores, real-time analytics.
  • Multiplayer games and presence/typing indicators.
Watch out

Common Mistakes

  • Trying to scale a single Node process to a million WebSocket clients without horizontal sharding or a pub/sub backbone (Redis, NATS).
  • No reconnection logic in the client; networks flap and connections drop constantly on mobile.
  • Authenticating only on the initial HTTP upgrade and never re-checking, long-lived sessions outlive token expiry.
  • Forgetting heartbeats; load balancers and NATs silently close "idle" connections after 30–120s.
FAQ

WebSocket, Frequently Asked

WebSocket or Server-Sent Events?

Use SSE when only the server needs to push (notifications, dashboards), it's simpler, runs over plain HTTP, and reconnects automatically. Use WebSocket when both sides talk frequently (chat, collaborative editing, gaming).

How do I scale WebSockets?

Sticky load balancing or a stateless edge that forwards to a worker pool, plus a pub/sub layer (Redis, NATS, Kafka) to fan out messages across instances. Or use a managed service (Pusher, Ably, AWS API Gateway WebSocket, Cloudflare Durable Objects).

Related Terms