Cache-Aside
The most common pattern.
The most common caching pattern is called cache aside, or lazy loading. The application checks the cache first, and only goes to the database when it must.

- Check the cache first
- Database only if needed
- Cache-aside
Read with cache-aside
Here's the flow. The app looks for the key in the cache. If it's there, that's a cache hit, and we return it. If it's missing, that's a miss. The app reads from the database, stores the result in the cache, and returns it. Next time, it's a hit.
- Look in cache
- Hit? Return
- Miss: read DB
- Store in cache
- Return

Hits and misses
Here's cache aside in code, with a dictionary as the cache. We request products, some of them more than once. Run it. The first request for each product is a miss, and goes to the database. Repeats are hits. The hit rate, here seventy percent, tells you how well the cache is working.
db = {1: "mug", 2: "pot", 3: "towel"}
cache, hits, misses = {}, 0, 0
def get_product(pid):
global hits, misses
if pid in cache:
hits += 1
return cache[pid]
misses += 1
value = db[pid] # slow database read
cache[pid] = value
return value
for pid in [1, 2, 1, 1, 3, 2, 1, 1, 2, 1]:
get_product(pid)
print(f"hits {hits}, misses {misses}, hit rate {hits / (hits + misses):.0%}")hits 7, misses 3, hit rate 70%
Summary
Cache aside checks the cache first, and fills it from the database on a miss. Watch the hit rate. Next, what to do when data is written.
Key takeaways- Check cache
- Miss: load and store
- Track hit rate