Module 4 · Caching and performanceLesson 35 of 886 minIntermediate

The cache-aside pattern

The app checks the cache first, fills it on a miss, and clears it on a write. The database stays the source of truth.

Try it

Play the miss, then the hit, then the write. Notice the write deletes the cached value instead of updating it.

Cache-aside (also called lazy loading) is the most common caching pattern. The application manages the cache itself; the cache and database don't know about each other.

Reading

value = cache.get(key)
if value is missing:
    value = db.query(key)
    cache.set(key, value, ttl=10 minutes)
return value

Writing

db.update(key, new_value)
cache.delete(key)

Why it's popular

  • Only useful data is cached: things nobody reads never take up space.
  • Resilient: if the cache goes down, the app still works, just slower.
  • Simple: any cache, any database, a few lines of code.

Its weak spots

  • First reads are slow: every key misses once. After a deploy or cache restart, the database takes a burst of misses. Some teams warm the cache by preloading popular keys.
  • A short window of staleness: between the database update and the cache delete, readers may see the old value. Usually fine.
  • A sneaky race: a slow reader can fetch an old value, then a writer updates and deletes, then the slow reader writes its old value into the cache. A TTL on every key limits how long such mistakes last.

Compared to other patterns

  • Read-through: the cache itself loads from the database on a miss. Same idea, but the logic lives in the cache layer.
  • Write-through and write-back: the cache sits in the write path. That's the next lesson.

Quick check

In cache-aside, why delete the cached value on a write instead of updating it?