Two-Level Cache Pattern
Combine an L1 in-memory cache with an L2 distributed cache to reduce latency for hot keys while maintaining cache consistency across instances.
Overview
A two-level cache combines an L1 in-memory cache (fast, local, limited size) with an L2 distributed cache (slower, shared, larger capacity). L1 serves hot keys at memory speed with zero network overhead. L2 provides shared cache state across application instances and holds the full dataset.
Reads check L1 first. On a miss, they check L2. On an L2 miss, they fetch from the database and populate both levels. Writes update both levels and invalidate L1 on other instances via pub/sub or TTL. For a runnable implementation with Redis pub/sub invalidation, see the multi-level cache recipe.
When to Use
- Hot keys are read frequently and network latency to Redis is noticeable
- Multiple application instances share cached data
- You need sub-millisecond read latency for specific keys
- L1 miss rate is low enough that the extra complexity is justified
- You want to reduce load on the distributed cache (Redis)
Skip it if you run a single instance (L2 alone is enough), if access is uniform with no hot keys, or if Redis latency is already acceptable.
Solution
Python with LRU L1 and Redis L2
import redis
import json
import time
from collections import OrderedDict
class TwoLevelCache:
def __init__(self, redis_client: redis.Redis, l1_max_size: int = 1000, l1_ttl: float = 60.0, l2_ttl: int = 3600):
self.redis = redis_client
self.l1_max_size = l1_max_size
self.l1_ttl = l1_ttl
self.l2_ttl = l2_ttl
self._l1 = OrderedDict() # key -> (value, expiry_timestamp)
def get(self, key: str, loader: callable) -> any:
# L1 check
if key in self._l1:
value, expiry = self._l1[key]
if time.time() < expiry:
self._l1.move_to_end(key)
return value
del self._l1[key]
# L2 check
cached = self.redis.get(key)
if cached is not None:
value = json.loads(cached)
self._populate_l1(key, value)
return value
# Cache miss — load from database
value = loader()
self._populate_l1(key, value)
self.redis.setex(key, self.l2_ttl, json.dumps(value))
return value
def _populate_l1(self, key: str, value: any):
if len(self._l1) >= self.l1_max_size:
self._l1.popitem(last=False) # Evict LRU
self._l1[key] = (value, time.time() + self.l1_ttl)
def invalidate(self, key: str):
self._l1.pop(key, None)
self.redis.delete(key)
cache = TwoLevelCache(redis.Redis(host='localhost', port=6379))
def get_user(user_id: str) -> dict:
return cache.get(
f"user:{user_id}",
lambda: db.query_one("SELECT * FROM users WHERE id = %s", [user_id])
)
def update_user(user_id: str, name: str, email: str):
db.execute("UPDATE users SET name=%s, email=%s WHERE id=%s", [name, email, user_id])
cache.invalidate(f"user:{user_id}")
Pub/sub invalidation for L1
The snippet above only clears L1 on the instance that writes. Other instances serve stale data until their L1 TTL kicks in. Publishing invalidations on a Redis channel closes that window:
CHANNEL = "cache:invalidate"
def invalidate(self, key: str):
self._l1.pop(key, None)
self.redis.delete(key)
self.redis.publish(CHANNEL, key) # tell every other instance
# In a background thread on each instance:
def listen_invalidations(cache: TwoLevelCache):
pubsub = cache.redis.pubsub()
pubsub.subscribe(CHANNEL)
for message in pubsub.listen():
if message["type"] == "message":
cache._l1.pop(message["data"].decode(), None)
The race to watch: an instance can repopulate L1 between your delete and the published message. Publishing invalidation twice (delete → write → publish again) or versioning keys shrinks it further.
TypeScript with Map L1 and Redis L2
import { createClient } from 'redis';
class TwoLevelCache {
private l1: Map<string, { value: any; expiry: number }> = new Map();
private l1MaxSize: number;
private l1TtlMs: number;
private l2Ttl: number;
private redis: ReturnType<typeof createClient>;
constructor(
redisClient: ReturnType<typeof createClient>,
l1MaxSize = 1000,
l1TtlMs = 60000,
l2Ttl = 3600
) {
this.redis = redisClient;
this.l1MaxSize = l1MaxSize;
this.l1TtlMs = l1TtlMs;
this.l2Ttl = l2Ttl;
}
async get<T>(key: string, loader: () => Promise<T>): Promise<T> {
// L1 check
const l1Entry = this.l1.get(key);
if (l1Entry && Date.now() < l1Entry.expiry) {
// Refresh LRU position
this.l1.delete(key);
this.l1.set(key, l1Entry);
return l1Entry.value as T;
}
this.l1.delete(key);
// L2 check
const l2Cached = await this.redis.get(key);
if (l2Cached !== null) {
const value = JSON.parse(l2Cached) as T;
this.populateL1(key, value);
return value;
}
// Cache miss — load from database
const value = await loader();
this.populateL1(key, value);
await this.redis.set(key, JSON.stringify(value), { EX: this.l2Ttl });
return value;
}
private populateL1(key: string, value: any): void {
if (this.l1.size >= this.l1MaxSize) {
// Evict oldest entry (first in Map)
const oldestKey = this.l1.keys().next().value;
if (oldestKey) this.l1.delete(oldestKey);
}
this.l1.set(key, { value, expiry: Date.now() + this.l1TtlMs });
}
invalidate(key: string): void {
this.l1.delete(key);
this.redis.del(key);
this.redis.publish('cache:invalidate', key);
}
}
// Usage
const redisClient = createClient({ url: 'redis://localhost:6379' });
await redisClient.connect();
const cache = new TwoLevelCache(redisClient);
const user = await cache.get(`user:${userId}`, () =>
db.query('SELECT * FROM users WHERE id = $1', [userId])
);
Java with Caffeine L1 and Redis L2
import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import redis.clients.jedis.Jedis;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.concurrent.TimeUnit;
public class TwoLevelCacheManager {
private final Cache<String, Object> l1;
private final Jedis l2;
private final ObjectMapper mapper = new ObjectMapper();
private final int l2Ttl;
public TwoLevelCacheManager(Jedis jedis, int l1MaxSize, int l1TtlMinutes, int l2TtlSeconds) {
this.l2 = jedis;
this.l2Ttl = l2TtlSeconds;
this.l1 = Caffeine.newBuilder()
.maximumSize(l1MaxSize)
.expireAfterWrite(l1TtlMinutes, TimeUnit.MINUTES)
.build();
}
@SuppressWarnings("unchecked")
public <T> T getOrLoad(String key, java.util.function.Function<String, T> loader, Class<T> type) {
// L1 check
T l1Value = (T) l1.getIfPresent(key);
if (l1Value != null) {
return l1Value;
}
// L2 check
String l2Cached = l2.get(key);
if (l2Cached != null) {
try {
T value = mapper.readValue(l2Cached, type);
l1.put(key, value);
return value;
} catch (Exception e) {
// Deserialization failed, treat as miss
}
}
// Cache miss — load from database
T value = loader.apply(key);
try {
l2.setex(key, l2Ttl, mapper.writeValueAsString(value));
} catch (Exception e) {
// Serialization failed, skip L2
}
l1.put(key, value);
return value;
}
public void invalidate(String key) {
l1.invalidate(key);
l2.del(key);
l2.publish("cache:invalidate", key);
}
}
Explanation
The two-level cache exploits locality of reference. Hot keys are served from L1 (in-memory), which has sub-microsecond access time. Cold keys fall through to L2 (Redis), which has network latency but serves all instances.
The L1 cache is per-instance. Each application instance maintains its own L1, so L1 can hold stale data after another instance writes. Two mechanisms bound that staleness:
- Short L1 TTL (e.g. 60s vs 1h on L2): simplest option, staleness window equals the TTL.
- Pub/sub invalidation: on write, publish the key so every instance drops it immediately. Staleness shrinks to milliseconds but adds a moving part.
On a write, both L1 and L2 are invalidated locally and the key is broadcast. If Redis is down, degrade to L1-only mode and let the TTL handle consistency: your reads keep working, just staler.
Variants
| Approach | L1 Implementation | L2 Implementation | Consistency |
|---|---|---|---|
| LRU + Redis | OrderedDict / Map | Redis | Eventual (L1 TTL) |
| Caffeine + Redis | Caffeine | Redis | Eventual (L1 TTL) |
| Pub/sub invalidation | Any in-memory | Redis | Strong (on invalidate) |
| Write-through both | Any in-memory | Redis | Strong |
| L1-only (no L2) | LRU / Caffeine | None | Per-instance, no sharing |
Related but different: cache-aside loads on miss without a local tier, read-through hides the loader inside the cache itself.
What Works
- Keep L1 small: 1000–5000 entries is typical; LRU eviction bounds memory
- Set L1 TTL well below L2 TTL (roughly 1/10): L1 must expire faster or it doesn’t reduce L2 load
- Broadcast L1 invalidations when staleness beyond a few seconds hurts; see the pub/sub snippet above
- Watch L1 hit ratio: if it stays low, drop the level; it only pays off for keys hit many times per second
- Serialize consistently: L1 holds objects, L2 holds JSON; make sure the round-trip preserves types
Common Mistakes
- L1 too large: GC pressure or OOM; cap size and evict LRU
- L1 TTL equal to L2 TTL: both expire together and L1 saves nothing
- No cross-instance invalidation: instance A writes, instance B keeps serving stale L1 data
- Caching everything in L1: cold keys waste memory and evict the hot ones L1 exists for
- No L2 failure plan: when Redis dies, every L2 miss becomes a database hit; fall back to L1-only or a circuit breaker
- Treating pub/sub as ordered delivery: a repopulate can race the invalidation; version keys or double-publish if it matters
See Also
- Multi-level cache recipe — runnable L1+L2 implementation with pub/sub invalidation
- Cache stampede prevention — what happens when the hot key expires
- Cache invalidation pattern — the broader invalidation toolbox
- Caffeine docs — the go-to L1 library for the JVM
- Redis Pub/Sub — the invalidation broadcast channel
- Runnable examples — all three implementations plus the pub/sub listener in the companion repo
Frequently Asked Questions
What is the difference between L1 and L2 cache?
L1 is in-memory, per-instance, and fast (sub-microsecond). L2 is distributed (Redis), shared across instances, and slower (network round-trip). L1 serves hot keys; L2 serves all keys.
How do I keep L1 consistent across instances?
Redis pub/sub: on write, publish the key and every subscribed instance drops it from L1. Without it, L1 converges through its TTL.
When is a two-level cache not worth it?
Single-instance app, uniform access with no hot keys, or Redis latency already under ~1ms. In all three cases L1 adds complexity without buying you much.
How do I size L1?
The top 1% of keys usually drive 50–80% of reads. Measure access frequency, size L1 for the hot set, start at 1000 entries, and tune against the hit ratio.
Related Resources
Read-Through Cache Pattern
A transparent cache layer that intercepts read requests, fetches from the data source on miss, and populates the cache automatically.
PatternCache Invalidation Pattern
Strategies for keeping cached data fresh: TTL expiration, explicit invalidation, write-through, and event-driven cache eviction.
PatternCache-Aside Pattern
Load data into the cache on demand from the backing store. A caching pattern that gives the application full control over what and when to cache.
PatternCache Stampede Prevention Pattern
Prevent thundering herd cache misses with locks, single-flight, stale-while-revalidate and early refresh strategies that keep the database safe.