WebSockets
Full-duplex browser-server communication over a persistent TCP connection - enabling real-time chat, live updates, and multiplayer without polling.
skill: WebSockets category: Web Development tags: [WebSockets, Real-Time, Socket.io, Node.js, Frontend] readingTime: 5
WebSockets are the right tool for bidirectional real-time communication - chat, live cursors, multiplayer games, trading feeds. For server-to-client only push (notifications, live scores), Server-Sent Events (SSE) are simpler. For infrequent updates, long-polling may suffice.
Workflow
- Set up a WebSocket server with ws or Socket.iows is minimal and fast; Socket.io adds rooms, namespaces, automatic reconnection, and fallback to HTTP long-polling.
- Connect from the browserThe browser's native WebSocket API is sufficient for basic use; Socket.io client adds reconnection and event namespacing.
- Authenticate the WebSocket connectionWebSocket handshake doesn't send cookies by default for cross-origin connections. Pass auth tokens as query params or in first message.
- Use rooms for group messagingRooms let you broadcast to a subset of connected clients - a chat room, a game session, or a document's collaborators.
- Scale with Redis adapterA single server holds WebSocket state in memory. Multiple servers need shared state - the Redis adapter syncs rooms and events across all nodes.
Output Format
Real-time WebSocket server with authentication, rooms, and Redis scaling.
Server: Node.js + Socket.io + Redis adapter
Client: socket.io-client with auth token
Events: join-room, leave-room, message, typing, disconnect
Persistence: DB for message history; WS for live deliveryExamples
Input
Output
Edge Cases & Gotchas
- Connection count limits - Each WebSocket holds an open file descriptor. Default Node.js limits and OS ulimits cap concurrent connections. Tune with ulimit -n 100000 and cluster/pm2.
- Message ordering - WebSockets guarantee order within a single connection, but if a client reconnects, buffered messages during disconnect may arrive out of order. Use sequence numbers for critical ordering.
- Proxy/load balancer sticky sessions - Standard load balancers don't route the same client to the same server. Use sticky sessions (ip_hash in nginx) or the Redis adapter to share state.
- Binary data - WebSockets support binary frames (ArrayBuffer). For large files, use regular HTTP multipart upload instead - WebSocket binary transfer isn't resumable.
When to Break These Rules
- Use SSE (Server-Sent Events) instead of WebSockets when communication is one-directional (server pushes events to the client) - SSE is simpler and works over HTTP/2.
- Use WebRTC for peer-to-peer real-time communication (video calls, screen sharing) - WebSockets are server-mediated and add latency.
Reference Files
https://developer.mozilla.org/en-US/docs/Web/API/WebSockets_APIhttps://socket.io/docs/v4/