Best Redis Caching Strategy in Laravel: A Guide to Fast and Efficient Caching

devmahfuz

Mahfuzur Rahman

Posted on November 11, 2024

Best Redis Caching Strategy in Laravel: A Guide to Fast and Efficient Caching

Laravel and Redis are a powerful combination for boosting application speed and performance. Redis, an in-memory key-value store, is perfect for caching, especially when you need fast and frequent data access. In this guide, we'll look at effective caching strategies in Laravel with Redis. We'll cover how to cache data, manage expiration times, and efficiently clear caches.

Why Use Redis Caching?
When you cache with Redis in Laravel, you're essentially saving data temporarily to reduce the time spent querying the database. Caching speeds up data retrieval, reduces server load, and improves user experience by making pages load faster.

Redis is ideal for caching because it:

  • Can quickly store and retrieve data
  • Supports various data structures like strings, lists, and hashes
  • Offers tools for managing cache expiration and clearing old data

Let's explore how to best use Redis caching in Laravel.
Let's say we have a News Paper Site. Now we need to build Api to Get News.

1. Setting Up Basic Caching with Laravel and Redis

To start, let's cache a simple API response, like a list of the latest news articles.

$data = Cache::remember('latest_news', 3600, function () {
    return News::latest()->get();
});
Enter fullscreen mode Exit fullscreen mode

In this example:
Cache::remember stores data with a key (latest_news) and a time-to-live (TTL) of 3600 seconds (1 hour).
If a request for latest_news comes in again within the hour, Redis serves the cached data without querying the database.

2. Structuring Cache Keys and Expiration Times

To keep the data fresh without overloading Redis:
Set shorter TTLs for frequently updated data (e.g., 15–30 minutes).
Use longer TTLs (e.g., 1–2 hours) for data that rarely changes.

Use specific, structured cache keys that reflect the data content. For example:

$cacheKey = "news:category:category_1";
Enter fullscreen mode Exit fullscreen mode

This key is clear, unique, and self-descriptive, making it easy to identify and manage within Redis.

3. Using Tags for Grouped Cache Management

Redis supports tags, which let us manage grouped data under a common tag. For example, tagging all news-related caches with news:

Cache::tags(['news', 'category'])->remember('category_news_1', 3600, function () {
    return $this->news_repository->getNewsByCategory(1);
});
Enter fullscreen mode Exit fullscreen mode

Now, if we want to clear all category-specific news caches (when news is updated), we can use:

Cache::tags(['news', 'category'])->flush();
Enter fullscreen mode Exit fullscreen mode
  1. Caching Paginated and Filtered Data When adding pagination or filters (like category or tags), make each cache key unique to the parameters:
$page = request()->input('page', 1);
$limit = request()->input('limit', 10);
$cacheKey = "news:page_{$page}:limit_{$limit}";

$newsData = Cache::remember($cacheKey, 3600, function () use ($page, $limit) {
    return News::latest()->paginate($limit, ['*'], 'page', $page);
});
Enter fullscreen mode Exit fullscreen mode

This way:
A unique cache entry is created for each page and limit.
Users can fetch pages quickly without re-querying the database.

For filtered data, include the filter parameters in the key:

$categoryId = request()->input('category_id');
$cacheKey = "news:category_{$categoryId}:page_{$page}:limit_{$limit}";
Enter fullscreen mode Exit fullscreen mode

This ensures each category and page combination has its own cache entry.

5. Automatic Cache Invalidation on Data Changes

Clearing or "invalidating" caches ensures users see updated data when necessary. Here's how to automate it:
Use model observers for events like created, updated, or deleted to clear related caches.
Example observer for news:

public function created(News $news) {
    Cache::tags(['news', 'pagination'])->flush();
}

public function updated(News $news) {
    Cache::tags(['news', 'pagination'])->flush();
}
Enter fullscreen mode Exit fullscreen mode

Now, whenever news is added or updated, all news and pagination tagged caches are flushed, keeping the data fresh.

6. Summary and Best Practices

To make caching work effectively:
Unique Keys: Structure keys with parameters like category, page, and limit.
Tags for Grouped Data: Use tags to easily manage caches for specific data groups.
Automate Invalidation: Set up observers to clear outdated caches on data changes.
Set Sensible Expiration: Choose TTLs based on how often the data changes, typically between 15 minutes and 1 hour.

Using Redis with this structured approach makes Laravel APIs respond faster, improves server load management, and ensures a reliable, efficient cache strategy that's easy to manage.

💖 💪 🙅 🚩
devmahfuz
Mahfuzur Rahman

Posted on November 11, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related