Back to results for “Profiling”
Node.js › Caching

What is the 'stale-while-revalidate' caching strategy, and how would you implement it for an API response?

Advanced

Answer

Stale-while-revalidate immediately returns the currently cached value (even past its ideal freshness window) to keep response latency low, while asynchronously triggering a background refresh for the next request -- trading a small amount of staleness for consistently fast response times.
async function getWithSWR(key, fetchFn, ttl = 60000) {
  const cached = swrCache.get(key);
  if (cached) {
    if (Date.now() - cached.timestamp > ttl) {
      fetchFn().then(fresh => swrCache.set(key, { value: fresh, timestamp: Date.now() }));
    }
    return cached.value;
  }
  const fresh = await fetchFn();
  swrCache.set(key, { value: fresh, timestamp: Date.now() });
  return fresh;
}
Real-world example A dashboard displaying slowly-changing analytics metrics uses stale-while-revalidate so every page load feels instant, with the underlying data refreshing transparently in the background rather than making any user's request wait for recalculation.

Common follow-ups: What's the risk of this pattern for data where even brief staleness is unacceptable, like real-time account balances?;How does the HTTP Cache-Control 'stale-while-revalidate' directive implement this same idea at the HTTP layer?