TIP 06 / 06

Serve Stale Cache Data While Refreshing It.

For expensive values that can be briefly stale, Cache::flexible() returns a fresh value immediately and refreshes a stale value after the response. This avoids making every visitor wait for the same recalculation.

code
$summary = Cache::flexible('dashboard:summary', [30, 300], function () {
    return Order::query()
        ->selectRaw('status, count(*) as total')
        ->groupBy('status')
        ->get();
});

The first duration is the fresh window; the second is the maximum stale window. Use it only when serving slightly out-of-date data is acceptable, and ensure the cache store is shared if the site runs on multiple servers.