What is WebSocket and how do you implement it in Node.js?
Why Interviewers Ask This
This tests whether you can apply Node.js knowledge to real-world scenarios. Interviewers are looking for clarity of thought and evidence that you've encountered this in production code.
Answer
WebSocket is a communication protocol that provides full-duplex (bidirectional), persistent connections over a single TCP connection. Unlike HTTP (request-response), WebSocket allows the server to push data to clients without a client request — essential for real-time features. The connection starts as HTTP then upgrades to WebSocket via the Upgrade header. Implementation in Node.js: (1) ws package (low-level): const wss = new WebSocket.Server({ port: 8080 }); wss.on("connection", ws => { ws.on("message", msg => ws.send(reply)); ws.send("Connected!"); });; (2) Socket.IO (higher-level): adds rooms, namespaces, reconnection, fallback to polling, and broadcast — io.to(room).emit("event", data). Use cases: chat applications, real-time dashboards, collaborative editing, live notifications, multiplayer games, financial tickers. For horizontal scaling with WebSockets, use Redis Pub/Sub as a message broker between multiple server instances (Socket.IO supports this with @socket.io/redis-adapter).
Pro Tip
If you're unsure about a detail, say so honestly and explain your reasoning. Interviewers respect candidates who can think through uncertainty rather than bluffing.
Previous
What is GraphQL and how does it differ from REST in Node.js?
Next
What is the difference between monolithic and microservices architecture in Node.js?