In this lesson, you will learn how to capture telemetry data—specifically round-trip time (RTT) and connection duration—to gain visibility into the health of your real-time WebSocket infrastructure.
Measuring Round-Trip Time (RTT)
To monitor latency, we measure how long a message takes to travel from the client to the server and back. We do this by attaching a high-resolution timestamp to a "ping" event emitted by the client. When the server receives the event, it immediately echoes it back.
// Client-side: Emitting the ping with a timestamp
const startTime = Date.now();
socket.emit('latency-check', { startTime });
// Client-side: Listening for the response
socket.on('latency-response', (data) => {
const roundTripTime = Date.now() - data.startTime;
console.log(`Current RTT: ${roundTripTime}ms`);
});
// Server-side: Echoing back
socket.on('latency-check', (data) => {
socket.emit('latency-response', { startTime: data.startTime });
});
By tracking this roundTripTime over time, you can detect spikes in jitter or network congestion. If the RTT consistently trends upward, your application may be struggling with heavy event-loop blockage or downstream network bottlenecks.
Tracking Connection Duration
Connection duration is a vital metric for identifying "churn"—the rate at which clients connect and disconnect. By capturing the timestamp when a socket joins and calculating the difference when it leaves, you can determine the average session length.
const connectionStats = new Map();
io.on('connection', (socket) => {
connectionStats.set(socket.id, Date.now());
socket.on('disconnect', () => {
const start = connectionStats.get(socket.id);
const duration = Date.now() - start;
console.log(`Socket ${socket.id} stayed connected for ${duration}ms`);
connectionStats.delete(socket.id);
});
});
Tracking this allows you to spot patterns, such as whether users are experiencing frequent involuntary disconnects (possibly due to aggressive load balancer timeouts) or if sessions are typically short-lived. Capturing these two metrics—latency and session length—gives you a baseline to distinguish between a healthy, responsive socket cluster and one that is degraded.
Key Takeaway: Monitor performance by measuring the round-trip latency of heartbeat events and calculating the duration of every socket session to proactively identify network degradation and connection instability.