Adding "Stale While Revalidate" functionality to Laravel's Cache

November 9th, 2023

Stale While Revalidate (SWR) is a strategy to first return the data from the cache (stale), then send the fetch request (revalidate), and finally come up with the up-to-date data.

We can add similar functionality to Laravel's Cache Facade, which first returns the cached value and then, after the request is returned, will go and update the value for the next time the value is requested.

Laravel's Cache helper has a Macroable trait, which allows us to add any method that we like to the Facade:

// In a service provider
use Illuminate\Support\Facades\Cache;

public function boot()
  Cache::macro('staleWhileRevalidate', function ($key, $ttl, $callback) {
      if (Cache::has($key)) {
          App::terminating(fn() => Cache::put($key, $callback(), $ttl));

      return Cache::remember($key, $ttl, $callback);

The code above has the same functionality as the ->remember method on the default Cache helper, except that when there is a value in the cache, a terminating callback is added to the application, which will recalculate the callback and put it in the cache.

This allows you to set a way longer $ttl than you'd typically like because every time the cached value is requested from the cache, it will be recalculated after the response has been sent to the browser. This way, the next time it is requested, you get a fresh recalculated value.