StackPractices
advanced By Mathias Paulenko

Multi-Level Cache with In-Memory L1 and Redis L2

Cut Redis round-trips on hot keys: in-memory L1 for microsecond reads, Redis L2 for shared state, and pub/sub invalidation across instances

One cache layer rarely gives you everything. In-memory caches answer in microseconds but never leave the process; Redis gives every instance the same data at the cost of a network hop per read. Stacking them — L1 in-memory for hot keys, L2 Redis for shared state — gets you both. The code below builds that stack with pub/sub invalidation, so every instance drops a stale L1 entry the moment another one writes. If you’re weighing the design rather than the implementation, the two-level cache pattern covers the trade-offs.

When to Use This

  • High-traffic APIs where a Redis round-trip on every read is the bottleneck
  • Deployments running several app instances that must see the same cached data
  • Read-heavy workloads that hit the same keys repeatedly within one instance
  • Hot key sets small enough to fit in a few MB of process memory per instance

Skip this setup when you’re running a single instance (a plain in-memory LRU is enough), writes dominate reads, or entries are large enough that duplicating them in every process costs more RAM than the latency you save.

Prerequisites

  • Node.js 18+
  • redis package (npm install redis)
  • lru-cache package (npm install lru-cache)

Solution

1. Install Dependencies

npm install redis lru-cache

2. Implement the Multi-Level Cache

// multi-level-cache.ts
import { LRUCache } from 'lru-cache';
import { createClient, RedisClientType } from 'redis';

export class MultiLevelCache {
  private l1: LRUCache<string, any>;
  private l2: RedisClientType;
  private pubsub: RedisClientType;
  private invalidationChannel: string;
  private l1TtlMs: number;
  private l2TtlMs: number;
  private ready: boolean = false;

  constructor(
    redisUrl: string = 'redis://localhost:6379',
    options: {
      l1MaxSize?: number;
      l1Ttl?: number;
      l2Ttl?: number;
      invalidationChannel?: string;
    } = {},
  ) {
    this.l1TtlMs = options.l1Ttl ?? 60_000;
    this.l2TtlMs = options.l2Ttl ?? 300_000;
    this.l1 = new LRUCache<string, any>({
      max: options.l1MaxSize ?? 1000,
      ttl: this.l1TtlMs,
      updateAgeOnGet: true,
    });

    this.l2 = createClient({ url: redisUrl });
    this.pubsub = createClient({ url: redisUrl });
    this.invalidationChannel = options.invalidationChannel ?? 'cache:invalidate';
  }

  async connect(): Promise<void> {
    await this.l2.connect();
    await this.pubsub.connect();
    await this.pubsub.subscribe(this.invalidationChannel, (message) => {
      const { key } = JSON.parse(message);
      this.l1.delete(key);
    });
    this.ready = true;
  }

  async disconnect(): Promise<void> {
    await this.pubsub.unsubscribe(this.invalidationChannel);
    await this.pubsub.quit();
    await this.l2.quit();
    this.l1.clear();
    this.ready = false;
  }

  async get<T>(key: string): Promise<T | undefined> {
    // L1 — in-memory
    const l1Value = this.l1.get(key);
    if (l1Value !== undefined) {
      return l1Value as T;
    }

    // L2 — Redis
    const l2Value = await this.l2.get(key);
    if (l2Value !== null) {
      const parsed = JSON.parse(l2Value) as T;
      this.l1.set(key, parsed);
      return parsed;
    }

    return undefined;
  }

  async set<T>(key: string, value: T, ttl?: number): Promise<void> {
    const serialized = JSON.stringify(value);

    // Write to both levels; L2 always outlives L1
    this.l1.set(key, value, { ttl: ttl ?? this.l1TtlMs });
    await this.l2.set(key, serialized, {
      EX: Math.floor(Math.max(ttl ?? 0, this.l2TtlMs) / 1000),
    });
  }

  async getOrLoad<T>(
    key: string,
    loader: () => Promise<T>,
    ttl?: number,
  ): Promise<T> {
    const cached = await this.get<T>(key);
    if (cached !== undefined) {
      return cached;
    }

    const value = await loader();
    await this.set(key, value, ttl);
    return value;
  }

  async invalidate(key: string): Promise<void> {
    this.l1.delete(key);
    await this.l2.del(key);
    // Notify other instances to invalidate their L1
    await this.l2.publish(
      this.invalidationChannel,
      JSON.stringify({ key }),
    );
  }

  async invalidatePattern(pattern: string): Promise<void> {
    // Clear L1 entries matching pattern
    for (const key of this.l1.keys()) {
      if (this._matchPattern(key, pattern)) {
        this.l1.delete(key);
      }
    }

    // Clear L2 entries matching pattern
    const keys = [];
    for await (const key of this.l2.scanIterator({ MATCH: pattern, COUNT: 100 })) {
      keys.push(key);
    }
    if (keys.length > 0) {
      await this.l2.del(keys);
    }

    // Notify other instances
    await this.l2.publish(
      this.invalidationChannel,
      JSON.stringify({ pattern }),
    );
  }

