Tutorial

Caching Strategies for Web Applications

Choose the right cache for each layer, invalidate with tags and versions, and serve fresh data with stale-while-revalidate without thundering herds.

On this page

  1. Introduction
  2. The Layers and Their Trade-offs
  3. HTTP Caching: Cache-Control and the CDN
  4. In-Application Caching: LRU and TTL
  5. Invalidation: The Hard Problem
  6. Stale-While-Revalidate: Freshness Without the Stampede
  7. Cache Stampede, Single-Flight, and Consistency Models
  8. Conclusion

Introduction

Caching is the highest-leverage performance optimization and the most common source of correctness bugs. A well-placed cache turns a 200ms database query into a 2ms memory lookup; a poorly invalidated cache serves yesterday’s prices to today’s shoppers. The difficulty is not in caching — putting a value in a map is trivial — but in deciding what to cache, where, for how long, and how to invalidate it without serving stale data or stampeding the origin. This article covers the layers at which to cache, the invalidation strategies that scale, and the patterns (stale-while-revalidate, request coalescing) that give you freshness without the thundering herd.

The Layers and Their Trade-offs

A request passes through several layers, each a candidate for a cache: the browser, the CDN edge, the application’s in-memory or distributed cache, and the database. Each layer is cheaper to hit than the one behind it, and each serves a different kind of data. The browser cache (via HTTP Cache-Control) is closest to the user and free to the server, but it is per-user and per-device, so it cannot share a cached response across users. The CDN cache is shared across users at the edge, close to them geographically, and ideal for public, cacheable responses. The application cache (in-memory like LRU, or distributed like Redis) is shared across requests and can cache computed or database-backed data the CDN cannot. The database query cache is the last line, caching the result of a query within the database itself.

Cache at the highest layer you can while still serving fresh data. A static asset with a content hash in its name can be cached at the CDN for a year; a user-specific API response can be cached in the application for seconds; a per-request computation should not be cached at all. Pushing a cache down a layer (caching in the application what the CDN could cache) leaves latency on the table; pushing it up a layer (caching at the CDN what is user-specific) serves the wrong user’s data. The layer is a decision about who shares the data and how stale it can be.

HTTP Caching: Cache-Control and the CDN

HTTP caching is declared with the Cache-Control header and enforced by the browser and CDN. The directives express who may cache and for how long: public allows shared caches (CDN), private allows only the browser, max-age is the freshness lifetime in seconds, and immutable tells the cache the resource will never change during its lifetime (so a reload does not revalidate). For a hashed asset, the combination public, max-age=31536000, immutable lets the CDN cache it for a year, because the filename changes when the content does.

// A hashed asset: cache forever, it is addressed by content hash.
res.setHeader("Cache-Control", "public, max-age=31536000, immutable");
res.setHeader("Vary", "Accept-Encoding"); // cache gzip and brotli separately

// A user-specific API response: cache briefly, only in the browser.
res.setHeader("Cache-Control", "private, max-age=10");
res.setHeader("Vary", "Authorization"); // do not share across users

The Vary header is essential and often forgotten: it tells the cache that the response varies by another header, so the cache stores separate entries for each value. Without Vary: Authorization, a CDN might cache the response for user A and serve it to user B. Without Vary: Accept-Encoding, a CDN might cache the brotli response and serve it to a client that requested gzip. Set Vary for every header that changes the response, or the cache serves the wrong variant.

In-Application Caching: LRU and TTL

The application cache lives in process memory (fast, per-instance, lost on restart) or in a shared store like Redis (slower, shared across instances, durable). An LRU (least-recently-used) cache evicts the least recently used entry when it is full, which is the right policy for a cache of bounded size where recent entries are more likely to be requested again. A TTL (time-to-live) cache evicts entries after a duration, which is the right policy for data that goes stale on a schedule.

