Module 4 · Caching and performanceLesson 33 of 886 minBeginner

What is caching?

A cache keeps a copy of answers you'll need again somewhere much faster, so you don't redo slow work.

Try it

Turn the cache on and watch database reads drop and hits climb. Then shrink the cache size and see how few keys it takes to catch most requests.

A cache is a small, fast store that keeps copies of data you've already fetched or computed, so the next request can skip the slow part.

Typical speeds:

  • Reading from memory (a cache like Redis): well under 1 ms
  • A database query: a few ms to hundreds of ms
  • Calling another service across the world: hundreds of ms

Hits and misses

  • Hit: the answer is in the cache. Fast.
  • Miss: it isn't. Go to the source, return the answer, and usually store it for next time.

The hit rate (hits divided by all requests) is the number to watch. A 90% hit rate means the database sees only one request in ten.

Why it works

Traffic is lopsided. A small set of items is wanted again and again: the home page, the top 100 products, today's popular posts. This pattern (often called a power law, or "the 80/20 rule") is why a cache much smaller than your data can still catch most requests.

Where caches live

Caching happens at every layer:

  • Browser: images, scripts and pages on the user's device.
  • CDN: files at servers near the user.
  • App memory: a small in-process cache per server.
  • Shared cache: Redis or Memcached, shared by all servers.
  • Database: its own buffer cache of recently used pages.

The catch

A cache holds copies. When the real data changes, copies become stale. Every caching design has to answer: how stale is acceptable, and how do we throw old copies away? The rest of this module is about exactly that.

And when the cache is full, something must go. The most common rule is LRU (least recently used): evict what nobody has asked for in the longest time.

Quick check

Why can a cache holding only 10% of your items answer most requests?