Course contentsShow
← Node.js
Lesson 586 of 1,9806. Networking and HTTP FundamentalsFree lesson

Micro-Service Service Discovery

Implement a simple heartbeat mechanism to track the health of available service instances in a cluster.

Keeping Services Alive: The Heartbeat Mechanism

In this lesson, you will learn how to implement a heartbeat mechanism to track the health of individual service instances in a micro-service cluster.

When you run multiple instances of a service, your API Gateway needs to know which ones are actually "alive" and ready to process requests. If a server crashes or encounters a memory leak, it shouldn't continue receiving traffic. A heartbeat is a periodic signal sent from the service instance to a central registry (or the gateway itself) to prove that it is healthy and responsive.

Implementing the Pulse

Think of this like a doctor checking a patient's pulse. Each service instance proactively tells the system, "I'm still here," at a set interval (e.g., every 5 seconds). If the registry doesn't receive a signal within a specific window, it marks the instance as "down" and stops routing requests to it.

Here is a simplified example of how a service instance might send its heartbeat to a registry:

// On the Service Instance
const HEARTBEAT_INTERVAL = 5000; // 5 seconds

function sendHeartbeat() {
  fetch('http://api-gateway/register/heartbeat', {
    method: 'POST',
    body: JSON.stringify({ instanceId: 'node-01', status: 'up' }),
    headers: { 'Content-Type': 'application/json' }
  }).catch(() => console.error("Registry unreachable"));
}

// Send the heartbeat every 5 seconds
setInterval(sendHeartbeat, HEARTBEAT_INTERVAL);

Why it Matters

Without heartbeats, your cluster suffers from "ghost instances"—servers that appear active in your discovery list but are actually dead, causing 503 errors for your users. By implementing this, you create a self-healing architecture. The registry keeps a map of healthy instances, and when it misses a heartbeat from node-01, it immediately removes it from the rotation, ensuring that only functioning services handle your traffic.

This simple "I'm alive" signal is the backbone of reliable distributed systems, allowing your gateway to remain load-balancer-aware even as individual nodes come and go.

Key Takeaway: A heartbeat mechanism prevents request failures by ensuring the traffic director only routes traffic to instances that have proven their health through regular, timely status updates.