The Cache Method Most Laravel Developers Are Overlooking

The Cache Method Most Laravel Developers Are Overlooking

Laravel has many great features that make our lives as developers easier. One such example is a cache, which allows us to increase the performance of our application and reduce the load on some services. Almost every Laravel developer knows the basics of caching: using the Cache :: remember() or Cache :: put() methods. But there is also a Cache :: flexible() method, which may not be so obvious at first glance.

In this post, we’ll take a look at what the Cache :: flexible() method is for. More specifically, we’ll look at implementing the so-called stale-while-revalidate pattern. We will also discuss what the difference is between fresh, stale, and expired data.

What is Stale-While-Revalidate Caching?

Imagine your users waiting for some important report to be generated or for data to be pulled from a slow 3rd party API. With standard caching strategies this would only delay a user having to wait again for the same data once the cache expires.

The stale-while-revalidate cache strategy helps to reduce this problem by doing the following,

  • When a cached request is made and the cached content is fresh (hasn't expired yet) it will return the fresh copy of the content
  • If the cached content is stale (has expired) but still within the 'stale' period specified it will return the stale copy to the user while asynchronously requesting a new copy of the content and updating the cached version.
  • If the data has expired and is beyond the 'stale' period then it will synchronously get a new copy of the content and return that to the user.

By implementing this cache strategy we can serve content from the cache to the user, possibly avoiding any delay from the source of the data being retrieved, while also keeping the cache updated with the latest information available.

Why Cache::flexible()?

Laravel's Cache::flexible() helper makes it easy to implement the stale-while-revalidate pattern, defining a primary TTL (time to live) for fresh data, and a stale TTL for how long to serve stale data while it's being refreshed.

The Problem Cache::flexible() Solves

Imagine an expensive operation: a complex database query, report generating or an external API call that takes several seconds to respond. By caching this data for, let's say, 5 minutes, any user that will hit the application after this period will be forced to wait all those seconds for a result. With Cache::flexible() you can serve them the previous (slightly-stale) 5-minutes-old data right away, and generate new data for the cache asynchronously for the next users.

Basic Syntax and How it Works

I think I see how it works. The Cache::flexible() method takes a cache key, primary time to live, stale time to live, plus a closure, which contains the logic to retrieve the fresh data.

use Illuminate\Support\Facades\Cache;

$data = Cache::flexible('your-cache-key')
    ->ttl(60) // Data is fresh for 60 seconds
    ->staleTtl(300) // Stale data can be served for an additional 300 seconds (5 minutes)
    ->get(function () {
        // This closure runs to fetch fresh data
        // Simulate an expensive operation
        sleep(5); 
        return ['message' => 'Fresh data from a slow source', 'timestamp' => now()];
    });

// $data will contain the fresh or stale value.

Let's parse the parameters:

  • 'your-cache-key': your cache key;
  • ttl(60): how long (in seconds) the data should be considered fresh. If you call get(), it will return a cached value;
  • staleTtl(300): how long (in seconds) the data should be considered stale. The next get() call will return a cached value, but your closure will be called to update the cache;
  • get(function () { ... }): closure that will be called to get or update a value. It will be called if the cache is empty, stale, or expired.

Practical Example: Optimizing a Slow Report

Consider a dashboard with a 'Monthly Sales Summary' report on it. The report requires complex aggregations and, therefore, takes about 5 seconds to generate. However, if the report is often viewed, 5 seconds on each cache expiration is a significant period.

Without Cache::flexible() (Standard Caching)

First, let's see how standard caching might work:

// app/Http/Controllers/ReportController.php
namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;

class ReportController extends Controller
{
    public function monthlySalesStandard()
    {
        $reportData = Cache::remember('monthly_sales_standard', 60, function () { // Cache for 60 seconds
            // Simulate a slow report generation
            sleep(5); 
            $data = [
                'period' => 'January 2024',
                'total_sales' => rand(10000, 50000),
                'generated_at' => now()->toDateTimeString(),
                'cache_status' => 'fresh (standard)'
            ];
            return $data;
        });

        return response()->json($reportData);
    }
}

In this setup, for the first request or after 60 seconds, the user waits 5 seconds. For subsequent requests within 60 seconds, it's instant.

With Cache::flexible() (Stale-While-Revalidate)

Now, let's implement the same report using Cache::flexible():

// app/Http/Controllers/ReportController.php
namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;

class ReportController extends Controller
{
    public function monthlySalesFlexible()
    {
        $reportData = Cache::flexible('monthly_sales_flexible')
            ->ttl(60) // Fresh for 60 seconds
            ->staleTtl(300) // Stale but usable for another 300 seconds
            ->get(function () {
                // Simulate a slow report generation
                sleep(5); 
                $data = [
                    'period' => 'January 2024',
                    'total_sales' => rand(10000, 50000),
                    'generated_at' => now()->toDateTimeString(),
                    'cache_status' => 'fresh (flexible)'
                ];
                return $data;
            });

        return response()->json($reportData);
    }
}

Let's understand the flow with Cache::flexible():

  • First Request (cache is empty): closure is executed, user waits for 5 seconds. The data is cached (fresh for 60 seconds).
  • Request within 60 seconds: the data is returned instantly from cache (fresh).
  • Request after 60 seconds but within 60 + 300 = 360 seconds:
    • the user gets instantly the stale data (which was cached 60 seconds ago). Meanwhile, Laravel will run in background the job that executes the closure (to generate fresh data). 
    • The job will take 5 seconds to complete. 
    • The next requests will get the fresh data instantly.
  • Request after 360 seconds (cache expired): closure is executed synchronously, the user waits 5 seconds. The data is cached as fresh.

As you can see, for the crucial period when the cache "goes stale," the user experience is greatly improved by providing an immediate, albeit slightly outdated, response.

Configuring Background Revalidation

As default, Laravel's Cache::flexible() makes the background revalidation task a queue job. This requires your queue worker to be running for stale-while-revalidate to be done asynchronously. If none is running or the queue driver is not setup, the closure will run synchronously on data being stale, almost as a Cache::remember() with extended expiry. So, make sure you've set up your queue config and that a queue worker is running:

php artisan queue:work

Real-World Use Cases

Cache::flexible() shines in scenarios where:

  • Dashboard widgets: A dashboard with analytics that do not need to be real-time (e. g., number of users for the last month, revenue for the last week). It can tolerate a several-minute delay to load faster.
  • Expensive API calls: Calling a third-party API that might have rate-limiting restrictions or is simply slow.
  • Complex database aggregations/reports: Relatively complex queries that take a noticeable amount of time to execute (e. g., reports of a company’s finances for a given quarter).
  • Feeds: News feed, articles, product catalog, etc., where a brief delay is not noticeable, or one does not mind seeing feeds from a few seconds or minutes ago.
  • Search results with filters: Search results that are relatively unimportant to have up-to-the-second data for.

When This Strategy Is Inappropriate

While powerful, stale-while-revalidate is not a panacea for all situations. Avoid using it for:

  • Real-time critical data: e-commerce checkout flows, stock trading applications, and any other systems where every piece of information must be up-to-date (e.g., remaining inventory count).
  • User-specific session data: information directly relating to the user’s current interaction with the application such as their shopping cart or form submissions.
  • Security-sensitive information: data that if slightly out-of-date, would create a security vulnerability.
  • Financial transactions: any operation that deals with money should always operate on the freshest possible data.

Best Practices and Things to Remember

  • Choose your TTLs wisely: The ttl and staleTtl values should be picked such that the data is as fresh as it needs to be, and the user will not wait longer than acceptable for fresh data.
  • Make sure your queues are fast enough: If your workers which perform the background revalidation jobs are slow, you will end up with stale data which simply cannot be revalidated in time.
  • Make sure your closure handles errors: The closure you pass to get() should handle errors itself, because if your background revalidation fails, the old, stale data will keep being served until it expires or successfully revalidates.
  • If your source data changes often, or you want to refresh cache entries outside of the stale-while-revalidate window (e.g. because an administrator changed some data directly in the database), you will need to manually invalidate entries using Cache::forget('your-cache-key').

Conclusion

Cache::flexible() is a great but overlooked utility in Laravel's caching ecosystem. Using the stale-while-revalidate pattern can lead to significant improvement in the perceived performance of your application for expensive operations, without sacrificing eventually consistent data. It's a prime example of how Laravel helps us to build performant web applications.

Thank you for reading this article 😊

For any query, do not hesitate to comment 💬









Previous Post Next Post

Contact Form