Course contents · Lesson 8 of 19

What Is Caching? Why Fast Apps Keep Copies Nearby

Scaling and Capacity · Lesson 8 of 19 · 10 min Engineer

Open a busy shop's home page and it takes a moment to appear. Reload it and it shows up almost at once, because a copy was kept somewhere along the way. So what is caching, and why does it make apps fast? This lesson covers where copies live, how they go stale, and how they help or hurt reliability.

Hits, misses and the hit ratio

A cache is a small, fast store that keeps copies of data so later requests can skip the origin, where the original data lives: usually the database for an app's cache, and your own servers for a CDN, which you meet below. Each copy is stored under a key, a unique name such as product:42.

A cache hit means the copy is there and is returned at once. A cache miss means it is not, so the app reads the origin, stores the result with a time-to-live (TTL), a lifetime explained below, and then answers. This pattern is called cache-aside, or lazy loading, because the cache fills only with data someone asked for. In the flowchart, notice that each miss turns the next request for that key into a hit.

Flowchart. A request arrives for the key product:42 and the app asks: is it in the cache? On a hit it returns the copy with no database work. On a miss it reads the database, the slower origin, stores the result with a TTL using SET product:42 with EX 300, and returns the result, a little slower than a hit. A dashed arrow shows the next request for this key is a hit until the TTL ends. A side panel defines hit ratio as hits divided by hits plus misses: illustratively, 950 hits and 50 misses in 1,000 lookups is a 95 percent hit ratio, so the database sees only 50 reads
A miss pays once so that the next requests for the same key skip the database.

The hit ratio is hits divided by all lookups, hits plus misses. With illustrative numbers, 950 hits in 1,000 is 95 percent, so the database answers 50 reads instead of 1,000. Small changes matter: a fall to 90 percent doubles the misses, and the database's work, to 100 per 1,000. This is how caching takes reads off a database, as lesson 7 promised.

Where caches live

A request tries the nearest copy first and travels further only on a miss:

  • Browser cache: files kept on the user's device and reused for as long as the server's Cache-Control header allows. A header is a named line of extra information sent with a response.
  • CDN: a content delivery network is a fleet of caching servers, called edge servers, in many cities near users. Cloudflare and Amazon CloudFront are examples.
  • Application cache: the app's own memory, fastest but private to each instance and lost on restart, or Redis or Memcached, in-memory key-value stores that all instances share over the network.
  • Database buffer: recently used blocks of data kept in memory, called the buffer pool in MySQL and shared buffers in PostgreSQL, so popular rows skip the disk.

In the diagram, notice the big jump: a Redis lookup takes well under a millisecond, but reaching it means a trip across the internet.

Layer diagram with illustrative times the user waits if each layer answers. Browser cache, on the user's device, holds images, scripts and styles: about 0 ms. CDN edge, servers in cities near users, holds public pages, images and video: about 20 ms. App cache, app memory or Redis, holds query results and sessions: about 100 ms. Database, with a buffer in memory and then disk, holds rows read recently: about 150 ms or more. A miss at each layer passes the request down to the next. A note says the jump at the app is distance, because the Redis lookup itself takes under 1 ms
Each layer nearer the user saves a longer trip, so the nearest correct copy wins.

Personal pages, such as a basket, are marked private or no-store in Cache-Control, so a CDN never serves one user's page to another.

Expiry and invalidation: keeping copies fresh

A copy is stale, out of date, once the origin changes. The simplest guard is the TTL, set when the copy is stored; after it, the copy expires and the next request is a miss. In Redis, SET product:42 "…" EX 300 keeps a copy for 300 seconds; in HTTP, Cache-Control: max-age=300 says the same.

A TTL bounds staleness: at 300 seconds, a copy is never more than about five minutes behind. A long TTL gives more hits but older data, a short one fresher data but more origin load. A product photo can live for days, a stock count seconds. Layers add up, too: with five-minute TTLs in both the CDN and the app cache, a page can be nearly ten minutes behind.

To show changes sooner, you invalidate: delete or overwrite the cached copy when the data changes, such as deleting product:42 right after a new price is saved. The hard part is finding every affected copy: search results, category pages, CDN copies that need a purge request, and browser copies you cannot reach. Teams do both: invalidate on writes, with a TTL as a safety net.

When caches go wrong: cold starts and stampedes

Two more risks come from misses arriving in a crowd. A cold cache is an empty one: a cache held only in memory starts empty after a restart, and a rolling deploy empties each app instance's memory in turn. Until it fills, nearly every request misses and the origin takes the full load. Restart cache servers one at a time, at a quiet hour, or warm a new one by loading popular keys before it takes traffic.

A cache stampede, or thundering herd, happens when a popular key expires and many requests miss at once, each sending the same query before any has refilled the cache. In the timeline, notice that the top lane sends 1,000 queries and the bottom lane one.

Timeline with illustrative numbers: a popular key expires at 0 seconds and 1,000 requests miss within the next second. Without protection, each miss asks the database, so 1,000 identical queries hit the database, with a warning sign. With one request refilling, the first miss takes a lock and its 1 query refills the cache, while 999 others wait or get the old copy, so the database load stays flat
The same expiry costs 1,000 queries or one, depending on whether misses can pile up.

Common fixes, often combined:

  • One refill at a time: the first miss takes a short lock and queries the database; the rest wait briefly or use the old copy. Many CDNs call this request collapsing.
  • Serve stale while refreshing: return the expired copy for a few seconds while one request fetches a new one, which HTTP's stale-while-revalidate directive asks for.
  • Jitter: spread TTLs randomly, such as 300 seconds plus up to 30, so keys stored together do not expire together.

Caching and reliability

A cache also helps reliability. It absorbs load and hides slow dependencies: if, for example, a pricing service takes two seconds, a cached price returns in about a millisecond, and the last known price keeps pages working while that service is briefly down.

The danger is a service that cannot run without its cache. At a 95 percent hit ratio, the database sees 50 reads in every 1,000; if the cache fails or goes cold, it sees all 1,000, twenty times its usual load. A database sized for the cached load falls over. So:

  • Know what the origin can take with an empty cache, and count the cache in your capacity plan (lesson 10).
  • Give cache calls short timeouts, so a slow cache becomes misses, not hung requests.
  • If the origin cannot carry everything, shed load: quickly reject a share of requests with an error rather than let them all time out.
  • Alert on the hit ratio, and avoid relying on one cache server, a single point of failure of the kind lesson 11 removes.

Check yourself

The hit ratio falls from 98 to 94 percent after a release, and the database starts to struggle. Why can a four-point drop hurt so much?

The database serves the misses, which tripled from 2 to 6 per 100 reads, so its load tripled.

A price change takes up to an hour to appear on product pages. What most likely sets that delay, and how could it shrink to seconds?

A TTL of about an hour, the longest a stale copy can be served. Deleting the cached copy when the price is saved shows the change on the next read.

You restart every cache server at once at peak time, and the database falls over, though it handled the same traffic yesterday. Why?

The caches came back cold, so nearly every request missed and the database took the full load instead of its small share. Restart one at a time, off-peak, or warm them first.

Go deeper