Distributed Cache with Invalidation

cachingHard
Applicability

When to Use

When running multiple application instances
When cache consistency across nodes matters
When data changes need to propagate quickly
Overview

How It Works

In distributed systems, each node may have its own cache. When data changes, all caches must be invalidated. This pattern uses a pub-sub channel (Redis or NATS MCP Server) to broadcast invalidation events. When any node updates data, it publishes an invalidation message that all other nodes receive. The MCP agent subscribes to the invalidation channel on startup. When it receives an invalidation message, it removes the affected key from its local cache. This ensures all nodes see consistent data within the pub-sub delivery time.
Implementation

Code Example

typescript
const localCache = new Map();

// Subscribe to invalidation events
nats.subscribe("cache.invalidate", (msg) => {
  const { key } = JSON.parse(msg);
  localCache.delete(key);
});

async function get(key) {
  if (localCache.has(key)) return localCache.get(key);
  const data = await redis.get(key);
  if (data) { localCache.set(key, JSON.parse(data)); return JSON.parse(data); }
  const dbData = await postgres.query("SELECT * FROM data WHERE key=$1", [key]);
  await redis.set(key, JSON.stringify(dbData.rows[0]));
  localCache.set(key, dbData.rows[0]);
  return dbData.rows[0];
}

async function update(key, value) {
  await postgres.query("UPDATE data SET value=$1 WHERE key=$2", [value, key]);
  await redis.del(key);
  localCache.delete(key);
  await nats.publish("cache.invalidate", JSON.stringify({ key }));
}

Quick Info

Categorycaching
ComplexityHard

Need Architecture Help?

Our team designs custom automation architectures.

Get in Touch
CortexAgent Customer Service

Want to skip the form?

Our team is available to help you get started with CortexAgent.

This chat may be recorded for quality assurance. You can view our Privacy Policy.