Website Performance

Cache Invalidation: Why It Is Hard and Strategies That Work

By NileVPS Team · Published · 5 min read

اقرأ المقال بالعربي

Adding a cache is easy. Knowing when the cached copy is no longer true is the hard part. Every cache creates a second copy of your data, and the moment the original changes, the copy starts lying. Cache invalidation is the process of removing or refreshing those copies at the right time. Get it wrong in one direction and visitors see an old price, a deleted article or yesterday's stock level. Get it wrong in the other direction and you purge so often that the cache stops helping. This article explains why the problem is hard and walks through strategies you can apply on a VPS today.

Why invalidation is hard

Several things make invalidation difficult, and most real incidents involve more than one of them.

  • Many layers: a single page may be cached in the browser, a CDN, Nginx or Varnish, Redis and the application. Clearing one layer does not clear the others.
  • Hidden dependencies: changing a product's price affects the product page, category pages, the home page, search results and maybe a sitemap. The cache rarely knows these relationships.
  • Timing and races: if a request reads old data from the database just before an update, then writes it to the cache just after the purge, the stale value comes back. This is a classic race condition.
  • Copies you do not control: once a browser or a downstream proxy stores a response with a long lifetime, you cannot reach out and delete it.
  • Cost of purging: clearing everything after every edit causes a sudden flood of cache misses, and the origin server must rebuild every page at once.

There is no universal fix. Instead, you combine a few strategies, each suited to a different type of content.

Strategy 1: Time-based expiry (TTL)

The simplest approach is to let entries expire after a fixed time to live. The cache never needs to know about changes; it just accepts that content may be up to one TTL old.

Content typeExample TTLReasoning
Hashed static files1 yearThe URL changes when content changes
Blog articles10 minutes to 1 hourRarely change, small delay is acceptable
Product listings1 to 5 minutesPrices and stock change more often
Account and cart pagesDo not cachePersonal data

Short TTLs are a safety net even when you also purge actively. If a purge fails, the content still corrects itself.

Strategy 2: Versioned URLs (cache busting)

For CSS, JavaScript and images, avoid invalidation entirely by changing the URL whenever the file changes. Build tools generate names such as main.8c1e4f.css; frameworks offer helpers like Laravel's mix() or Vite::asset(). Old URLs remain valid for anyone still holding the old HTML, and new HTML points to new files.

This lets you send aggressive headers safely:

location /build/ {
    add_header Cache-Control "public, max-age=31536000, immutable";
}

The immutable directive tells supporting browsers not to revalidate the file during its lifetime.

Strategy 3: Explicit purge on change

When content changes, the application tells the cache to drop the affected entries. With Nginx fastcgi_cache you need the ngx_cache_purge module or a plugin to purge single URLs; with Varnish you can send an HTTP PURGE request that your VCL accepts only from trusted addresses. In Redis, delete keys directly:

redis-cli DEL product:42

Purging works best when you can list every URL or key affected by a change. Keep that logic close to the code that updates the data, for example in a model event or a post-save hook, so nobody forgets it.

Strategy 4: Tags and key namespaces

When one change affects many entries, tag them. Varnish (with modules such as xkey) and several CDNs support tag-based purges, and many frameworks support tagged cache entries in Redis. A product page might carry tags product-42 and category-7; updating product 42 purges everything tagged product-42 in one call.

A lighter alternative is versioned keys. Store a counter such as catalog:version and include it in every catalog key (catalog:v15:page:2). Incrementing the counter instantly makes every old key unreachable, and the old entries simply expire or get evicted later.

Strategy 5: Serve stale while refreshing

Sometimes slightly old content is better than a slow page. HTTP supports this with stale-while-revalidate:

Cache-Control: max-age=60, stale-while-revalidate=300

Supporting caches serve the stored copy for up to five extra minutes while fetching a fresh one in the background. In Nginx, fastcgi_cache_use_stale updating combined with fastcgi_cache_background_update on gives similar behaviour, and fastcgi_cache_lock on prevents many requests from rebuilding the same page at once, which protects against the cache miss storms that follow a large purge.

A practical invalidation plan

  • List every cache layer your site uses, from the browser to Redis.
  • Classify content: static assets, public pages, personal pages.
  • Use versioned URLs for all static assets.
  • Give public pages a modest TTL as a safety net.
  • Purge or tag on content updates, triggered from application code.
  • Never cache personal pages in shared caches.
  • Test: edit a page, then confirm with curl -I that each layer shows fresh content.
  • Document how to clear everything in an emergency.

FAQ

Should I just purge the entire cache after every update?

It works for small sites with occasional edits, but it gets expensive as traffic grows. Every purge forces the server to rebuild all pages at once. Targeted purges or tags keep most of the cache warm and are kinder to your VPS during busy periods.

Why do some visitors still see old content after I purge?

Their browser, a CDN or another proxy may still hold a copy. Server-side purges cannot reach browser caches, so keep HTML lifetimes short and use versioned URLs for assets. If you use a CDN, purge it as well, since it is a separate layer.

Is a short TTL enough without purging?

For many content sites, yes. If a delay of a few minutes is acceptable, a TTL alone is simple and reliable. For prices, stock or legal text where accuracy matters immediately, combine TTLs with explicit purging.

Related guides