Course contentsShow
← Node.js
Lesson 1325 of 1,98012. Caching Strategies and Application SpeedFree lesson

Pub-Sub Synchronization Across Cache Clusters

You will broadcast cache invalidation events to all nodes using a message bus.

In this lesson, you will learn how to maintain cache consistency across multiple Node.js instances by using a message bus to broadcast invalidation signals.

When your application scales horizontally, each Node.js process maintains its own local memory cache. If one instance updates a database record, the local caches of all other instances become "stale" because they are unaware of the change. While TTL-based expiration (Lesson 11) helps, it often introduces an unacceptable delay between the update and the data refresh.

To solve this, we implement Pub-Sub (Publish-Subscribe) Synchronization.

The Mechanism

Instead of relying on timers, we treat our message bus (like Redis Pub-Sub) as a broadcast channel. When an application modifies a piece of data, it publishes an "invalidation message" to a specific channel. Every other running Node.js instance subscribes to this channel. Upon receiving the message, the instance identifies the affected key and flushes it from its local LRU cache.

Implementation Pattern

Here is how you might trigger this flow when a user updates their profile:

// 1. Update the primary database
await db.users.update(userId, data);

// 2. Broadcast the invalidation event to all cluster nodes
redisPublisher.publish('cache-invalidation', JSON.stringify({ key: `user:${userId}` }));

// 3. Subscriber logic in every node process
redisSubscriber.subscribe('cache-invalidation');
redisSubscriber.on('message', (channel, message) => {
  const { key } = JSON.parse(message);
  localCache.del(key); // Instantly clear the stale local copy
});

Why this matters

By decoupling the data update from the cache state, you avoid the "Read-Modify-Write" conflicts discussed in Lesson 16. Even if instances are physically separated or running in different container clusters, the pub-sub layer ensures that the global state remains synchronized as closely as network latency allows. This approach turns your isolated local caches into a coordinated, distributed caching layer, ensuring that no user sees outdated information after a write operation occurs.

Key Takeaway: Use a Pub-Sub message bus to broadcast invalidation signals, allowing your distributed Node.js nodes to purge stale local entries immediately after a database mutation.