StackPractices
intermediate By Mathias Paulenko

Implement Redis Cache Invalidation in Node.js

Invalidate Redis cache entries in Node.js with TTL expiry, explicit deletion, pattern-based clearing, and pub/sub-based distributed invalidation.

Overview

Cache invalidation is the hard part of caching. Redis gives you a few ways out: TTL expiry (automatic), explicit DEL (manual), pattern-based clearing (SCAN + DEL), and pub/sub for propagating invalidation across app instances. This recipe covers each one in Node.js with ioredis, and shows when to reach for which.

When to Use

  • Any Node.js application using Redis as a cache layer where stale reads would cause real problems (wrong prices, outdated permissions)
  • Multi-instance deployments where one instance’s del() must propagate to the in-memory caches of the rest
  • Clearing keys in bulk by pattern after mass data updates
  • Preventing stampedes when a hot key expires under load

Avoid it when cached data can tolerate staleness — a plain TTL with no invalidation logic is simpler. And if Redis is your source of truth (queues, sessions), don’t treat those keys as an invalidable cache: deleting them loses real data. For alternatives on other stacks, see Use Spring Cache Annotations with Redis Backend or the write-through cache pattern.

Prerequisites

  • Node.js 18+
  • Redis 6+
  • ioredis package

Solution

1. Install ioredis

npm install ioredis

2. TTL-Based Invalidation (Automatic)

const Redis = require('ioredis');
const redis = new Redis({ host: 'localhost', port: 6379 });

// Set with TTL — Redis auto-expires the key
async function cacheProduct(product) {
  await redis.set(
    `product:${product.id}`,
    JSON.stringify(product),
    'EX', 300 // 5 minutes
  );
}

async function getProduct(id) {
  const data = await redis.get(`product:${id}`);
  return data ? JSON.parse(data) : null;
}

// Redis automatically removes the key after 300 seconds.
// No manual invalidation needed — but stale data exists until expiry.

3. Explicit Deletion (Manual)

// Delete a single key after data changes
async function updateProduct(productId, updates) {
  const product = await db.product.update(productId, updates);

  // Invalidate cache
  await redis.del(`product:${productId}`);

  // Optionally re-populate cache with fresh data
  await redis.set(`product:${productId}`, JSON.stringify(product), 'EX', 300);

  return product;
}

// Delete multiple keys at once
async function deleteProducts(productIds) {
  const keys = productIds.map(id => `product:${id}`);
  const deleted = await redis.del(...keys);
  console.log(`Deleted ${deleted} cache entries`);
}

4. Pattern-Based Invalidation (SCAN + DEL)

When you need to clear all keys matching a pattern (e.g., all product cache entries):

async function invalidatePattern(pattern) {
  const stream = redis.scanStream({
    match: pattern,
    count: 100, // Scan 100 keys per batch
  });

  let deletedCount = 0;

  for await (const keys of stream) {
    // SCAN may return the same key in more than one batch — dedupe first
    const unique = [...new Set(keys)];
    if (unique.length > 0) {
      // Exec per batch so the pipeline doesn't grow without bound
      const results = await redis.pipeline().del(...unique).exec();
      deletedCount += results.reduce((sum, [err, n]) => sum + (err ? 0 : n), 0);
    }
  }

  console.log(`Deleted ${deletedCount} keys matching ${pattern}`);
}

// Usage: clear all product cache entries
await invalidatePattern('product:*');

// Clear all products in a specific category
await invalidatePattern('product:category:electronics:*');

5. Pipeline-Based Bulk Deletion

For large-scale invalidation, batch DEL commands in a pipeline:

async function bulkInvalidate(prefix, batchSize = 1000) {
  let cursor = '0';
  let totalDeleted = 0;

  do {
    // SCAN returns [cursor, keys[]]
    const [nextCursor, keys] = await redis.scan(
      cursor,
      'MATCH', `${prefix}*`,
      'COUNT', batchSize
    );

    if (keys.length > 0) {
      await redis.del(...keys);
      totalDeleted += keys.length;
    }

    cursor = nextCursor;
  } while (cursor !== '0');

  console.log(`Bulk invalidation: deleted ${totalDeleted} keys with prefix ${prefix}`);
  return totalDeleted;
}

6. Pub/Sub-Based Distributed Invalidation

When you run several Node.js instances, one instance’s redis.del() doesn’t notify others. Each app usually keeps its own in-memory L1 cache on top of Redis, so you need a way to tell every instance to drop the stale entry. Pub/sub handles that broadcast:

Sequence diagram showing an invalidation event published by Instance A through Redis pub/sub and received by Instances B and C, which then drop the key from their local caches.
// Cache invalidation publisher (on the instance that made the change)
const invalidationChannel = 'cache:invalidate';

