Redis as a Cache
What you'll learn: How to use Redis as a high-performance cache with time-based expiration, smart eviction policies, and the cache-aside pattern.
Why Redis Excels as a Cache
Redis's in-memory storage and single-threaded architecture make it perfect for caching—reading data at microsecond latency. You've already learned about Redis's TTL (time-to-live) feature; now we'll see how it powers real caching systems.
Time-to-Live (TTL) in Caching
Every cached item can have an expiration time. Set a user profile to expire in 5 minutes, and Redis automatically removes it when stale:
SET user:123 "profile_data" EX 300
This ensures your cache stays fresh without manual cleanup.
Eviction Policies
When Redis runs out of memory, it needs to evict data. You configure policies like:
- LRU (Least Recently Used): Removes items not accessed recently—great for hot data
- LFU (Least Frequently Used): Removes rarely-accessed items—better for popularity-based caching
Think of LRU like clearing out clothes you haven't worn lately, while LFU removes clothes you almost never wear.
Cache-Aside Pattern
The most common caching strategy:
- Read: Check Redis first
- Miss: If not found, fetch from database
- Populate: Store result in Redis with TTL
- Return: Serve data to user
On writes, you invalidate (delete) the cached key, forcing the next read to refresh from the database. This keeps your application in control of cache consistency.
When to Cache
Cache data that's read-heavy, computation-expensive, or tolerable to slight staleness—like product catalogs, user sessions, or API rate limits.
Key Takeaway: Redis caching with TTLs and eviction policies like LRU/LFU, combined with the cache-aside pattern, dramatically reduces database load and improves response times for read-heavy workloads.