Sobes.tech
Junior — Middle

How to determine the number of remaining nodes in a distributed system based on Node.js?

sobes.tech AI

Answer from AI

In a distributed system based on Node.js, mechanisms for detecting and monitoring the status of nodes are typically used to determine the number of remaining (active) nodes. The main approaches:

  1. Heartbeat (life signals) — each node periodically sends a signal (heartbeat) to a central service or a distributed storage. The absence of a signal for a specified time indicates that the node is unavailable.

  2. Using service discovery services — for example, Consul, Etcd, or Zookeeper, where nodes register at startup and deregister upon shutdown. Counting registered nodes gives the number of active nodes.

  3. Using cluster libraries for Node.js — for example, node-discover or socket.io with ping and disconnect mechanisms.

Example using a simple heartbeat:

const nodes = new Map(); // node id -> timestamp of last signal

// When receiving a heartbeat from a node
function onHeartbeat(nodeId) {
  nodes.set(nodeId, Date.now());
}

// Function to count active nodes
function countActiveNodes(timeout = 30000) { // 30 seconds
  const now = Date.now();
  let count = 0;
  for (const lastSeen of nodes.values()) {
    if (now - lastSeen < timeout) {
      count++;
    }
  }
  return count;
}

Thus, the number of active nodes is the count of nodes that have recently sent a heartbeat.