async function updateProductAndNotify(productId, updates) {
  const product = await db.product.update(productId, updates);

  // Delete local cache entry
  await redis.del(`product:${productId}`);

  // Notify all other instances to invalidate
  await redis.publish(invalidationChannel, JSON.stringify({
    type: 'delete',
    keys: [`product:${productId}`],
    timestamp: Date.now(),
  }));

  return product;
}

// Cache invalidation subscriber (on every instance)
const localCache = new Map(); // in-memory L1 cache this instance maintains
const subscriber = new Redis({ host: 'localhost', port: 6379 });

subscriber.subscribe(invalidationChannel);

// Pub/sub is fire-and-forget: while the connection is down, events are lost.
// On reconnect, refresh anything that might have gone stale.
subscriber.on('error', (err) => console.error('subscriber error:', err));
subscriber.on('reconnecting', () => localCache.clear());

subscriber.on('message', (channel, message) => {
  if (channel !== invalidationChannel) return;

  const event = JSON.parse(message);

  switch (event.type) {
    case 'delete':
      event.keys.forEach(key => {
        localCache.delete(key); // Clear in-memory L1 cache
      });
      break;

    case 'pattern':
      // Clear all matching keys from local cache
      for (const key of localCache.keys()) {
        if (key.startsWith(event.prefix)) {
          localCache.delete(key);
        }
      }
      break;

    case 'flush':
      localCache.clear();
      break;
  }
});

7. Write-Through Invalidation

Write to the cache at the same time as the database, so there’s never a stale window:

async function writeThroughUpdate(productId, updates) {
  // Update database
  const product = await db.product.update(productId, updates);

  // Overwrite cache with fresh data
  await redis.set(`product:${productId}`, JSON.stringify(product), 'EX', 300);

  return product;
}

async function writeThroughDelete(productId) {
  await db.product.delete(productId);
  await redis.del(`product:${productId}`);
}

8. Cache-Aside with Lock (Prevent Stampede)

When a cache entry expires, prevent a burst of requests from hitting the database at once:

async function getProductWithLock(productId, retries = 5) {
  const cacheKey = `product:${productId}`;
  const lockKey = `lock:${cacheKey}`;

  // Try cache first
  const cached = await redis.get(cacheKey);
  if (cached) return JSON.parse(cached);

  // Try to acquire lock
  const lockAcquired = await redis.set(lockKey, '1', 'NX', 'EX', 10);
  if (lockAcquired) {
    try {
      // This instance fetches from DB and populates cache
      const product = await db.product.findById(productId);
      if (product) {
        await redis.set(cacheKey, JSON.stringify(product), 'EX', 300);
      }
      return product;
    } finally {
      await redis.del(lockKey);
    }
  } else {
    if (retries <= 0) {
      // Gave up waiting on the lock — fall back to a direct DB read
      return db.product.findById(productId);
    }
    // Another instance is fetching — wait with jitter and retry
    await new Promise(resolve => setTimeout(resolve, 100 + Math.random() * 100));
    return getProductWithLock(productId, retries - 1);
  }
}

How It Works

  1. TTL expiry: Redis attaches a timestamp to each key via the EX flag and clears expired keys lazily on access plus through a periodic active-expiry cycle — so a key can linger a little past its TTL.
  2. DEL command: redis.del(key) drops keys right away, and it accepts several keys in a single call.
  3. SCAN-based pattern deletion: SCAN iterates the keyspace in batches without blocking Redis (unlike KEYS *). Each call hands back a cursor that picks up where the last one stopped. Combine it with DEL in a pipeline for bulk deletion.
  4. Pub/sub invalidation: The instance that changed the data publishes an event; every subscriber hears it and drops the key from its local L1 cache. Redis pub/sub is fire-and-forget — no persistence, no acknowledgment.
  5. Cache stampede prevention: A Redis lock (SET key NX EX timeout) makes sure only one instance fetches from the database on cache miss. Others wait and retry.

Variants

Lazy Invalidation (Soft Delete)

Mark cache entries as stale instead of deleting them:

async function softInvalidate(productId) {
  // Set a flag that the next read should refresh
  await redis.set(`stale:product:${productId}`, '1', 'EX', 60);
}

async function getProduct(productId) {
  const isStale = await redis.exists(`stale:product:${productId}`);
  if (isStale) {
    // Force refresh from DB
    const product = await db.product.findById(productId);
    await redis.set(`product:${productId}`, JSON.stringify(product), 'EX', 300);
    await redis.del(`stale:product:${productId}`);
    return product;
  }
  // Normal cache read
  const cached = await redis.get(`product:${productId}`);
  return cached ? JSON.parse(cached) : null;
}

