Ritenta

Caching from the browser to the backend

Follow a stale catalog response through browser, CDN and application caches, then measure what happens when they miss.

Published: 9 min read

An editor corrects a public course catalog. The database shows revision 42, some readers still see 41, and a cache purge sends the database into a queueing spike. Each cache on the request path can reuse a different copy, and each miss transfers work to the next layer. In this example, every timestamp and measurement is illustrative.

A cache stores a reusable result of earlier work. The browser can reuse downloaded bytes, a content delivery network (CDN) can reuse an HTTP response across readers, and an application can reuse the result of a database query. The savings come from repeated access within the useful lifetime of the result. A workload full of one-off requests can pay for a lookup and still do the original work. Once a service relies on hits to stay within its capacity, cold starts and cache outages become capacity events. Amazon Builders’ Library on caching · Hazelcast on caching

Make four decisions for each cache

DecisionQuestionPublic catalog example
KeyWhich requests can reuse the same result?Catalog ID, language and any filter that changes the returned data.
FreshnessFor how long and under what conditions may this copy be reused?An edge copy can be fresh for 120 seconds and a browser copy for 20.
EvictionWhich entries leave when storage fills?Keep frequently requested catalogs if frequency predicts reuse.
ConsistencyWhat must a reader see after an edit?Editors confirm against the authoritative store immediately. The public view has a propagation budget.

If the language lives in the URL, /uk/catalog/7 and /en/catalog/7 already differ by URI. If a URI negotiates language via Accept-Language, emit Vary: Accept-Language and verify how the configured shared cache handles that dimension. An application key can use the resolved supported locale, such as catalog:v2:7:uk, where v2 is the cached schema version. Equivalent browser preferences can then share an application entry. A deployment that changes the cached shape can move to a new namespace. For access-controlled data, authorize the current request before returning a result and design the cache scope explicitly. The example endpoint returns the same public catalog to every caller in a given language. RFC 9111 on cache keys and Vary

A Redis expiration gives an entry a time to live (TTL). A memory limit can remove an entry earlier under a configured eviction policy. Least recently used (LRU) favors recent reuse. Least frequently used (LFU) can help when a small set stays popular through scans of rarely visited items. Redis offers approximations of these policies. Test against the real access distribution and bound memory explicitly. An HTTP cache can retain a stale response to validate later. Invalidation is a deliberate action after a change. Decide what happens if an invalidation arrives late, repeats, or fails. Redis expiration · Redis eviction · RFC 9111 on freshness and validation

Follow a response through the browser and CDN

Assume the CDN honors the origin directives on this route and has already held the response for 70 seconds when a new browser receives it. This is the response at the browser.

Long code lines scroll sideways →
HTTP/1.1 200 OK
Date: Thu, 19 Nov 2026 09:00:00 GMT
Content-Type: application/json
Cache-Control: public, max-age=20, s-maxage=120
ETag: W/"catalog-7-en-r41"
Age: 70

{"id":7,"language":"en","revision":41,"title":"Systems catalog"}

A private HTTP cache uses max-age=20 for freshness. A shared cache uses s-maxage=120 in preference to max-age. At age 70 the edge has about 50 seconds of freshness left, and the response is already stale for the browser. The browser does not start a new 20-second clock on receipt. HTTP age accounts for time since generation or successful validation, including time spent in intermediary caches. Measure the revision or its commit timestamp separately to know how current the underlying data was when the response was built. RFC 9111 on freshness lifetime and age

On later reuse, the browser can send If-None-Match: W/"catalog-7-en-r41". A cache may answer a conditional request using an eligible stored representation. Otherwise the validator can reach the origin. A matching validator on a conditional GET can produce 304 Not Modified with no body. The recipient reuses its stored body with updated metadata. If revision 42 changes the selected representation and its validator, the origin sends 200 OK with the new body. The W/ prefix marks a weak ETag, sufficient for this validation. Generate the tag from the representation itself or include everything that changes its meaning, such as the variant and a representation format version. Last-Modified and If-Modified-Since provide a time-based alternative with second-level resolution. With both conditional headers present, If-None-Match takes precedence. RFC 9110 on validators and preconditions

no-cache permits storage and requires successful validation before reuse. no-store directs HTTP caches to refrain from storing the exchange. private bars shared caches from storing the response and can still allow browser caching. A content-hashed static asset can use a long freshness lifetime when each change gets a new URL. Give the document pointing to those URLs its own update policy. Verify CDN eligibility and cache keys in the deployed configuration, where provider rules can affect both. RFC 9111 on response directives · MDN on HTTP caching · Cloudflare on edge caching

A service worker may return a response from the Cache API, which stores request/response pairs in named caches. Cache Storage does not enforce HTTP freshness directives. If the worker stores the catalog there, it needs its own refresh and cleanup rules and must handle storage eviction. An offline app shell can use a versioned cache while the online catalog uses ordinary HTTP caching. Inspect worker control and Cache Storage separately in DevTools. MDN on the Cache API

Trace the edit and the purge

