Why Caching
Memory beats disk.
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.

- 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.
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")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.
| key | value |
|---|---|
| Speed | memory is fast |
| Less DB load | fewer queries |
| Lower cost | smaller database |
| Catch | data 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