  private _matchPattern(key: string, pattern: string): boolean {
    const regex = pattern.replace(/\*/g, '.*');
    return new RegExp(`^${regex}$`).test(key);
  }

  get stats() {
    return {
      l1Size: this.l1.size,
      l1MaxSize: this.l1.max,
      ready: this.ready,
    };
  }
}

3. Use the Cache

// usage.ts
import { MultiLevelCache } from './multi-level-cache';

const cache = new MultiLevelCache('redis://localhost:6379', {
  l1MaxSize: 500,
  l1Ttl: 30_000,   // 30 seconds in L1
  l2Ttl: 300_000,  // 5 minutes in L2
});

await cache.connect();

// Get or load from database
const user = await cache.getOrLoad(
  `user:123`,
  () => db.users.findById(123),
  120_000, // 2 minutes TTL
);

// Invalidate after update
async function updateUser(id: string, data: Record<string, unknown>) {
  const user = await db.users.update(id, data);
  await cache.invalidate(`user:${id}`);
  return user;
}

4. Cache Hit Rate Monitoring

export class InstrumentedMultiLevelCache extends MultiLevelCache {
  private hits = { l1: 0, l2: 0, miss: 0 };

  async get<T>(key: string): Promise<T | undefined> {
    const l1Value = this.l1.get(key);
    if (l1Value !== undefined) {
      this.hits.l1++;
      return l1Value as T;
    }

    const l2Value = await this.l2.get(key);
    if (l2Value !== null) {
      this.hits.l2++;
      const parsed = JSON.parse(l2Value) as T;
      this.l1.set(key, parsed);
      return parsed;
    }

    this.hits.miss++;
    return undefined;
  }

  getHitRates() {
    const total = this.hits.l1 + this.hits.l2 + this.hits.miss;
    if (total === 0) return { l1: 0, l2: 0, miss: 0, total: 0 };
    return {
      l1: (this.hits.l1 / total * 100).toFixed(1) + '%',
      l2: (this.hits.l2 / total * 100).toFixed(1) + '%',
      miss: (this.hits.miss / total * 100).toFixed(1) + '%',
      total,
    };
  }

  resetStats() {
    this.hits = { l1: 0, l2: 0, miss: 0 };
  }
}

How It Works

  1. L1 read — the in-memory LRU is checked first. Hits come back in microseconds with no network involved.
  2. L2 read — on an L1 miss, Redis is checked. A hit populates L1 and returns, paying one round-trip (~1 ms on a same-region network) instead of a database query.
  3. Cache miss — when both levels miss, the loader function queries the source and the result is written to both L1 and L2.
  4. Invalidation — invalidate deletes from L1 and L2, then publishes a message. Peer instances subscribed to the channel drop their L1 copy, so stale data doesn’t linger per-instance.
  5. Tiered TTLs — L1 expires faster than L2 (30 s vs 300 s). Even if a pub/sub message is lost, L1 converges back to L2 state within half a minute instead of serving stale data until the long TTL ends.
flowchart diagram: Read request

Trade-offs and Edge Cases

Running two cache levels costs you real complexity. These are the cases that bite in production:

  • Consistency window — pub/sub delivery is asynchronous. Between a write on instance A and the invalidation reaching instance B, B can still serve its old L1 copy. For data that must never be stale, keep TTLs very short or read through L2 on the critical path.
  • Cache stampede — when a hot key expires, every instance misses L1 and L2 at once and hammers the loader. The read-through variant below mitigates this with background refresh; for harder cases use a per-key lock or request coalescing so only one caller recomputes.
  • Serialization cost — every L2 write pays JSON.stringify and every L2 read pays JSON.parse. For large objects, measure whether a compact format or a smaller payload beats the savings.
  • Memory ceiling — L1 lives in the process heap of every instance. A 1000-entry cap means 1000 entries × N instances; size it against the hot set, not the whole dataset.
  • Eviction asymmetry — lru-cache evicts by recency of access; Redis evicts by its own maxmemory-policy. Make sure the Redis policy isn’t noeviction if you rely on the L2 TTL for cleanup.

Variants

Write-Through Cache

Write to both cache levels and the database in one operation:

async setWithPersistence<T>(
  key: string,
  value: T,
  persist: (value: T) => Promise<void>,
  ttl?: number,
): Promise<void> {
  await persist(value);          // Database first
  await this.set(key, value, ttl); // Then both cache levels
}

Read-Through with Background Refresh

Refresh L2 in the background when L1 is near expiry:

