← Lessons

quiz vs the machine

Silver1050

System Design

The Cache Aside Pattern

Letting the application, not the cache, decide when to load and store data.

4 min read · intro · beat Silver to climb

What it is

In the cache aside pattern the application code talks to both the cache and the database directly. The cache is a passive store that knows nothing about the database. This is also called lazy loading because data is only cached when it is first requested.

The read flow

  • Look in the cache for the key.
  • On a cache hit, return the cached value.
  • On a cache miss, read from the database, write the value into the cache, then return it.

The write flow

Writes go straight to the database. The cached copy is usually invalidated or deleted so the next read repopulates it with fresh data.

Trade offs

  • Only requested data is cached, so memory holds the working set.
  • The first read after a miss is slow, paying both a database and a cache write.
  • Stale data is possible if a write updates the database but the invalidation is missed.

Key idea

Cache aside puts the application in charge of loading on miss and invalidating on write, keeping the cache simple and independent.

Check yourself

Answer to earn rating on the learn ladder.

1. What happens on a cache miss in the cache aside pattern?

2. Why is cache aside called lazy loading?