Where caches sit

Topic 1 of 9 in Week 4: Caching, queues and content delivery9 min readBeginnerFree course

Overview

A cache stores the result of expensive work so that the next request can reuse it. Caching is the single most effective tool for making read-heavy systems fast and cheap, and it can happen at many points along a request’s path. This lesson maps those points and what each is good for. The following lessons cover how to fill, expire and protect caches.

The layers

Caches at every layer, from the user inward: the browser HTTP cache at about 0 milliseconds, a CDN edge for static files and some API responses at about 10 milliseconds, the application’s local memory at about 0.1 milliseconds, a shared Redis cache at about 1 millisecond, and the database’s buffer pool at about 5 to 50 milliseconds per query. Closer to the user is faster and cheaper but harder to invalidate. Browser and CDN caches are controlled with Cache-Control headers and can’t be purged per user; a local in-process cache is fastest but each server has its own copy that can go stale; a shared cache gives one copy for all servers a network hop away; and the database caches hot pages in memory too, so a cache in front helps only if it saves real work.

Browser cache

Browsers store responses according to HTTP headers:

  • Cache-Control: max-age=31536000, immutable for files whose name changes when their content changes (app.3f9a1c.js).
  • Cache-Control: no-cache plus an ETag for pages that must be checked each time: the browser asks “has it changed?” and gets a tiny 304 Not Modified if not.
  • Cache-Control: private for responses that belong to one user, so shared caches never store them.

A browser hit costs nothing: no network at all.

CDN

A content delivery network caches responses in edge locations near users. Ideal for images, video, scripts and stylesheets, and also for API responses that are the same for many users (a product page, a public article). CDNs can be purged when content changes, but purges take seconds to spread and you can’t purge one user’s copy.

Reverse proxy or gateway cache

NGINX, Varnish or an API gateway can cache whole responses in front of your app servers. Similar to a CDN but inside your network.

Application memory (local cache)

Each app server can keep a small in-process cache (a hash map with a size limit and expiry). It’s the fastest option, with no network hop, which is perfect for configuration, feature flags and very hot reference data. The catch: every server has its own copy, so after a change different servers may return different values until their copies expire.

Shared distributed cache

Redis or Memcached clusters hold one shared copy for all servers. A lookup takes about a millisecond over the network. This is what designs usually mean by “add a cache”: sessions, user profiles, computed feeds, rendered fragments, rate-limit counters.

The database’s own cache

Databases keep recently used pages in memory (the buffer pool). If the working set fits in RAM, many queries are already fast. A cache in front of the database pays off when it saves real work: complex queries, joins and aggregations, or simply the load of tens of thousands of identical reads per second.

What to cache

Good candidates:

  • read often, changed rarely (product details, profiles, configuration),
  • expensive to compute (feeds, recommendations, search results, aggregates),
  • OK to be slightly stale.

Poor candidates:

  • data that must always be exact at read time (account balances during a transfer, remaining stock at checkout),
  • data read once (a one-off report),
  • data unique to each request.

Split shared from personal

A page that mixes public and personal content can’t be cached as a whole by a CDN. Split it: serve the shared part (the article) from a cacheable URL and fetch the personal part (the user’s name, their recommendations) separately. This one change often moves most traffic to the CDN.

Measure the hit rate

The hit rate is the share of lookups answered by the cache. If it’s 95%, the backend sees 1 in 20 requests; at 80%, it sees 1 in 5, four times as many. Watch hit rate, memory use and evictions, and size the cache for the working set, not the whole dataset.

In an interview

Mention caching at the layers that matter for the problem: “Images and video through a CDN; profiles and feeds in Redis with cache-aside; static assets with hashed file names and year-long cache headers.” Then explain what happens when cached data changes, which is the next lesson.

Recap

Caches sit in the browser, the CDN, proxies, application memory, shared stores and the database. Closer to the user is faster and cheaper but harder to invalidate. Cache data that’s read often, expensive and tolerant of staleness; keep personal and shared content apart; and watch the hit rate to know whether a cache is paying for itself.

Exercise

Place the caches

A news website shows article pages (the same for everyone, updated a few times an hour), a personalised 'Recommended for you' box, and a header showing the signed-in user's name. It has 5 million readers a day. For each piece, say which cache layer(s) you'd use and how long items should live: (a) article text and images, (b) the CSS and JavaScript bundle, (c) the recommendations box, (d) the user's name in the header.

Text
(a) Articles and images:
(b) CSS/JS bundle:
(c) Recommendations:
(d) User name:

Summary

  • Caches exist at every layer: browser, CDN, reverse proxy, application memory, shared caches and the database's own memory.
  • The closer a cache is to the user, the faster and cheaper the hit — and the harder it is to invalidate.
  • HTTP caching is controlled with Cache-Control, ETag and versioned URLs.
  • Local in-process caches are fastest but each server keeps its own, possibly different, copy; shared caches such as Redis give one copy for all servers.
  • Keep shared content separate from personalised content so the shared part stays cacheable.