async getOrRefresh<T>(
  key: string,
  loader: () => Promise<T>,
  ttl: number,
): Promise<T> {
  const l1Value = this.l1.get(key);
  if (l1Value !== undefined) {
    // Check if L1 entry is near expiry
    const remaining = this.l1.getRemainingTTL(key);
    if (remaining < ttl * 0.1) {
      // Refresh in background
      setImmediate(async () => {
        const fresh = await loader();
        await this.set(key, fresh, ttl);
      });
    }
    return l1Value as T;
  }
  return this.getOrLoad(key, loader, ttl);
}

Python Implementation

import json
import threading
import time
from typing import Any

from redis import Redis


class MultiLevelCache:
    def __init__(
        self,
        redis_client: Redis,
        l1_maxsize: int = 1000,
        l1_ttl: float = 60.0,
    ):
        self.l2 = redis_client
        self.pubsub = redis_client.pubsub()
        self._l1: dict[str, tuple[Any, float]] = {}
        self._l1_maxsize = l1_maxsize
        self._l1_ttl = l1_ttl
        self._lock = threading.Lock()

    def get(self, key: str) -> Any | None:
        with self._lock:
            entry = self._l1.get(key)
            if entry is not None:
                value, expires_at = entry
                if expires_at > time.monotonic():
                    return value
                del self._l1[key]

        l2_value = self.l2.get(key)
        if l2_value:
            value = json.loads(l2_value)
            with self._lock:
                self._l1[key] = (value, time.monotonic() + self._l1_ttl)
                if len(self._l1) > self._l1_maxsize:
                    oldest = next(iter(self._l1))
                    del self._l1[oldest]
            return value

        return None

    def set(self, key: str, value: Any, ttl: int = 300) -> None:
        with self._lock:
            self._l1[key] = (value, time.monotonic() + self._l1_ttl)
        self.l2.setex(key, ttl, json.dumps(value, default=str))

    def invalidate(self, key: str) -> None:
        with self._lock:
            self._l1.pop(key, None)
        self.l2.delete(key)
        self.l2.publish("cache:invalidate", json.dumps({"key": key}))

    def listen_for_invalidations(self) -> None:
        """Run in a daemon thread; drops L1 keys invalidated by other instances."""
        self.pubsub.subscribe("cache:invalidate")
        for message in self.pubsub.listen():
            if message["type"] == "message":
                key = json.loads(message["data"])["key"]
                with self._lock:
                    self._l1.pop(key, None)

The Python version requires Python 3.10+ for the Any | None annotation. L1 entries expire after l1_ttl seconds (60 s by default), the counterpart of the lru-cache TTL in the TypeScript version. Start the listener once per process with threading.Thread(target=cache.listen_for_invalidations, daemon=True).start().

Best Practices

  • Set L1 TTL shorter than L2 — L1 refreshes from L2, so it re-converges even if an invalidation message is lost
  • Use pub/sub for L1 invalidation — without it, each instance serves stale L1 data until its TTL expires
  • Monitor hit rates per level — a high L1 hit rate means the L1 size is well-tuned; a high L2 hit rate means L1 is too small
  • Handle Redis failures gracefully — wrap L2 calls so L1 keeps serving cached data when Redis is unreachable
  • Coalesce misses on hot keys — a single getOrLoad per key is fine at low traffic, but add a lock or single-flight when an expired hot key can trigger hundreds of parallel loads

Common Mistakes

  • Setting the same TTL for L1 and L2 — L1 never refreshes from L2, so updates from other instances are invisible until full expiry
  • Not subscribing to invalidation — each instance’s L1 drifts independently, serving stale data
  • Making L1 too large — consumes process memory; keep it in the 500–5000 entry range unless you’ve measured otherwise
  • Invalidating L1 but not L2 — the next L1 miss re-populates from stale L2 data
  • Treating invalidation as synchronous — pub/sub is async; a peer can serve its old L1 copy for a few milliseconds after your write

See Also

Frequently Asked Questions

What L1 size should I use?

Start with 1000 entries. Monitor the L1 hit rate — if it's below 80%, increase the size. If memory usage is too high, decrease it.

What happens if Redis is down?

L1 continues serving cached data. New cache misses bypass L2 and call the loader directly. When Redis recovers, L2 starts populating again.

Should I use LRU or LFU for L1?

LRU is the safer default — it tracks recency, which matches how most caches behave. Reach for LFU when a small set of keys gets hammered far more than the rest.

How do I test cross-instance invalidation?

Start two instances, both connected to the same Redis. Set a key on instance A, invalidate it, and verify instance B's L1 no longer has the key.

Why not use Redis alone for everything?

Every read then pays a network round-trip. For keys read thousands of times per second, L1 removes that cost; L2 stays as the shared fallback and the coordination layer.

Can a hot key stampede the database when it expires?

It can. With enough concurrent readers, an expired key produces a burst of loader calls. Wrap getOrLoad with a per-key lock or single-flight so only one caller recomputes while the rest wait or serve the stale entry.

Does the JSON serialization format matter?

JSON.stringify/parse handles most payloads without fuss. For large objects, the serialize/parse cost per L2 access can exceed the latency you saved — measure with your real payload before choosing a different codec.