Urgent.News

What's breaking now, across thousands of outlets.

Tech

WebSockets in Node.js: Real-Time Apps Done Right

From a raw ws echo server to a horizontally scaled Socket.IO deployment — with the heartbeat, backpressure, and reconnection logic that keeps real-time apps alive in production. A client came to me with a dashboard that fell over. It was a fleet-tracking product — trucks reporting positions, dispatchers watching them on a live map — and the backend was polling a REST endpoint every three seconds…

WebSockets have revolutionized real-time applications by providing a single, long-lived TCP connection between a client and a server. This connection allows for efficient, low-overhead communication, as opposed to the traditional polling method where each client repeatedly requests updates from the server.

However, WebSockets are not a universal solution. They require careful consideration of their added connection state, which consumes memory and monitoring resources on the server. If updates occur less frequently than every 30 seconds, polling may be a more efficient choice. Conversely, WebSockets are ideal for real-time features such as sub-second updates, live chat, presence indicators, collaboration tools, and vehicle tracking systems where server-initiated pushes are necessary.

To implement a WebSocket server, start with the minimal "ws" package. This skeleton sets up a basic server that listens on port 8080 and exposes the "/live" path for WebSocket connections. The server-side code initializes a WebSocket server, logs connected clients, listens for message events to broadcast updates to all connected clients, and handles disconnections. The client-side code is equally straightforward, creating a new WebSocket instance and defining event listeners for incoming messages and connection closure.

One critical aspect of WebSocket deployment is handling connection stability. Ghost clients can accumulate in the server's memory if no heartbeat mechanism is in place. To prevent this, implement a heartbeat system where the server sends periodic ping messages to clients, and clients respond with pong acknowledgments. Clients that fail to respond within the expected timeframe are considered disconnected and removed from the server's list of active connections.

This simple yet effective heartbeat mechanism ensures that your WebSocket server remains responsive and avoids resource exhaustion due to inactive connections.

Written by urgent.news from Dev.to's reporting — not their text. Machine-written — may contain errors; check the original before relying on it.

Read the original at dev.to →

More in Tech

More from Sunday 6 September →