The cache-aside pattern
The cache aside pattern (lazy loading) in Node.js with Redis: read the cache, load on a miss, delete on write, and avoid the stampede and stale-write races.
The cache-aside pattern, also called lazy loading, is a caching strategy where the application checks the cache first, loads the data from the database only on a miss, and stores what it loaded in the cache with a time to live. Writes go to the database, followed by deleting the cached copy. The cache sits "aside" from the database: the application, not the cache, moves data between them.
Cache-aside is the most widely used caching strategy because it caches only what is actually read, keeps the database as the source of truth, and keeps working when the cache is down.
Level: zero to one · You need: What is caching? and Caching strategies
How cache-aside works
On a read
- Look up the key in the cache.
- Cache hit: return the cached value.
- Cache miss: query the database, write the result to the cache with a TTL, return it.
On a write
- Update the database.
- After the commit, delete the cache key. The next read misses and loads the new row.
Because data enters the cache only when a request asks for it, this style is called lazy loading. A lazy loading cache starts empty and fills itself, so the first read of every key is slow and later reads are fast.
Redis cache-aside in Node.js
This version uses ioredis and stores values as JSON for five minutes.
import { Redis } from 'ioredis'
import { db, type User } from './db.ts'
const redis = new Redis(process.env.REDIS_URL ?? 'redis://localhost:6379')
const TTL_SECONDS = 300
export async function getUser(id: string): Promise<User | null> {
const key = `user:${id}`
const cached = await redis.get(key)
if (cached !== null) return JSON.parse(cached) as User // hit
const user = await db.users.find(id) // miss
if (user) await redis.set(key, JSON.stringify(user), 'EX', TTL_SECONDS)
return user
}
export async function updateUser(id: string, changes: Partial<User>): Promise<void> {
await db.users.update(id, changes) // 1. the database is the source of truth
await redis.del(`user:${id}`) // 2. drop the copy after the commit
}This is correct for a small service. Production adds four problems the code above does not handle.
Four problems with hand-written cache-aside
1. Cache stampede
When a popular key expires, every request that arrives before the first load finishes also misses, and each one queries the database. A key read 2,000 times a second with a 100 ms query sends about 200 identical queries at once. See cache stampede.
The fix inside one process is request coalescing: the first miss starts the load, and every other caller for the same key waits for that same promise instead of starting its own.
import { getUser } from './users.ts'
import type { User } from './db.ts'
const inflight = new Map<string, Promise<User | null>>()
export function getUserCoalesced(id: string): Promise<User | null> {
const pending = inflight.get(id)
if (pending) return pending // join the load that is already running
const load = getUser(id).finally(() => inflight.delete(id))
inflight.set(id, load)
return load
}This stops duplicate loads inside one server only. Ten servers still send ten queries, which is the next level of the problem.
2. A slow read can undo a delete
- Request A misses and starts loading the old row.
- Request B updates the row and deletes the key.
- Request A finishes and writes the old row into the cache.
The cache now serves stale data until the TTL ends. The usual defenses are short TTLs, versioned keys, or a cache that fences loads against deletes.
3. Redis is down
If redis.get throws, every request fails even though the database is fine. Cache reads should fail open: treat a cache error as a miss and go to the database.
4. Every server keeps its own copy
If you add an in-memory layer in front of Redis to save the network round trip, each server has its own copy, and redis.del does not reach them. Every server must hear about the delete, usually over Pub/Sub.
The same pattern in one call
lazy-layers-cache implements cache-aside as a read-through call that handles all four problems:
import { setupCache } from 'lazy-layers-cache'
import { db, type User } from './db.ts'
const cache = await setupCache<string, User>({
namespace: 'users-api',
redis: { required: true }, // reads REDIS_URL
ttlMs: 300_000,
})
export function getUser(id: string): Promise<User | undefined> {
return cache.getOrSet(`user:${id}`, () => db.users.find(id))
}
export async function updateUser(id: string, changes: Partial<User>): Promise<void> {
await db.users.update(id, changes)
await cache.invalidate(`user:${id}`) // memory on every server, Redis, and in-flight loads
}What getOrSet adds to the hand-written version:
| Problem | What happens inside getOrSet |
|---|---|
| Stampede | Concurrent misses in one process share one loader call; across servers, a Redis lease lets one server load while the others wait for its value. In a recorded run, 1,200 callers on 6 servers caused 20 loads. |
| Slow read after a delete | invalidate also drops the key's in-flight load, and every delete advances a per-key generation, so peers ignore a value loaded before it. With versioning: { enabled: true }, an old value is stored under an old key version that reads no longer address. |
| Redis down | Reads fail open to memory and the loader. In a recorded run, a 4 s Redis freeze caused 0 errors. |
| Copies on many servers | invalidate publishes the delete on an event bus, so every server drops its in-memory copy. |
| A missing row | undefined is remembered for 10 s by default (negative caching), so a missing ID does not hit the database on every request. |
For the full picture of what invalidate does, read invalidation and lazy loading.
Next lesson: cache invalidation.
Further reading
- Microsoft, Cache-Aside pattern: the pattern with its context, problem and solution, from a vendor's architecture guide.
- AWS ElastiCache, caching strategies: describes lazy loading step by step: check the cache, read the data store on a miss, write the result to the cache.
- Nishtala et al., Scaling Memcache at Facebook, NSDI 2013: calls its cache a demand-filled look-aside cache and explains why writes delete the cached value instead of updating it.
- Uber, CacheFront: a cache-aside read path in front of a large database, with Redis and a 5 minute default TTL.
Questions
What is the cache-aside pattern?
Cache-aside is a caching strategy in which the application talks to both the cache and the database. On a read, it checks the cache; on a miss, it loads the data from the database, stores it in the cache with a TTL, and returns it. On a write, it updates the database and deletes the cached copy.
Is cache-aside the same as lazy loading?
Yes. Cache-aside is also called lazy loading, because data enters the cache only when a request first needs it, not ahead of time. AWS documentation for ElastiCache uses the name lazy loading.
What is the difference between cache-aside and read-through?
In cache-aside the application code does the check, the database call and the cache write. In read-through the cache does them, given a loader function. The data flow is the same; read-through moves it into one place where concurrent misses can share a single load.
What are the disadvantages of cache-aside?
Every miss costs three trips (cache, database, cache). Data can be stale until the TTL ends or the key is invalidated. Many requests missing the same key at once all query the database, which is a cache stampede. And a slow read racing a write can put an old value back after the delete.
Should I update or delete the cache on write in cache-aside?
Delete it. Two concurrent writes can update the database in one order and the cache in the other, leaving the cache wrong until the TTL. Deleting always leaves the cache empty, and the next read loads the committed value.
What is request coalescing in a cache?
Request coalescing means that when many callers miss on the same key at once, only the first one runs the loader and the rest wait for its result. It turns 200 identical database queries into one inside a process, and it is the first defense against a cache stampede.
Caching strategies and how to choose one
Caching strategies compared: cache-aside, read-through, write-through, write-back, write-around and refresh-ahead. See how each works and which to pick.
Cache invalidation for beginners
Cache invalidation explained: TTL expiry, delete on write, versioned keys, pattern and tag invalidation, and clearing copies on many servers, with TypeScript.