Clearing Redis Cache Without Disrupting User Sessions in Laravel 5
When you integrate Redis as a session driver in Laravel 5, you gain significant performance benefits, but it introduces a specific architectural constraint: your application's memory and user state are tightly coupled to the same key space. If you blindly flush the entire Redis instance using redis-cli FLUSHALL or a generic cache clear method, you will inevitably wipe out active sessions along with your cached data. This results in users being unexpectedly logged out immediately after a deployment or cache maintenance task, which is often unacceptable for production environments.
The core challenge lies in distinguishing between transient application data (cache) and persistent user state (sessions) within the same store. Since you have explicitly ruled out using separate Redis instances for sessions and cache, you must rely on Laravel's key naming conventions to achieve selective deletion.
Understanding Laravel's Key Naming Strategy
Laravel 5 relies heavily on prefixing keys to namespace different data types. When using the redis session driver, the configuration typically looks like this:
'mysql' => [
'driver' => 'redis',
'connection' => 'default',
'lock_col' => 'lock_col',
'key_prefix' => 'laravel_session_', // Default might vary
],
However, the default behavior for Redis sessions in Laravel 5 often prefixes keys with session_ or relies on a configurable prefix defined in your .env file or configuration array. By contrast, general cache data usually shares the same redis.default connection but lacks the session_ prefix (or uses a different one if configured).
To clear only the cache while preserving sessions, you must target keys that do not match the session prefix. The most robust approach is to leverage Laravel's command-line interface or a direct Redis script that filters based on these patterns.
Using Artisan Commands for Selective Clearing
The safest way to manipulate this separation without writing raw SQL or Redis scripts is to utilize Artisan commands that respect key prefixes. If your CACHE_DRIVER is set to redis, you can clear the cache layer specifically:
php artisan cache:clear
This command iterates through the configured cache store and deletes keys matching the cache prefix. Because it operates at the application logic level rather than the storage driver level, it should not touch keys prefixed with session_. However, this assumes your configuration strictly separates the prefixes. If you are using a shared prefix strategy where both sessions and cache use myapp: as a base, this approach fails unless the specific sub-paths differ significantly.
If your setup does not enforce distinct prefixes via configuration, you must rely on pattern matching within Redis itself. You can use the KEYS command to inspect the store, but be aware that KEYS * is dangerous in production due to performance hits. Instead, filter for specific patterns:
# Inspect session keys (adjust prefix based on your config)
redis-cli KEYS "session_*"
# Clear only non-session keys if they share a root prefix
# This assumes cache keys do not match the session pattern
redis-cli EVAL "return redis.call('DEL', unpack(redis.call('KEYS', 'cache_*')))" 0 "cache_*"
Implementing a Custom Script for Safety
For production environments where you need to guarantee zero impact on sessions, injecting a small Lua script is often superior to chaining multiple KEYS and DEL commands. This prevents race conditions where a session key might be generated between the list of keys retrieval and the deletion loop.
You can create a file at resources/lua/clear-cache.lua:
local cache_keys = redis.call('KEYS', 'cache_*')
for _, key in ipairs(cache_keys) do
redis.call('DEL', key)
end
return #cache_keys
Then execute it via CLI:
redis-cli EVAL "$(cat resources/lua/clear-cache.lua)" 0 "cache_*"
This ensures that only keys matching the cache_ pattern are removed, leaving session_* entries untouched.
Configuration Best Practices
The most reliable long-term solution is to configure your .env file to enforce distinct prefixes from the start. Set your cache driver configuration to use a different namespace than sessions:
SESSION_DRIVER=redis
SESSION_PREFIX=session_
CACHE_PREFIX=cache_
With this separation, any standard php artisan cache:clear or even a generic FLUSHDB (used with extreme caution) will behave predictably. Always verify your key patterns using redis-cli KEYS "*" before executing bulk operations to ensure your prefix strategy aligns with your actual data layout.