Technology

Caching strategies for web applications, and how to invalidate them

Caching is easy to add and hard to get right. A practical look at each cache layer, the common patterns, and how to keep cached data correct after it changes.

  • By Systronium Team, Engineering & Delivery
  • November 12, 2026
A request flowing from browser to CDN, application cache and database, with a cache hit returning early

Caching is usually the quickest way to make a slow system fast. It is also one of the easiest ways to show people the wrong data. The difference between the two comes down almost entirely to invalidation: knowing when a cached value is no longer true, and what to do about it.

This post walks through the layers where caching happens in a typical web application, the patterns used at each one, and the invalidation approaches that hold up in production.

Where caching happens

A single page view can pass through several caches before it reaches your database:

  1. The browser cache, controlled by the HTTP headers you send.
  2. A CDN or reverse proxy, which serves cached responses close to the visitor.
  3. An application cache, such as Redis or an in-process memory cache, holding computed results.
  4. The database's own buffers, which keep frequently used pages in memory.

Each layer is cheaper and closer to the user than the one behind it, and each is also harder to control once a value is stored. You can delete a Redis key instantly. You cannot reach into a visitor's browser and remove what it has kept.

HTTP caching: get the headers right

Most of the benefit of browser and CDN caching comes from a handful of Cache-Control directives.

Static assets with hashed filenames, such as app.3f9a1c.js, never change at the same URL, so they can be cached for a year:

Cache-Control: public, max-age=31536000, immutable

When the file changes, the build produces a new filename, and the old one is simply never requested again. That is the easiest invalidation strategy there is: change the URL.

HTML pages and API responses change in place, so they need shorter lifetimes. A common setup lets the CDN cache for a few minutes while the browser always checks back:

Cache-Control: public, max-age=0, s-maxage=300, stale-while-revalidate=60

max-age applies to the browser, s-maxage applies to shared caches like CDNs, and stale-while-revalidate lets a cache serve a slightly old copy while it fetches a fresh one in the background, so no visitor has to wait for the refresh.

Two directives are often confused:

  • no-cache means "you may store this, but check with the server before using it". Paired with an ETag, that check is cheap: the server answers 304 Not Modified with no body.
  • no-store means "never store this anywhere". Use it for responses containing personal or sensitive data.

Never let a shared cache store personal data. A response that depends on who is logged in must be marked private or no-store, or a CDN can hand one user's account page to the next visitor. This mistake has caused real data leaks, and it usually begins with someone adding caching to a slow endpoint without checking whether the response varies by user.

Application caching patterns

Inside the application, four patterns cover most needs.

Cache-aside. The application checks the cache first. On a miss, it reads from the database, stores the result in the cache and returns it. This is the most common pattern because it is simple and only caches what is actually requested.

async function getProduct(id: string) {
  const key = `product:${id}`;
  const cached = await redis.get(key);
  if (cached) return JSON.parse(cached);

  const product = await db.products.findById(id);
  if (product) {
    await redis.set(key, JSON.stringify(product), 'EX', 600);
  }
  return product;
}

Read-through. The same idea, except the cache layer loads missing values itself, so application code only ever talks to the cache.

Write-through. Every write goes to the database and the cache together, so the cache always holds the latest value. Reads are fast, at the cost of slower writes and caching some data that may never be read.

Write-behind. Writes land in the cache first and are flushed to the database later in batches. It is very fast, but data can be lost if the cache fails before a flush. It suits counters and metrics, and rarely anything involving money.

Invalidation strategies that work

There is no single right answer, but there is a sensible order to consider them in.

1. Expire with a TTL. Give every cached value a time to live, even when you also invalidate it explicitly. The TTL is your safety net: if an invalidation is ever missed, the stale value still disappears on its own. Choose it by asking how long it would be acceptable to show old data. For a product description, ten minutes is probably fine. For the stock level at checkout, it is not.

2. Delete on write. When the underlying data changes, delete the cache key in the same code path that writes to the database. Delete rather than update. The next read repopulates the cache from the source of truth, which avoids races where two concurrent writers leave the cache holding the older value.

Do the delete after the database transaction commits, not before. If you delete first, a read that sneaks in between the delete and the commit can put the old value straight back into the cache.

3. Version your keys. Include a version number in the key, for example product:42:v7, and increase it whenever the record changes. Old entries are never read again and expire on their own. This works well for data that is expensive to find and delete entry by entry.

4. Tag related entries. A single product change might affect its detail page, three category listings and the search results. Tag each cache entry with the records it depends on and invalidate by tag. Many CDNs and web frameworks support this directly, and it scales far better than tracking every key by hand.

Protect against cache stampedes

When a popular key expires, every request that arrives in the next moment misses the cache and goes to the database at once. For a heavily used key, that burst can overwhelm the database. This is called a cache stampede, or a thundering herd.

Three common defences:

  • Request coalescing. Only one request recomputes the value, and the others wait for its result. With Redis this is often a short lock taken with SET lock:product:42 1 NX PX 5000.
  • Serve stale while refreshing. Keep the old value a little past its expiry and keep returning it while a single background task fetches the new one.
  • Add jitter to TTLs. If thousands of keys are written at the same moment with the same TTL, they all expire together. Add a few random percent to each TTL so expiries spread out.

What not to cache

  • Responses that depend on the user, in any shared cache.
  • Data where a stale read causes real harm, such as an account balance or stock at the moment of purchase. Read those from the source.
  • Values that are cheap to compute. A cache lookup is a network call too, and caching something that takes a millisecond to build only adds moving parts.

A good cache is one you can explain: what is stored, for how long, and what removes it. If you cannot answer those three questions for a cached value, that value will eventually be wrong in a way that is hard to debug.

Caching in our own products

Smart POS uses Redis for entitlement and lookup caching, and its storefront works out which shop to render from the Host header and caches that answer for a minute, a short lifetime that is cheap to be wrong about. This website takes the event-driven route instead: content reads are cached under tags, and saving a page in the CMS invalidates exactly the tags it touched. Choosing between models like these is a routine part of our web application development work.

Let's build something reliable

Practical software. Reliable systems. Built to scale.

Tell us what you are building and where delivery is slowing down. We will map the shortest practical path to a working product.

A remote-first software studio building web platforms, desktop software, and scalable systems that keep working after launch.

  • Web platforms
  • Desktop software
  • Cloud & DevOps
info@systronium.com