Skip to content

Search

Articles, tools, solutions and knowledge base guides

Start typing to search across articles, tools and apps.

Caching in web applications: browser, CDN, Redis and data invalidation

Caching improves a web application only when it is designed as part of the data-consistency model, not as an accidental speed layer. Browser caches, CDNs and Redis operate at different layers, use different keys, freshness rules and invalidation mechanisms. The hardest bugs appear when those layers disagree about how long data is valid and who is responsible for refreshing it.

Published Written by Reading time 21 min read
On this page Contents: quick navigation between sections

Cache is a stack of layers, not one mechanism

HTTP caching distinguishes private and shared caches. A browser cache is the common private-cache example, while a CDN or proxy is a common shared-cache example. [1][3]

Redis works at another layer. It does not automatically cache HTTP responses; the application chooses which values to store, such as database results, user profiles or computed aggregates. [9]

These layers can operate at the same time, so a caching policy should define browser TTL, CDN TTL and application-cache TTL separately.

Fresh, stale and revalidation in HTTP

RFC 9111 defines a response as fresh while its age does not exceed its freshness lifetime. Once that lifetime is exceeded, the response is stale. [1]

A fresh response can be reused without contacting the origin. A stale response normally requires revalidation or another explicit permission to use it. [1]

Freshness can be defined with Cache-Control: max-age or Expires. When an explicit freshness lifetime exists, caches should not replace it with heuristic freshness. [1]

no-cache, no-store and private mean different things

DirectiveMay be storedMay be reused without originTypical use
no-cacheYesNo, requires revalidationHTML and APIs that must stay current
no-storeNoNot applicableData that must not be stored
privateYes, private caches onlyDepends on freshnessPersonalized responses
publicYes, including shared cachesDepends on freshnessPublic content

Cache-Control: no-cache allows a response to be stored but requires validation with the origin before reuse. [3][4]

Cache-Control: no-store tells caches not to store the response. private allows storage in a private cache but not in a shared cache. [4]

For personalized responses after sign-in, private is especially important because it prevents a shared cache from reusing the response for another user. [4]

ETag, Last-Modified and 304 Not Modified

HTTP supports representation validators. An ETag can later be sent in If-None-Match, while Last-Modified can be used with If-Modified-Since. [1]

If the representation has not changed, the origin can return 304 Not Modified, avoiding retransmission of the complete response body. [1][3]

For HTML or APIs that should always be current, no-cache together with ETag or Last-Modified is often a better trade-off than disabling storage entirely with no-store. [3]

immutable and versioned static assets

Static files whose URLs contain a content hash or version can use a long max-age because a content change creates a new URL. MDN recommends this cache-busting pattern for assets that do not change under the same URL. [3]

The immutable directive tells caches that the representation will not change while it is fresh, reducing unnecessary revalidation on reload. [3][4]

This pattern fits JavaScript bundles, CSS, fonts and generated images particularly well.

stale-while-revalidate and stale-if-error

RFC 5861 defines stale-while-revalidate, allowing a cache to serve a stale response for a specified interval while it attempts revalidation in the background. [2]

stale-if-error allows a stale response to be used when the origin fails or is temporarily unavailable, within the configured staleness window. [2]

These mechanisms can improve latency and availability, but they intentionally increase the time during which a user may see stale data.

A CDN cache key is as important as TTL

A cache key determines which requests map to the same stored response. Cloudflare's default key includes elements such as scheme, host, URI with query string and selected headers. [6]

An overly broad key definition can fragment the cache and reduce hit rate. An overly narrow key can merge requests that need different responses.

If a response varies on a header named by Vary, RFC 9111 requires that difference to be considered when selecting a stored response. [1]

A CDN follows origin policy only within its edge configuration

Cache-Control sent by the origin can control CDN behavior. Cloudflare describes Origin Cache Control as the mechanism for respecting cache directives from the origin. [5]

CDN rules can still override or augment origin policy, so effective caching semantics can differ from the response header emitted by the application. [5]

Debugging therefore requires checking application headers, edge rules and the actual cache status observed at the CDN.

Purge and invalidation are not the same CDN operation

CDN operationWhat happensNext requestWhen to use
PurgeObject is removedFull fetch from originStale content must never be served again
Invalidate / soft purgeObject stays but is marked staleRevalidation with originYou want to reuse 304 or stale policies

Cloudflare purge removes cached content. The next request becomes a miss and fetches a full response from the origin. [7]

Invalidation, also called soft purge, keeps the object but marks it stale. The next request revalidates with the origin and can reuse the object if the origin returns 304 Not Modified. [8]

Purge is appropriate when stale content must not be served again. Invalidation is useful when revalidation is acceptable and may avoid downloading the full body. [8]

Purging by tag is more precise than purge everything

Cloudflare lets responses carry Cache-Tag values and later purge all cached objects associated with a tag. [7]

That makes it possible to connect multiple URLs to one domain entity, such as a product affecting its detail page, category page and home page.

After a purge, the next request must rebuild the cache, so broad purges can temporarily increase load on the origin. [7]

Redis cache-aside is a common application pattern

With cache-aside, the application first tries Redis. On a miss it reads the source of truth, such as the primary database, and stores the result in cache. [9]

On update, the application writes to the primary store and invalidates the relevant cache key. Redis documents this as a way to bound staleness with TTL plus explicit invalidation. [9]

Cache-aside stores only data that is actually requested, but the first request after a cold miss still pays the source-read cost.

Redis TTL and eviction solve different problems

Redis mechanismPurposeExample
TTLLimit entry lifetimeSET key value EX 300
EvictionControl memory when maxmemory is reachedallkeys-lru, allkeys-lfu
Explicit invalidationRemove immediately after a data changeDEL cache:product:123

