Course contentsShow
← Node.js
Lesson 1095 of 1,98010. Real-time Communication and WebsocketsFree lesson

Building a Reliable Message Delivery System

You will implement acknowledgment callbacks to confirm that critical messages reached the client successfully.

In this lesson, you will learn how to implement acknowledgment callbacks to ensure critical messages are successfully received by the client, transforming a "fire-and-forget" socket event into a reliable delivery mechanism.

The Problem: Fire-and-Forget

In a standard WebSocket implementation, when you call socket.send(), the server pushes data into the TCP buffer and considers its job done. However, there is no inherent guarantee that the client application processed the message, or that it even received it before a sudden network drop occurred.

Implementing Acknowledgments

To achieve reliability, we introduce an Acknowledgment (ACK) pattern. Instead of just sending a payload, the server sends a unique identifier (like a UUID) along with the message and expects a specific confirmation back from the client.

If the server doesn't receive this confirmation within a defined timeout window, it marks the message as "pending retry" and places it into a retransmission queue.

Here is how you might structure an ACK-based event:

// Server-side: Sending a critical message with a callback
const messageId = generateUniqueId();

socket.send(JSON.stringify({
  type: 'CRITICAL_UPDATE',
  id: messageId,
  payload: { balance: 500 }
}));

// We store the message in a Map for retry logic
pendingAcks.set(messageId, {
  payload,
  timestamp: Date.now(),
  retries: 0
});

The Client’s Role

The client must be programmed to listen for these specific message types and immediately emit an ACK event back to the server.

// Client-side: Acknowledging receipt
socket.on('message', (data) => {
  const msg = JSON.parse(data);
  if (msg.type === 'CRITICAL_UPDATE') {
    // Process the update...
    
    // Send confirmation back to the server
    socket.send(JSON.stringify({ 
      type: 'ACK', 
      id: msg.id 
    }));
  }
});

When the server receives the ACK event with the matching id, it removes the message from the pendingAcks map. If a message lingers in the map beyond the timeout threshold, the server triggers a retry, ensuring that the client eventually receives the critical state update.

Key Takeaway: Reliability is achieved by shifting from one-way broadcasting to a request-response cycle where the sender tracks delivery status until a formal acknowledgment is received from the recipient.