Caching & Session
Redis Caching & Session Storage
Learn how to use Redis as a high-performance cache layer and session store for web applications. Reduce database load and speed up response times.
Real-World Business Scenario
An e-commerce platform handles 50,000 concurrent users during flash sales. Product detail pages hit the database on every request, causing response times to spike to 3+ seconds. User sessions stored in the application server are lost on restart. By introducing Redis as a cache and session store, page load drops to under 50ms and sessions persist across deployments.
Architecture Diagram
Client Request → Nginx Load Balancer
↓
App Server (Node.js / Spring Boot)
↓ Check Redis Cache
┌─────────────────────────────────┐
│ Redis (Cache + Session Store) │
│ ┌───────────┐ ┌──────────────┐ │
│ │ Cache TTL │ │ Session Hash │ │
│ │ product:* │ │ sess:token:* │ │
│ └───────────┘ └──────────────┘ │
└─────────────────────────────────┘
↓ Cache Miss Only
PostgreSQL / MySQL (Primary DB)
Key Commands Explained
Performance Analysis
Redis GET/SET: ~0.1ms latency vs ~5-50ms for a typical SQL query. 100x-500x faster for cached reads.
Session in Redis Hash: O(1) per field access. Supports partial updates without full serialization overhead.
Memory: A typical session (500 bytes) × 100K users = ~50MB. Redis handles this easily on a single node.
Throughput: Single Redis instance handles 100K+ ops/sec. Cluster mode scales linearly.
Common Pitfalls
Cache Stampede: When a hot key expires, hundreds of concurrent requests hit the DB simultaneously. Use mutex locks (SET NX) or staggered TTLs to prevent this.
Stale Data: Cache-aside pattern can serve outdated data if DB writes don't invalidate the cache. Always DEL the cache key after DB updates.
Session Size Bloat: Storing entire user objects in sessions leads to memory waste. Keep sessions lean — store only IDs and references.
No Persistence Config: If Redis restarts without RDB/AOF enabled, all sessions are lost. Enable persistence or use Redis Cluster with replicas.
Best Practices
Use consistent key naming: cache:{entity}:{id} for cache, sess:{token} for sessions.
Always set TTL on cache keys. Unbounded caches lead to memory exhaustion.
Implement cache-aside (lazy loading) pattern: read from cache first, populate on miss.
Use HSET for sessions instead of SET with JSON — enables partial field updates.
Add jitter to TTL values (e.g., 3600 ± 300s) to prevent mass expiration.
Monitor cache hit rate with INFO stats. Aim for 90%+ hit rate.
Runnable Demo
Redis Demo
Click "Step" or "Run All" to execute commands...
▌