Redis LRU Cache With TTL Eviction

Build a Redis-backed caching layer with TTL eviction, LRU maxmemory policy, cache-aside reads, and explicit invalidation on writes.

JavascriptNodeData Fetching

Code

javascriptsnippet
30 lines
import { createClient } from 'redis';

const redis = createClient({ url: process.env.REDIS_URL ?? 'redis://127.0.0.1:6379' });
redis.on('error', (err) => console.error('redis:', err.message));
await redis.connect();

const TTL_SECONDS = 300;

async function cached(key, loader) {
  const hit = await redis.get(key);
  if (hit !== null) {
    await redis.incr('cache:stats:hits');
    return JSON.parse(hit);
  }
  const fresh = await loader();
  await redis.set(key, JSON.stringify(fresh), { EX: TTL_SECONDS, NX: true });
  await redis.incr('cache:stats:misses');
  return fresh;
}

async function invalidate(prefix) {
  const pattern = prefix + ':*';
  for await (const key of redis.scanIterator({ MATCH: pattern, COUNT: 200 })) {
    await redis.del(key);
  }
}

const product = await cached('product:42', () => fetchProduct(42));
await invalidate('product');
await redis.quit();

How the snippet works

Redis LRU Cache With TTL Eviction reduces to the functions cached and invalidate.

The loop for await (const key of redis.scanIterator({ MATCH: pattern, COUNT: 200 })) is the only repeated construct. Asynchronous boundaries use await, so failures surface as rejected promises at the call site instead of being swallowed. The import line is the dependency contract: createClient comes from redis and nothing else.

Environment variables REDIS_URL drive configuration, so one artifact serves every environment.

Points of care

  • Plan for an install step: redis is a real dependency, resolved by the package manager.

Applying it

Entry signature: async function cached(key, loader)

The demo output is labeled (redis:), so every printed line maps back to its originating operation.

Statements that matter

await redis.set(key, JSON.stringify(fresh), { EX: TTL_SECONDS, NX: true });
const product = await cached('product:42', () => fetchProduct(42));
const redis = createClient({ url: process.env.REDIS_URL ?? 'redis://127.0.0.1:6379' });

Interactive Tools for This Topic

FAQ

Which packages must be installed first?
Yes. The imports resolve to `redis`, which the package manager must provide.