The note in the Laravel 10 upgrade guide regarding Redis cache tags is likely due to the fact that Redis, unlike Memcached, does not natively support tag-based cache invalidation. Laravel has implemented a workaround to provide tag support for Redis, but it comes with limitations and potential performance issues, especially as the size of the cached data grows.
The reason for the recommendation against using Redis for cache tagging is that the implementation is not as efficient as it is with Memcached. When you use tags with Redis in Laravel, it stores the tagged cache keys in a "tag set," and when you need to invalidate a given tag, it retrieves all the keys from the tag set and deletes them one by one. This can be a slow operation if there are many keys associated with a tag, and it can also increase the complexity of your cache management.
If you are using Redis and require cache tagging, you have a few options:
-
Continue using Redis with cache tags, accepting the potential performance implications. If your application is not heavily reliant on cache invalidation by tags or does not operate at a large scale, this might be an acceptable trade-off.
-
Refactor your caching strategy to avoid the need for tags. This could involve using more specific cache keys that you can invalidate individually or in smaller groups without relying on tags.
-
Use a combination of Redis for pub/sub and other features, and Memcached for caching where you need to use tags. This would involve configuring your Laravel application to use different cache drivers for different caching needs.
-
Explore third-party packages or custom solutions that may offer more efficient tag-based caching with Redis.
If you decide to continue using Redis with cache tags, you don't need to change anything immediately, but you should be aware of the potential limitations and monitor your application's performance.
Here's an example of how you might refactor your caching strategy to avoid using tags:
// Instead of using tags, use a structured cache key naming convention.
$cacheKey = "posts.{$postId}.comments";
// When you cache data, you use the structured key.
Cache::put($cacheKey, $comments, now()->addHours(1));
// When you need to invalidate the cache, you can do so directly using the key.
Cache::forget($cacheKey);
In this example, instead of tagging the cache and invalidating by tag, you create a cache key that includes the resource type and identifier, allowing you to target the cache invalidation more precisely.