Skip to content

Layered cache — L1 in-process, L2 shared, origin

How to build a layered cache — fast L1 inside the process, shared L2 across the cluster, origin at the bottom — and how to size each layer.

A single cache layer makes sense at small scale: every miss hits origin, every hit is fast, and the math is simple. Past a certain throughput, the right answer is a layered cache — a tiny fast cache inside the process (L1), a shared cache visible to the cluster (L2), and origin at the bottom. Each layer absorbs the layer below it. This article is the operating manual for the pattern: when to add a layer, how to size it, and what the consistency story looks like.

How to verify

Measure the hit rate at each existing layer and the load each one passes through.

# In-process cache stats (depends on the library — example: Python cachetools)
curl http://app.internal/metrics | grep -E 'cache_(hit|miss|size|evict)'

# Redis L2 stats
redis-cli INFO stats | grep -E 'keyspace_(hits|misses)|expired_keys'
redis-cli DBSIZE

# Origin DB hits
psql -c "SELECT relname, idx_scan + seq_scan AS total_reads FROM pg_stat_user_tables ORDER BY total_reads DESC LIMIT 10;"

If origin is doing 80 % of the read work, the L2 is undersized or the L1 is missing. If L1 hit rate is 95 % but every L1 miss goes straight to origin, you have skipped the L2 step.

What’s happening

Caching is a memory/latency/cost trade-off. An in-process cache (L1) has the fastest access (no serialization, no network) but is per-process — a 100-MB L1 means 100 MB times your process count, and entries do not propagate. A shared cache (L2 — Redis, memcached) is bigger and shared across the cluster but pays the network round-trip. Origin is biggest and slowest.

The pattern: read first from L1 (5 µs), miss falls to L2 (1 ms), miss falls to origin (10-100 ms). On miss, populate both layers above. On invalidation, clear from L1 (cheap, per-process) and from L2 (one delete); origin remains the source of truth.

The trick is the L1 invalidation story. L2 holds the canonical cached value; L1 caches L2’s value, so an L2 invalidation must reach every L1. Common solutions: TTL L1 entries aggressively (10-60 seconds) so they self-heal, or wire L1 to subscribe to a pub/sub channel that L2 publishes invalidation events on. The TTL approach is simpler; the pub/sub approach is necessary when staleness costs are high.

The procedure

  1. Pick the L1 library that matches your runtime. The candidates are not equal — pick one that supports per-entry TTL, size limits, and stats.

    # Python: cachetools with TTL
    from cachetools import TTLCache
    l1 = TTLCache(maxsize=10_000, ttl=30)
    
    # Go: hashicorp/golang-lru/v2/expirable
    import "github.com/hashicorp/golang-lru/v2/expirable"
    l1 := expirable.NewLRU[string, []byte](10_000, nil, time.Second*30)
    
    # Node.js: lru-cache
    const LRU = require('lru-cache')
    const l1 = new LRU({ max: 10_000, ttl: 30_000 })
  2. Wrap the read path. Hit L1, fall to L2, fall to origin; populate up on the way back.

    def get(key):
        v = l1.get(key)
        if v is not None: return v
        v = redis.get(key)
        if v is not None:
            l1[key] = v
            return v
        v = origin_load(key)
        redis.set(key, v, ex=300)
        l1[key] = v
        return v
  3. Wire invalidation. Application writes invalidate L2 (one DEL) and publish an invalidation message; L1 instances subscribe and drop the key locally.

    def invalidate(key):
        redis.delete(key)
        redis.publish('cache_invalidations', key)
    
    # In L1 subscriber thread
    def subscriber():
        p = redis.pubsub()
        p.subscribe('cache_invalidations')
        for msg in p.listen():
            if msg['type'] == 'message':
                l1.pop(msg['data'].decode(), None)
  4. Size each layer with a budget. L1 is “per process times processes” — the cache is duplicated. L2 is “total RAM across nodes if clustered.” Origin is whatever you have.

    L1: 10,000 entries * average 1 KB = 10 MB per process,
        16 processes per node, 4 nodes = 640 MB total RAM in L1.
    L2: 4 GB Redis instance covers ~4M entries at 1 KB each.
    Origin: 100 GB Postgres holds the source of truth.
  5. Monitor each layer’s hit rate. A useful L1 has ≥30 % hit rate; below that it costs memory without saving much. A useful L2 has ≥80 % hit rate. Origin sees what falls through.

    # expose via prometheus_client
    l1_hits.inc()    # in your get() function
    l1_misses.inc()
    l2_hits.inc()
    l2_misses.inc()

Common pitfalls

  • L1 entries with TTL longer than the L2 entries — L1 keeps a value alive after L2 expires it; you have created a stale read window.
  • Populating L1 from a miss that came from L1’s own subscriber — you have created a write loop. Subscriber drops, does not populate.
  • Sizing L1 by “available RAM” without dividing by process count — N=16 processes means each one sees 1/N of the budget.
  • Treating L1 as the source of truth for any state that needs cluster consistency. L1 is a read-through accelerator; never the only place a value lives.
  • Skipping L1 statistics. Without per-layer hit rates you cannot tell if L1 is paying its rent.

In the engagements we run, the layered cache is the production-grade design behind anything that calls itself “high traffic.” Stack Harbor’s managed operations approach is to set the sizes from real measurements, monitor each layer’s contribution, and adjust as traffic shifts — the L1/L2 split is not “set once and forget.”