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+
ioredispackage
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:
// 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
- TTL expiry: Redis attaches a timestamp to each key via the
EXflag and clears expired keys lazily on access plus through a periodic active-expiry cycle — so a key can linger a little past its TTL. - DEL command:
redis.del(key)drops keys right away, and it accepts several keys in a single call. - SCAN-based pattern deletion:
SCANiterates the keyspace in batches without blocking Redis (unlikeKEYS *). Each call hands back a cursor that picks up where the last one stopped. Combine it withDELin a pipeline for bulk deletion. - 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.
- 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.SCANspreads 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:
DELfrees memory synchronously and can stall Redis on a big key.UNLINKdetaches 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. UseSCANinstead. - 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) andset, another request may have already fetched and cached the value — take a lock so only one requester does the work.
Further Reading
- Redis docs — EXPIRE and SCAN: the official semantics for TTL and incremental iteration
- Redis docs — Pub/Sub: delivery guarantees, and why events are lost on disconnect
- ioredis: the client used in every example, including cluster and sentinel support
- Runnable companion project: these helpers wired into a working Express app with tests
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.
Related Resources
Cache Function Results with Redis and TTL in Python
Build a Python decorator that caches function return values in Redis with configurable TTL, key generation, and cache invalidation
RecipeCache HTTP Responses with Nginx Reverse Proxy
Configure Nginx as a caching reverse proxy to cache upstream HTTP responses with TTL zones, cache keys, and conditional purging.
GuideComplete Guide to API Versioning Strategies
Compare URI, header, query-param and content-negotiation versioning for REST, plus GraphQL schema evolution, deprecation and migration.
RecipeUse Spring Cache Annotations with Redis Backend
Apply Spring's @Cacheable, @CachePut, and @CacheEvict annotations with a Redis cache manager for declarative caching in Java applications.
RecipeCache HTTP Responses with httpx and CacheControl in Python
Cache HTTP responses in Python using httpx with CacheControl for HTTP-compliant caching, ETag handling, and conditional requests.
RecipeNode.js Redis Caching: Cache-Aside and TTL
Cache API responses in Node.js with Redis using cache-aside and TTL patterns