Cache-aside
Also called: lazy loading, look-aside cache, lazy caching.
Read a product twice: the first read misses the cache and goes to the database, the second is served from Redis.
Cache hits: 0 · Database reads: 0
Nothing read yet. The cache starts empty.
The app reads from a cache such as Redis first; on a miss it reads the database, stores the result in the cache and returns it. On a write it updates the database and then deletes the cached key, so the next read loads fresh data. The cache only ever holds data someone asked for.
Say it in a prompt
Add a cache-aside layer with Redis for GET /products/:id: read the key product:{id} first; on a miss, load the row from Postgres, store it with a 300-second TTL and return it. On update or delete, write to Postgres first, then delete the key. If Redis is down, read straight from Postgres. Vague vs precise prompt
Vague prompt
make the product page faster when lots of people open it Typical resultAdds an in-memory Map inside one server with no expiry. The other servers still hit the database, and edits don't show until a restart.
Precise prompt
Add cache-aside with Redis for GET /products/:id: read product:{id} first; on a miss load it from Postgres, cache it for 300s (TTL) and return it. On update, write Postgres, then delete the key. Typical resultRepeat reads skip Postgres, the database sees at most one query per product every 5 minutes plus one after each edit, and an edit shows on the next read.
Seen on
- Azure Architecture Center: Documents the Cache-Aside pattern: try the cache, load from the data store on a miss and add the item to the cache, and invalidate the cached item when the data changes.
- Amazon ElastiCache: Calls the same strategy lazy loading: data goes into the cache only when it is requested, and adding a TTL keeps it from getting too stale.
You might describe it as
- check Redis first, then the database
- only cache what people actually ask for
- keep a copy of hot rows so the database gets fewer reads
Not to be confused with
- TTL (time to live)
Cache-aside decides when data goes into the cache (on a miss); a TTL decides when it drops out.
- CDN
Cache-aside is a cache your app code fills from the database; a CDN caches whole HTTP responses on servers near the user.