Redis Caching Setup for Real Performance Gains
Redis is not magic speed dust—it is a structured cache and queue backend. Used correctly, it cuts dashboard load times from 800ms to 40ms. Used wrong, you cache stale billing data and debug for days.
Laravel Redis Configuration
# .env
REDIS_CLIENT=phpredis
REDIS_HOST=127.0.0.1
REDIS_PASSWORD=null
REDIS_PORT=6379
CACHE_STORE=redis
QUEUE_CONNECTION=redis
SESSION_DRIVER=redis
// config/database.php redis section
'redis' => [
'client' => env('REDIS_CLIENT', 'phpredis'),
'default' => [
'host' => env('REDIS_HOST', '127.0.0.1'),
'password' => env('REDIS_PASSWORD'),
'port' => env('REDIS_PORT', 6379),
'database' => 0,
],
'cache' => [
'database' => 1,
],
],
Caching Patterns
Cache expensive aggregations with explicit TTLs and cache tags for invalidation on writes. Example: dashboard stats cached 5 minutes, busted when invoice created.
Cache::tags(['tenant:'.$tenantId, 'stats'])
->remember("dashboard:{$tenantId}", 300, fn () => $this->buildStats());
- Separate Redis DB index for cache vs sessions vs queues
- Set
maxmemory-policy allkeys-lruon small instances - Monitor hit rate—below 70% means wrong keys or TTL too short
Production Redis Hardening
Bind Redis to private network interface only. Require AUTH password even inside VPC. Disable FLUSHALL for application users—one wrong artisan command should not wipe entire cache cluster.
Enable AOF persistence if Redis holds session data you cannot lose on restart. For pure cache, RDB snapshots or no persistence is fine—design for cold cache warmup on restart.
ElastiCache or managed Redis offloads patching and failover. Self-hosted Redis on same VPS as app works until memory contention causes both to swap—give Redis dedicated instance above 2GB working set.
Alert on evicted_keys and used_memory hitting maxmemory—silent evictions cause mysterious cache misses masquerading as application bugs. Document which keys are safe to lose versus session keys requiring persistence or shorter TTL with refresh on activity.
Laravel Cache Patterns in Practice
Remember() wrapper convenient but hides stampede risk on hot keys—use locks for expensive rebuilds during flash sales. Cache user permissions with tag invalidation on role change—stale permissions cache is security bug showing features user should not access until TTL expires.
Horizon dashboard for queue monitoring complements Redis cache metrics—same Redis instance handling both needs memory headroom planning; queues balloon during outages if workers down while cache competes for same maxmemory.
Never run KEYS in production scripts—use SCAN. Monitor slowlog for expensive operations that spike latency for every connected client simultaneously during maintenance gone wrong.
High Availability
Redis Sentinel or managed failover for session storage prevents mass logout during node failure. Test failover quarterly—applications must reconnect cleanly. For pure cache, brief unavailability is acceptable; for sessions, it is not—design TTL and persistence accordingly per use case.
Document cache key taxonomy in README—new engineers guessing keys cause collisions and stale data mysteries. Prefix environment: prod vs staging prevents accidental cross-environment flush scripts run against wrong host during late-night debugging sessions.
Size Redis memory with 25% headroom above working set measured during peak—eviction storms during flash sales cause thundering herd on database exactly when it least needs load multiplication effect cascading failure risk real not theoretical experienced teams know.
Revisit cache TTL values quarterly against current SLAs—features ship faster than invalidation logic updates, and stale dashboard numbers erode support trust until someone catches the mismatch in an executive review.
Load-test cache failure scenarios—what happens when Redis disappears entirely? Graceful degradation beats hard 500s on every page view during brief outages.
Production Hardening
Bind Redis to private interfaces only—exposed port 6379 is still a top attack vector. Enable AOF if sessions cannot be lost on restart. Audit cache TTLs quarterly against product SLAs.
Document cache key prefixes per environment so a staging flush script never touches production keys during late-night debugging.
Frequently Asked Questions
Redis vs Memcached?
Redis supports persistence, pub/sub, and richer data structures. Memcached is simpler pure cache—Redis wins for Laravel queues too.
Do I need Redis Cluster?
Single instance handles 100k ops/sec for most SaaS. Cluster when memory exceeds one node or you need HA with automatic failover.
How do I avoid cache stampede?
Use Cache::lock() around expensive rebuilds or probabilistic early expiration.