Stale-While-Revalidate
You'll learn how to serve cached content instantly while updating it in the background for future requests.
What Is Stale-While-Revalidate?
Stale-While-Revalidate (SWR) is a caching strategy that prioritizes speed by serving "stale" (slightly outdated) content from cache immediately, then fetching fresh content in the background to update the cache for next time.
Think of it like a newspaper stand: when you arrive, the vendor gives you yesterday's paper right away (so you're not waiting), but simultaneously sends someone to grab today's edition from the printer. Next customer gets the fresh one.
How It Works with Cache-Control
You enable this pattern using the Cache-Control header:
Cache-Control: max-age=3600, stale-while-revalidate=86400
This tells the browser:
- For 3600 seconds (1 hour), serve from cache without checking
- For the next 86400 seconds (24 hours), serve stale content immediately but revalidate in the background
The User Experience Benefit
When a user requests content that's stale but within the stale-while-revalidate window:
- Browser serves cached version instantly (no waiting)
- Browser simultaneously fetches fresh version in background
- Fresh version updates cache for the next request
The current user gets instant response. The next user gets fresh content. Everyone wins.
When to Use It
Ideal for content that changes occasionally but where instant response matters more than absolute freshness: API responses, profile data, news feeds, product listings.
Avoid for: critical data requiring real-time accuracy (stock prices, bank balances).
Key Takeaway: Stale-While-Revalidate delivers instant responses by serving cached content immediately while updating it behind the scenes, balancing speed with freshness.