The CDN cached revision 41 at 09:00:00, and Redis already held the same revision. At 09:00:15 an editor committed revision 42. A reader at 09:01:10 may still get 41 from a fresh edge copy, including after a conditional request that the edge answers with a 304. At 09:01:20 an operator purged the edge. The next origin response still carried 41 with a newly generated Date. The origin had read Redis. The purge removed an HTTP copy while the application kept its older query result. The regenerated response can start another 120-second edge freshness window, so that setting alone gives no reliable bound on time since the edit.

Work from the observed revision inward. In DevTools, check whether the response came from memory, disk or a service worker, and distinguish a network 304 from a network 200. For network responses record the URL, Age, Date, ETag and any provider cache-status header. A DevTools HTTP-cache bypass leaves the CDN and Cache Storage in the path unless separately bypassed. Correlate edge logs with the origin trace, selected key, cache outcome and returned revision. Check the authoritative revision separately. In this example, an origin hit with revision 41 explains the post-purge response. An origin miss returning 41 points toward the database read path, where replica lag is one possibility. Cloudflare on cache response statuses

Fix the application read and write paths together

With cache-aside, the application reads the key, fetches from the source on a miss and stores the result. Commit the database update before deleting dependent cache entries. Deleting first lets a reader refill from the old database state before the commit. Commit-then-delete still has a race. A reader can begin a miss, read revision 41, pause, and write it to the cache after the revision 42 commit and key deletion. Coalescing readers alone leaves that interleaving possible. Azure Architecture Center on cache-aside

Suppose an authoritative catalog lookup returns its current revision, and published snapshots are immutable and readable by revision. Read the revision directly, then cache the expensive assembly under a versioned key. The lightweight lookup remains on the origin path.

In this JavaScript example, the cache returns undefined on a miss. The source, cache and per-key coalescer are provided by the application.

Long code lines scroll sideways →
async function readPublicCatalog(id, locale, dependencies) {
  const { source, cache, coalesceByKey } = dependencies;
  const revision = await source.readPublishedRevision(id);
  const key = JSON.stringify(['catalog:v2', id, locale, revision]);

  const cached = await cache.get(key);
  if (cached !== undefined) return cached;

  return coalesceByKey(key, async () => {
    const current = await cache.get(key);
    if (current !== undefined) return current;

    const result = await source.assembleSnapshot(id, locale, revision);
    const ttlSeconds = 90 + Math.floor(Math.random() * 21);
    await cache.put(key, result, { ttlSeconds });
    return result;
  });
}

A request that started with 41 may finish with 41. Its late fill goes into the 41 key; the next lookup that observes 42 uses a different key. This requires a consistent revision lookup and the ability to finish reading a pinned snapshot. With mutable rows only, another approach is a coordinated version check at cache publication plus a reliable way to advance the version after commits. Separate read-then-set operations leave a race between the check and the write. For immediate editor confirmation, return the committed revision from the write or read the authoritative store. Set and verify a public propagation budget across all active layers.

Read-through moves miss loading into the cache abstraction. Write-through coordinates synchronous persistence, adding latency and requiring defined behavior when part of a write fails. Write-behind schedules persistence asynchronously, so durability, ordering and retries determine what can be lost or reordered. An in-process cache avoids a network hop and keeps a separate copy per process. A shared cache lets instances reuse fills and adds a network dependency. A hybrid design combines both and needs an invalidation policy for both. Hazelcast on access patterns · Microsoft on local, distributed and hybrid caching

Size the miss path

Suppose the edge serves 1,000 requests per second with a 90% hit rate. Of the 100 requests per second reaching the application, 80% hit its data cache. With one expensive query per application miss, that is 1,000 × 0.10 × 0.20 = 20 expensive queries per second, plus lightweight lookups. If both layers go cold together, the upper bound without coalescing is 1,000 expensive queries per second, or 50 times steady state. A hot key drawing 400 origin requests per second just after a purge, with a fill taking 200 ms, can accumulate roughly 80 requests before the first fill finishes. If they all start the same work independently, that burst is a cache stampede.

Coalescing gives concurrent misses for one key one fill to wait for. Recheck after acquiring ownership, give waiters deadlines, and release ownership on errors. Process-local coalescing can still produce one fill per process. If that exceeds the origin budget, consider coordinating across instances and limit simultaneous fills across keys. TTL jitter spreads expiration across keys. A single hot key still needs protection. Where the product allows it, serve a bounded stale copy during refresh or source failure. When Redis times out, unlimited fallback can put the database into the same outage. Set a lookup deadline, cap fallback concurrency and define what the application returns at that limit. Amazon Builders’ Library on cache failure and load · Microsoft on stampede protection

Measure warm hits, cold misses and cache unavailability under the same traffic mix. Track hits, misses, bypasses and errors per layer with their own denominators, plus p50, p95 and p99 latency, database query rate, saturation, evictions and time from a committed edit to public visibility. Keep revalidations visible: a small 304 can still cost a round trip or origin work. Compare with a baseline and watch miss latency separately. A high hit rate averaged over a day can conceal the seconds when the queue filled. For the catalog, verify the public update budget under a normal edit and the database capacity budget during a cold start or cache failure.

Practise what you read

Answer questions based on this article in Ritenta.

Open practice