Skip to main content
CodingMarble

Programming fundamentals

Caching Explained for Web Developers: Layers and Headers

Caching stores a copy of an expensive result close to whoever needs it next, so repeat requests skip the slow work. The hard parts are deciding how long a copy stays valid and removing it when the original changes, so cache only what is read often, changes rarely and is safe to share.

By CodingMarble · Published · 4 min read

A blue and white laptop screen
Photo: Philipp Katzenberger on Unsplash

What caching trades away

A cache keeps a saved answer so the next request for the same thing is cheap. Computing a page, running a database query or downloading an image from a distant server all take time; reading a stored copy from memory or the user's own disk takes far less. The benefit is speed and reduced load on your servers.

The cost is that a copy can become wrong. The moment the original changes, every cached copy is stale until it expires or is removed. Every caching decision is therefore a bargain between freshness and speed, and the right answer depends on how bad it is to show slightly old data. A product photo can be old for a year; an account balance should not be old for a second.

The layers a request passes through

A single page view can hit several caches, nearest to the user first. The browser cache stores files on the visitor's device and is the fastest of all, because no network request happens when a fresh copy exists. A CDN cache sits at servers around the world and answers for many visitors, so far-away users do not hit your origin. A server-side or application cache, often an in-memory store or a reverse proxy in front of your app, saves rendered pages or query results. At the bottom, the database has its own internal caches.

Each layer has its own rules, which is why debugging can be confusing: the stale thing you are looking at may be in any of them. When something looks outdated, work from the outside in. Check the browser with developer tools, then the CDN response headers, then your application cache.

Cache keys and time to live

A cache is essentially a lookup table, and the cache key is what identifies an entry. For a browser or CDN the key is mostly the URL, sometimes combined with headers named in Vary, such as Accept-Encoding. For an application cache you choose the key yourself, and the golden rule is that the key must include everything that changes the answer. If a price depends on currency, put the currency in the key, otherwise one visitor's result leaks to another.

Time to live, or TTL, is how long an entry is considered fresh before it must be refetched or revalidated. A short TTL limits how stale data can get but sends more traffic to the origin. A long TTL is cheap and fast but leaves stale data for longer. Pick the TTL from the business answer to how stale can this be, not from habit.

Cache-Control headers in practice

HTTP lets your server tell browsers and CDNs how to cache a response through the Cache-Control header. max-age=N says the response is fresh for N seconds. public allows shared caches such as a CDN to store it, while private restricts it to the user's own browser, which matters for personalised responses. no-store tells caches not to keep the response at all, the right choice for sensitive pages. no-cache is often misread: it means the copy may be stored but must be revalidated with the server before reuse.

stale-while-revalidate=N lets a cache serve a stale copy immediately for up to N seconds after it expires, while it fetches a fresh one in the background. Visitors get a fast answer and the next visitor gets the updated one. Support for this directive varies between browsers and CDNs, so check current documentation for the layers you rely on.

Prompt· Three typical response header sets
# Fingerprinted asset such as app.4f2a9c.js: cache for a year
Cache-Control: public, max-age=31536000, immutable

# HTML page: always check with the server, reuse if unchanged
Cache-Control: no-cache

# Account page with personal data: never store
Cache-Control: no-store

Fingerprinting is what makes long lifetimes safe. If the file name contains a hash of its content, a changed file gets a new URL, so the old long-lived copy is simply never requested again. This sidesteps invalidation for static assets.

Invalidation, the hard part

Deciding when a cached copy is no longer valid is the genuinely difficult problem. There are three broad strategies. Wait for the TTL to expire and accept some staleness. Change the key, as fingerprinted file names do. Or actively purge the entry when the data changes, which gives the freshest results but requires every code path that modifies the data to remember to purge it, and a forgotten path produces stale pages that are hard to trace.

CDNs usually offer a purge or invalidate feature, but purging propagates across many locations and is not always instant, so do not design something that depends on it being immediate. Where freshness really matters, keep cacheable content separate from the dynamic parts and fetch the dynamic parts live.

An application cache and the stampede problem

In application code the usual pattern is cache-aside: look in the cache, and on a miss compute the value, store it with a TTL and return it. A problem appears when a popular entry expires and hundreds of requests all miss at once and all hit the database to rebuild it. This is a cache stampede. A simple defence is to let concurrent callers share one in-flight computation.

JavaScript· A tiny TTL cache that shares one in-flight load per key
const store = new Map(); // key -> { value, expires }
const inflight = new Map(); // key -> Promise

export async function cached(key, ttlMs, load) {
  const hit = store.get(key);
  if (hit && hit.expires > Date.now()) return hit.value;

  if (inflight.has(key)) return inflight.get(key);

  const promise = load()
    .then((value) => {
      store.set(key, { value, expires: Date.now() + ttlMs });
      return value;
    })
    .finally(() => inflight.delete(key));

  inflight.set(key, promise);
  return promise;
}

This lives in one process only. With several servers each keeps its own copy, so use a shared store when entries must be consistent, and consider adding a little random variation to TTLs so many keys do not expire at the same instant.

Deciding what to cache

Good candidates are read far more often than written, expensive to produce, identical for many users and tolerant of some staleness: images, scripts, public pages, reference data, the results of heavy reports. Poor candidates are personal data, anything tied to a login, and values that must be exact at read time such as stock for the last item or a payment status.

Practical tip: open developer tools, go to the Network tab and reload twice. Look at the Size column for from disk cache or memory cache and click a request to read its Cache-Control, Age and any CDN headers. Verifying what your own site actually sends is quicker and more reliable than reasoning about what you think you configured.

Need this built properly for your business?

CodingMarble is a remote studio in India that builds websites, apps and games on fixed packages with the scope written down before payment. Try the free tools we run, or start a project when you are ready.