How-To Guide

How to Implement a Multi-Layer Cache

Build a layered cache: a local layer for speed, a shared layer for consistency, and a clear read path that falls through the layers in order.

On this page

  1. Introduction
  2. Choose what each layer holds
  3. Read through the layers in order
  4. Invalidate both layers on a write
  5. Guard against the stampede
  6. Test hit, miss, promotion, and invalidation
  7. Common pitfalls
  8. Conclusion

Introduction

A single cache layer makes one trade-off: a shared cache is consistent across instances but costs a network round trip, and a local cache is fast but per-instance and can diverge. Layering both keeps the strengths and bounds the weaknesses: a small in-process cache catches the hottest keys with no hop, and a shared cache keeps the fleet roughly coherent and absorbs misses. The complexity is the read path and the invalidation, which must touch both layers.

This tutorial builds a two-layer cache for a Node.js service: a local map in front of a shared Redis, a read-through that checks local, then shared, then origin, and an invalidation that clears both. It covers TTLs per layer, stampede protection, and tests for hit, miss, and invalidation. The examples are generic to any in-process cache plus any shared store.

Choose what each layer holds

The local layer should hold the hottest, smallest, most-read keys, because its value is avoiding the network hop and its cost is memory per process. A few hundred to a few thousand entries per process is typical. The shared layer holds a larger working set and is the source that all instances agree on, so a value missing locally is found there without reaching the origin.

Not every value belongs in both. Very large values or rarely read ones may go only to the shared layer to avoid duplicating memory across every instance. Values that must be coherent instantly may skip the local layer entirely, so a write is seen immediately. Decide per key class, and keep the decision with the code that reads the key so the policy is visible.

import { LRUCache } from 'lru-cache';
import { createClient } from 'redis';

const local = new LRUCache({ max: 2000, ttl: 2000 });        // 2s local TTL
const redis = createClient();
await redis.connect();

const SHARED_TTL = 300; // 5 minutes shared

async function get(key) {
  const localHit = local.get(key);
  if (localHit !== undefined) return localHit;               // fastest: no hop
  const shared = await redis.get(key);
  if (shared !== null) {
    const value = JSON.parse(shared);
    local.set(key, value);                                   // warm the local layer
    return value;
  }
  return undefined;                                           // caller loads from origin
}

Read through the layers in order

The read path is local, then shared, then origin. On a local miss, check shared; on a shared hit, promote the value into local so the next read is a local hit; on a shared miss, load from the origin and populate both. Each promotion is what makes the layers useful, because it moves the value one step closer to the caller.

Only populate on a found value. Caching a miss without care can make a transient absence sticky, so handle a genuine ‘not found’ with a short negative TTL rather than a full one, or not at all. Keep the promotion logic in one function so every read path behaves the same and the TTLs are applied consistently.

async function getOrLoad(key, loadFromOrigin) {
  const cached = await get(key);
  if (cached !== undefined) return cached;
  const value = await loadFromOrigin();
  if (value !== undefined) {
    local.set(key, value);
    await redis.set(key, JSON.stringify(value), { EX: SHARED_TTL });
  }
  return value;
}

Invalidate both layers on a write

A write must clear the value from both layers, or a stale copy survives in the local layer of every instance. Invalidate by deleting the key locally in the writing process and in the shared store, and let other instances pick up the change when their local TTL expires or when they next miss. To propagate faster, publish an invalidation event so every instance drops its local copy promptly.

Choose delete over update when invalidating. Writing the new value into every layer risks racing writes and a version skew, while deleting forces the next read to fetch the current value from the origin and repopulate consistently. The cost is one origin read after a write, which is the price of coherence, and a short local TTL bounds how long an untouched instance serves the old value.

async function invalidate(key) {
  local.delete(key);                       // this process
  await redis.del(key);                    // shared layer
  await redis.publish('cache:invalidate', key); // other processes drop their local copy
}
redis.subscribe('cache:invalidate', (key) => local.delete(key));

Guard against the stampede

When a hot key expires, many concurrent requests miss at once and all load from the origin, a stampede that can overload it. A single-flight guard, where the first caller loads and the others wait for its result, prevents the burst. Apply it on the shared miss, so even as the local layer misses across instances, only one load per key proceeds at a time per instance, and the shared cache absorbs the rest.

Combine single-flight with a short negative cache and jitter on the TTL. Jitter spreads expirations so keys do not all expire together. A negative cache with a very short TTL absorbs repeated misses for a genuinely absent key. Together they keep a cache miss from becoming an origin overload, which is the failure that makes a cache worse than no cache.

const inflight = new Map<string, Promise<unknown>>();

function singleFlight<T>(key: string, fn: () => Promise<T>): Promise<T> {
  const existing = inflight.get(key) as Promise<T> | undefined;
  if (existing) return existing;
  const p = fn().finally(() => inflight.delete(key));
  inflight.set(key, p);
  return p;
}

Test hit, miss, promotion, and invalidation

Test that a warm local value is served without touching the shared store, by instrumenting the shared store to count reads. Test that a shared hit promotes into local, so the second read skips the shared store. Test that a write invalidates both layers and the next read reloads from the origin. Test that concurrent misses for one key result in a single origin load, which proves the single-flight guard.

# count shared-store reads: first read -> 1, second warm read -> still 1
curl -s http://localhost:3000/items/1 >/dev/null
curl -s http://localhost:3000/items/1 >/dev/null
# invalidate, then read again: shared-store reads increment by 1
curl -s -X PUT http://localhost:3000/items/1 -d '{"name":"new"}' >/dev/null
curl -s http://localhost:3000/items/1 >/dev/null

Common pitfalls

Populating only one layer so the other never helps, a local TTL longer than coherence allows, invalidating only the shared store so local copies go stale, no single-flight so a hot key expires into a stampede, and caching misses with a full TTL so a transient absence sticks are the recurring mistakes. Two-layer promotion, a short local TTL, dual invalidation with a publish, single-flight, and a short negative cache address them.

Conclusion

A layered cache gets speed from local and coherence from shared. Read through local, then shared, then origin, promote on a hit, invalidate both layers on a write with a publish to bound staleness, and guard the shared miss with single-flight. Self-check by counting shared-store reads and asserting a warm read skips them and a write forces a reload. Then hot keys avoid the hop and the fleet stays coherent within the local TTL.

Sources: Redis: Client-side caching, MDN: HTTP caching, Caffeine: Caching library architecture.

FAQ

Why not just use Redis?
A local in-process cache avoids a network round trip for the hottest keys and reduces load on the shared cache. A shared cache gives consistency across instances but costs a hop. Layering both gets the speed of local for hot keys and the coherence of shared for the rest.
How do layers stay consistent?
They do not stay perfectly consistent, because each has its own TTL. Bound the divergence by giving the local layer a short TTL, and invalidate both layers on a write. The result is eventual consistency within the local TTL, which is acceptable for most cached data.

Related Examples