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

Why Caching

Memory beats disk.

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

Shoply's home page shows the same twenty best sellers to every visitor. Asking the database for them a thousand times a second is wasteful. A cache keeps a copy of the answer in fast memory.

Why Caching
From the video: Why Caching
  • Same answer, every visitor
  • Wasteful database calls
  • Keep a copy in memory

The power of a cache

Here's a slow function that pretends to query a database, taking a tenth of a second. We call it five times, with and without a cache. Python's l r u cache decorator remembers answers. Run it. Without a cache, five calls take half a second. With it, only the first call is slow, and the rest are instant.

cache.pypython
import time
from functools import lru_cache

def best_sellers():
    time.sleep(0.1)  # pretend database query
    return ["mug", "pot", "towel"]

cached = lru_cache(maxsize=1)(best_sellers)

for name, fn in [("no cache", best_sellers), ("cached", cached)]:
    start = time.perf_counter()
    for _ in range(5):
        fn()
    print(f"{name:>8}: {time.perf_counter() - start:.2f} s")
Output
no cache: 0.52 s
  cached: 0.10 s

What caching gives

Caching gives three big wins. Faster responses, because memory is far quicker than a database. Less load on the database, so it can serve the requests that really need it. And lower cost. The price is that cached data can be out of date, which is the main challenge of caching.

keyvalue
Speedmemory is fast
Less DB loadfewer queries
Lower costsmaller database
Catchdata can be stale

Summary

A cache keeps answers in fast memory, cutting latency and database load. The challenge is keeping it fresh. Next, the most common way to use a cache.

Key takeaways
  • Memory is fast
  • Fewer DB queries
  • Watch for staleness
Next up: Cache-Aside — the most common pattern