Skip to content
OpenCloseEsc
Tips
  • Laravel
  • cache
  • performance

Serve stale data with Cache::flexible()

flexible() returns a fresh value while it is young, serves the old one and rebuilds in the background during a grace window, and only blocks once that window has passed.

1 min read

Cache::remember has one mode: fresh or rebuild now. Since Laravel 11.23, Cache::flexible has two timers.

$posts = Cache::flexible('posts.latest', [300, 3600], function () {
    return Post::latest()->take(5)->get();
});
  • Under 5 minutes old: returned as is.
  • Between 5 and 60 minutes: the stale value is returned at once, and the rebuild runs after the response has been sent.
  • Over 60 minutes: rebuilt inline, like remember.

Nobody waits for the rebuild as long as the key is touched now and then. It fits lists, counters and dashboards where a few minutes of lag is fine, and not a seat count or a balance.