Course contentsShow
← Node.js
Lesson 672 of 1,9807. Web Framework Architecture and MiddlewareFree lesson

Worker-to-Worker Communication

Enable synchronization between clustered processes using message passing channels.

In this lesson, you will learn how to enable direct synchronization between clustered processes using Node.js's built-in message-passing channels.

The Need for Synchronization

When you use the cluster module to spin up multiple worker processes, each worker lives in its own isolated memory space. While this is great for performance and stability, it creates a "silo" effect. If Worker A updates a shared state (like a local cache or a throttling counter), Worker B has no way of knowing about that change.

To bridge this gap, Node.js provides a built-in IPC (Inter-Process Communication) channel. This allows your workers to talk to each other by routing messages through the primary process.

How Message Passing Works

Think of the primary process as a central post office. Since the primary process maintains a reference to every worker, it can receive a message from one worker and "forward" it to another.

Here is how you can implement a simple synchronization pattern:

const cluster = require('cluster');

if (cluster.isWorker) {
  // Sending a sync message to other workers
  process.send({ type: 'SYNC_CACHE', data: { userId: 123 } });

  // Listening for incoming sync messages
  process.on('message', (msg) => {
    if (msg.type === 'SYNC_CACHE') {
      console.log('Worker updated local cache with:', msg.data);
    }
  });
}

if (cluster.isPrimary) {
  cluster.on('message', (sender, message) => {
    // Broadcast the message to all other workers
    for (const id in cluster.workers) {
      if (cluster.workers[id] !== sender) {
        cluster.workers[id].send(message);
      }
    }
  });
}

Designing the Communication Flow

When implementing this, remember that messaging is asynchronous. Because you are sending data across process boundaries, the payload must be serializable (usually JSON).

You should avoid sending massive objects over this channel, as it can block the event loop of the primary process. Instead, treat the IPC channel as a signaling system—send lightweight "notifications" that trigger the workers to perform their own local updates or re-fetch data from your shared database. By using this pattern, you keep your workers synchronized while maintaining the architectural benefits of process isolation.

Key Takeaway: Use the primary process as a message broker to relay signals between isolated workers, ensuring all processes stay consistent without sharing memory directly.