What is Redis?
Redis (Remote Dictionary Server) is an in-memory data store used as a database, cache, and message broker. It delivers sub-millisecond response times, making it essential for high-performance web applications.
Caching Patterns
- Cache-Aside: Application checks cache first. On miss, reads from database and populates cache. Most common pattern.
- Write-Through: Writes go to cache and database simultaneously. Ensures consistency but adds write latency.
- Write-Behind: Writes go to cache immediately, database asynchronously. Fast but risk of data loss.
Common Use Cases
# Session storage
SET session:abc123 '{"user_id":42,"role":"admin"}' EX 3600
# API response caching
GET cache:api/products?page=1
# Rate limiting
INCR rate:ip:192.168.1.1
EXPIRE rate:ip:192.168.1.1 60
# Real-time leaderboards
ZADD leaderboard 1500 "player:42"
ZREVRANGE leaderboard 0 9 WITHSCORES
Cache Invalidation
"There are only two hard things in Computer Science: cache invalidation and naming things." — Phil Karlton
Use TTL (Time-To-Live) for automatic expiration. For immediate invalidation, publish cache invalidation events when data changes. Use Redis Pub/Sub for distributed cache invalidation.