class LRUCache<K, V> {
  private map = new Map<K, V>();
  constructor(private readonly max: number) {}
  get(key: K): V | undefined {
    const value = this.map.get(key);
    if (value !== undefined) { this.map.delete(key); this.map.set(key, value); } // move to most-recent
    return value;
  }
  set(key: K, value: V) {
    if (this.map.has(key)) this.map.delete(key);
    this.map.set(key, value);
    if (this.map.size > this.max) this.map.delete(this.map.keys().next().value!); // evict least-recent
  }
}

The Map in JavaScript maintains insertion order, so deleting and re-setting a key moves it to the end (most recent), and the first key is the least recently used. This is a complete LRU in a few lines. Use it for the hot, bounded set of data that fits in memory — the most recent 10,000 sessions, the top 100 products — and use Redis for the larger or shared set.

Invalidation: The Hard Problem

There are only two hard problems in computer science, and cache invalidation is one of them. The strategies, from simplest to most robust, are TTL expiration, explicit invalidation, and tag-based invalidation. TTL expiration lets entries go stale on a schedule — simple, but it serves stale data between the change and the expiration. Explicit invalidation removes the entry when the data changes — correct, but it requires the code that changes the data to know every cache key that references it. Tag-based invalidation is the scalable middle: each cache entry is stored with tags, and invalidating a tag drops every entry with that tag.

// Tag-based cache: store with tags, invalidate by tag.
const cache = new Map<string, { value: unknown; tags: Set<string> }>();
const tagIndex = new Map<string, Set<string>>(); // tag -> keys

function set(key: string, value: unknown, tags: string[]) {
  cache.set(key, { value, tags: new Set(tags) });
  for (const t of tags) (tagIndex.get(t) ?? tagIndex.set(t, new Set()).get(t)!).add(key);
}
function invalidate(tag: string) {
  for (const key of tagIndex.get(tag) ?? []) cache.delete(key);
  tagIndex.delete(tag);
}

// Cache a product, tagged so invalidating "product:42" or "products" drops it.
set("product:42", product, ["product:42", "products"]);
// When the product changes:
invalidate("product:42"); // drops the specific entry
invalidate("products");   // drops every product-list entry

With tags, the code that updates a product invalidates the product:42 and products tags without knowing every list endpoint that includes it. This is how you keep a cache correct at scale: the invalidation is by semantic group, not by enumerated key, so adding a new list endpoint does not require updating every write path.

Stale-While-Revalidate: Freshness Without the Stampede

Stale-while-revalidate (SWR) serves the cached value immediately if it is present, even if it is stale, and refreshes it in the background. The user gets an instant response (the stale cache) and the cache is updated for the next request, so the user never waits for a refresh and the origin is never stampeded. The pattern, popularized by the SWR and TanStack Query libraries on the client and by the stale-while-revalidate HTTP directive on the server, is the best default for data that is read often and updated rarely.

async function swr<T>(key: string, maxAgeMs: number, staleMs: number, fetch: () => Promise<T>): Promise<T> {
  const entry = store.get(key);
  const now = Date.now();
  if (entry) {
    if (now - entry.fetchedAt < maxAgeMs) return entry.value; // fresh
    if (now - entry.fetchedAt < maxAgeMs + staleMs) {
      // stale but usable: serve now, refresh in the background.
      if (!entry.refreshing) { entry.refreshing = true; fetch().then(v => { store.set(key, { value: v, fetchedAt: Date.now(), refreshing: false }); }).catch(() => { entry.refreshing = false; }); }
      return entry.value;
    }
  }
  // no usable cache: fetch and serve.
  const value = await fetch();
  store.set(key, { value, fetchedAt: now, refreshing: false });
  return value;
}

Pair SWR with request coalescing — if a refresh is already in flight, subsequent requests wait for it rather than starting their own — and you eliminate the thundering herd: a hundred concurrent requests for the same stale key produce one origin fetch, not a hundred.

