AI Hints
Home›System Design Tutorial›Caching Basics
System Design · Lesson 56 of 120

Cache-Aside

The most common pattern.

⏱ 2 min read▶ Video at 1:06:36🎓 Free
Watch this lesson in the System Design courseWatch on YouTube ↗Full System Design course

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.

Cache-Aside
From the video: Cache-Aside
  • 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.

  1. Look in cache
  2. Hit? Return
  3. Miss: read DB
  4. Store in cache
  5. Return
Read with cache-aside
From the video: Read with cache-aside

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.

aside.pypython
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%}")
Output
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
Next up: Write Strategies — through, back, around