Versioned Cache Keys

Bump a version number to invalidate all entries in a namespace:

async function getProduct(productId) {
  const version = await redis.get('product_cache_version') || '1';
  const key = `product:v${version}:${productId}`;
  const cached = await redis.get(key);
  if (cached) return JSON.parse(cached);

  const product = await db.product.findById(productId);
  await redis.set(key, JSON.stringify(product), 'EX', 300);
  return product;
}

async function invalidateAllProducts() {
  // Bump version — all old keys become invisible
  await redis.incr('product_cache_version');
}

TTL Jitter

Prevent cache stampedes caused by synchronized expiry:

async function cacheWithJitter(key, value, baseTTL = 300) {
  // Add random 0-60 seconds jitter
  const jitter = Math.floor(Math.random() * 60);
  await redis.set(key, JSON.stringify(value), 'EX', baseTTL + jitter);
}

Best Practices

  • Use TTL as a safety net: Even with explicit invalidation, always set a TTL. If you forget to invalidate, the cache self-heals.
  • Prefer explicit deletion over short TTLs: Short TTLs cause unnecessary cache misses. Set longer TTLs and invalidate explicitly on data changes.
  • Use SCAN, not KEYS: KEYS * walks the whole keyspace in one blocking call. SCAN spreads the same work over incremental, non-blocking batches.
  • Batch DEL in pipelines: Deleting 10,000 keys one by one costs a round trip each. Pipeline them per batch.
  • Prefer UNLINK for large values: DEL frees memory synchronously and can stall Redis on a big key. UNLINK detaches it instantly and frees it in a background thread.
  • Use pub/sub for multi-instance: A single redis.del() doesn’t clear other instances’ L1 caches. Broadcast invalidation events.
  • Add TTL jitter: If thousands of keys expire in the same second they all miss together — a random offset spreads the reloads out.

Common Mistakes

  • Using KEYS * in production: Can freeze Redis for seconds on a big keyspace — the single-threaded server serves nothing else meanwhile. Use SCAN instead.
  • No TTL as fallback: If explicit invalidation fails (bug, exception), stale data persists forever. Always set a TTL.
  • Invalidating too broadly: invalidatePattern('product:*') wipes every product when just one changed — delete the keys you actually mean to.
  • Not handling pub/sub disconnects: If a subscriber loses connection, it misses invalidation events. Reconnect, and refresh what might have gone stale.
  • Race condition in cache-aside: Between get (miss) and set, another request may have already fetched and cached the value — take a lock so only one requester does the work.

Further Reading

Frequently Asked Questions

TTL or explicit invalidation — which should I use?

Both. Use TTL as a safety net (e.g., 5 minutes) and explicit deletion for immediate invalidation on data changes. TTL covers the cases where explicit invalidation fails — a missed event, a crashed instance.

How does Redis pub/sub differ from Redis Streams for cache invalidation?

Pub/sub is fire-and-forget — if a subscriber is offline, it misses the event. Streams persist messages, so offline subscribers can catch up. Use pub/sub for simple invalidation, streams for guaranteed delivery.

What is the difference between DEL and UNLINK?

DEL is synchronous — Redis blocks while freeing memory. UNLINK removes the key from the keyspace immediately but frees memory asynchronously in a background thread. Use UNLINK for large values.

How do I invalidate cache across multiple Redis instances?

On Redis Cluster, a published message reaches every node. With separate Redis instances, each one needs its own pub/sub channel — or put a dedicated broker (RabbitMQ, Kafka) in between for cross-instance invalidation.

Can I use Redis Lua scripts for atomic invalidation?

Yes. A Lua script can check a condition and delete keys atomically. This is useful for compare-and-swap invalidation where you only delete if the cached value matches a specific version.

Is this solution production-ready?

The patterns are the standard cache-aside + invalidation stack, and ioredis is the most-used Node.js Redis client. Before deploying, wire the connection through env vars, configure retryStrategy so reconnects are automatic, and prefer UNLINK over DEL if your values are large.

What are the performance characteristics?

GET/DEL/UNLINK are O(1) — microseconds each. The expensive operations are KEYS * (O(n), blocking — that's why it's banned here) and pattern invalidation, which is O(n) total but spread over non-blocking SCAN batches. Pub/sub costs one extra connection per instance; Redis handles thousands of subscribers without trouble.

How do I debug issues with this approach?

Run MONITOR against a dev Redis to watch the DEL/PUBLISH/SET traffic live. If invalidation events go missing, check subscriber.status — pub/sub drops messages while the connection is down. For stale reads, compare TTL product:1 and the cached payload against the actual DB row.