In this lesson, you will learn how to prevent data loss during network instability by implementing an outbound message queue that caches messages while your WebSocket is offline.
The Problem: Transient Disconnects
When a client’s network drops, your server might attempt to push an update—like a real-time notification or a status change—at the exact moment the socket is closing or unavailable. If you simply call socket.send() during this window, the data vanishes into the void. To ensure reliability, we need to intercept these attempts and "park" them in a queue until the connection heartbeat signals that the client is back online.
Implementing the Buffer Pattern
The most robust approach is to wrap your socket sending logic in a service class. Instead of sending directly, you check the readyState of the socket. If the connection isn't OPEN, you push the message into an array (a buffer) rather than discarding it.
class SocketMessenger {
constructor(socket) {
this.socket = socket;
this.buffer = [];
}
send(data) {
if (this.socket.readyState === WebSocket.OPEN) {
this.socket.send(JSON.stringify(data));
} else {
console.log('Connection down, buffering message.');
this.buffer.push(data);
}
}
flush() {
console.log(`Reconnected! Flushing ${this.buffer.length} messages.`);
while (this.buffer.length > 0) {
this.send(this.buffer.shift());
}
}
}
Managing the Lifecycle
Once your reconnection logic successfully re-establishes the handshake, you must trigger the flush() method. The while loop ensures that all queued messages are processed in the order they were received.
Pro-tip: Be mindful of memory leaks. If a client remains disconnected for a long duration, your buffer array could grow indefinitely. Consider implementing a maximum queue size or a "time-to-live" for buffered messages to ensure that the server doesn't consume excessive memory for stale data.
Key Takeaway: By decoupling your message-sending logic from the immediate state of the socket, you transform a fragile stream into a resilient, buffer-aware communication channel that persists across connection windows.