TTL defines when a specific key expires. Redis SET supports EX, PX, EXAT and PXAT, so expiration can be attached when the value is written. [11]

Eviction defines what Redis does when it reaches the configured memory limit. Available policies include LRU, LFU, random and variants limited to keys with TTL. [10]

TTL controls time-based freshness of an entry, while eviction manages memory pressure. They are not substitutes.

Cache stampede and hot keys

Redis describes a cache stampede as the situation where a popular key expires and many concurrent application instances query the primary database at the same time to rebuild it. [9]

Mitigations include a mutex or lock during regeneration, probabilistic early refresh, stale-while-revalidate at an appropriate layer, or adding jitter to expiration times.

The goal is to prevent hundreds of concurrent requests from performing the same expensive rebuild after one popular key expires.

Event-driven invalidation needs a reliable channel

Redis keyspace notifications can report key changes, but they are implemented with Pub/Sub. Redis documents Pub/Sub as fire-and-forget, so a subscriber that is disconnected misses events published during the outage. [12]

Keyspace notifications therefore should not be the only mechanism for business-critical cross-service invalidation.

If invalidation must be guaranteed, use a durable event channel or another mechanism with retry and replay semantics.

How to design caching from the beginning

Start by classifying data into immutable assets, public content, personalized content, frequently changing API data and expensive computed data. Each category can have a different policy.

Separate browser cache, CDN cache and Redis cache. For each layer, document the cache key, TTL, source of truth, invalidation trigger and error behavior.

Design correctness and the maximum acceptable staleness window first, then optimize hit rate.

  • Use long TTL plus immutable for versioned assets.
  • For current HTML, consider no-cache plus ETag or Last-Modified rather than automatically using no-store.
  • Use private for personalized responses that must not enter shared caches.
  • Design cache keys together with language, query parameters and other representation variants.
  • Prefer granular CDN purge or invalidation by URL, tag, prefix or host.
  • Set Redis TTL deliberately and choose an eviction policy that matches the access pattern.
  • Protect popular keys against cache stampede.
  • Monitor hit ratio, miss ratio, evictions, origin latency and invalidation volume.

The best caching strategy is not the one with the longest TTL. Define which data may be stale, for how long, who can share it and how invalidation happens after a change. Browser caching should rely on HTTP semantics, CDNs need correct cache keys and purge controls, and Redis needs deliberate TTL, eviction and invalidation policies. When those layers are designed together, caching reduces latency and origin load. When they are designed independently, caching can become a source of subtle consistency bugs.

Caching HTTP Cache Browser Cache CDN Redis Cache-Control ETag Cache Invalidation Performance Web Performance

Frequently asked questions

Does no-cache disable caching?

No. no-cache allows storage but requires revalidation with the origin before reuse. [3][4]

When should no-store be used?

When a response should not be stored by caches. Note that no-store does not automatically remove an older stored response for the same URL. [3][4]

What is the difference between ETag and Last-Modified?

Both are validators. ETag identifies a representation variant with an entity tag, while Last-Modified validates by modification time. [1]

Does 304 Not Modified contain the full body?

No. It tells the client or cache that the stored representation can be reused, so the full body does not need to be retransmitted. [1][3]

Does a CDN always respect Cache-Control from the application?

Not necessarily. It depends on provider configuration and edge rules. Cloudflare can honor Origin Cache Control, but Cache Rules can override or extend it. [5]

What should be part of a CDN cache key?

Anything that changes the representation, such as host, path, query or selected headers. Too many dimensions reduce hit rate; too few can merge distinct variants. [6]

Purge or invalidate?

Purge removes the object and the next request performs a full fetch. Invalidate keeps it as stale and allows revalidation. [8]

Are Redis TTL and eviction the same?

No. TTL decides when a key expires; eviction decides which keys are removed under memory pressure. [10][11]

How does cache-aside work?

The application reads Redis first, fetches from the primary store on miss, caches the result and invalidates the relevant key after updates. [9]

What is a cache stampede?

It occurs when a popular key expires and many concurrent requests try to rebuild it from the data source at the same time. [9]

Are Redis keyspace notifications suitable for guaranteed invalidation?

Not as the only mechanism. They use fire-and-forget Pub/Sub, so disconnected subscribers lose events. [12]

Does stale-while-revalidate always return fresh data?

No. It intentionally allows a stale response for a bounded interval while revalidation happens in the background. [2]

Sources and references

  1. RFC 9111, HTTP Caching↩1↩2↩3↩4↩5↩6↩7↩8↩9
  2. RFC 5861, HTTP Cache-Control Extensions for Stale Content↩1↩2↩3
  3. MDN Web Docs, HTTP caching↩1↩2↩3↩4↩5↩6↩7↩8↩9
  4. MDN Web Docs, Cache-Control↩1↩2↩3↩4↩5↩6
  5. Cloudflare Docs, Origin Cache Control↩1↩2↩3
  6. Cloudflare Docs, Cache Keys↩1↩2
  7. Cloudflare Docs, Purge cache by cache-tags↩1↩2↩3
  8. Cloudflare Docs, Invalidate cached content↩1↩2↩3
  9. Redis Docs, Cache-aside↩1↩2↩3↩4↩5↩6
  10. Redis Docs, Key eviction↩1↩2
  11. Redis Docs, SET command↩1↩2
  12. Redis Docs, Keyspace notifications↩1↩2

Was this helpful?

Get new articles by email

One short email per new Learning article. No spam, unsubscribe in one click.

We only use your email to send new articles. No third-party sharing.

Back to Learning