Cache Stampede, Single-Flight, and Consistency Models

The cache stampede (or thundering herd) is the failure mode that occurs when a popular cache entry expires and a burst of requests arrives before the first request repopulates it. Every request in the burst sees a cache miss, every request fetches from the origin, and the origin — which the cache was protecting — is hit by N concurrent fetches for the same key. For a database query that takes 500ms, a stampede of 100 requests is 100 concurrent queries that may exhaust the connection pool and cascade into a timeout. The cache, intended to protect the origin, becomes the trigger for the origin’s failure.

The single-flight pattern prevents the stampede by ensuring only one request fetches the value while the others wait for the result. The first request to see the miss acquires a lock (or creates a promise) for the key; subsequent requests see the in-flight fetch and await the same promise rather than starting their own. When the fetch completes, the value is cached and every waiting request receives it. The origin is hit once, not N times.

const inflight = new Map<string, Promise<unknown>>();

async function singleFlight<T>(key: string, fetcher: () => Promise<T>): Promise<T> {
  if (cache.has(key)) return cache.get(key) as T;
  if (inflight.has(key)) return inflight.get(key) as Promise<T>;
  const promise = fetcher().then((value) => { cache.set(key, value); inflight.delete(key); return value; })
                            .catch((err) => { inflight.delete(key); throw err; });
  inflight.set(key, promise);
  return promise;
}

The inflight map is the single-flight state: a key is present while a fetch is in progress, and absent otherwise. The error handler deletes the key on failure so a failed fetch does not cause subsequent requests to await a rejected promise forever. For a distributed system, the single-flight state lives in Redis (a SET NX lock with a TTL) rather than in a process-local map, so the deduplication spans every instance. The TTL on the lock is the guard against a crashed fetcher holding the lock forever — if the fetcher dies, the lock expires and another request takes over.

A softer approach is early refresh (or probabilistic early expiration), which refreshes the cache before it expires rather than after. Each request computes a probabilistic refresh window based on the remaining TTL and the fetch duration: if the entry is near expiry and the fetch is slow, the request refreshes it in the background while serving the stale value. The result is that the cache is refreshed before the miss occurs, and the stampede never happens. This is the algorithm used by Redis client libraries like ioredis and by Netflix’s internal caching, and it is the approach when the single-flight lock is too coarse.

// Probabilistic early refresh: refresh in the background if the entry is "near" expiry.
function shouldRefresh(ttl: number, fetchDuration: number, beta = 1): boolean {
  // The probability of refresh increases as ttl decreases relative to fetchDuration.
  return -Math.log(Math.random()) * beta * fetchDuration > ttl;
}

Cache consistency is the question of how long a stale value is acceptable. A write-through cache updates the cache at the same time as the origin, so the cache is always consistent — at the cost of a cache write on every origin write, which adds latency to writes. A write-behind cache updates the cache immediately and the origin asynchronously, so writes are fast but the origin may lag behind the cache, and a crash between the cache update and the origin write loses the write. A cache-aside cache is updated on the next read after a write invalidates the entry, which is simple but allows a window of staleness between the write and the next read. Choose the consistency model the feature needs: a product catalog tolerates seconds of staleness (cache-aside with a TTL); a bank balance does not (write-through or no cache). The consistency model is a property of the cache, not an accident of the implementation, and it should be stated and tested.

Conclusion

Caching well is a decision at each layer: cache at the highest layer that can serve the data fresh, declare HTTP caching with the right Cache-Control and Vary, use LRU or TTL in the application for the hot bounded set, invalidate by semantic tag so writes do not need to know every key, and serve stale-while-revalidate with request coalescing so freshness does not stampede the origin. The cache you can invalidate is a cache you can trust; the cache you cannot is a cache that will serve stale data at the worst moment. Choose the layer, set the lifetime, wire the invalidation, and the cache becomes a reliable performance multiplier rather than a correctness liability.

Related Examples