🌐Key Takeaways
- 1Redis: feature-rich (data structures, pub/sub, Lua scripting), single-threaded event loop, supports persistence
- 2Memcached: simpler, multi-threaded, pure caching (no persistence), slightly faster for simple get/set
- 3CDN as cache: edge caching for static content and API responses, global distribution
- 4Redis is the default choice for 95% of caching needs in modern systems
Choosing a Caching System
While the caching concepts (eviction, write strategies) are database-agnostic, your choice of caching system determines what's possible. Redis has become the de facto standard, but understanding the alternatives helps you make informed decisions.
Redis vs Memcached
| Feature | Redis | Memcached |
|---|---|---|
| Data types | Strings, hashes, lists, sets, sorted sets, streams, bitmaps | Strings only |
| Threading | Single-threaded (event loop) | Multi-threaded |
| Persistence | RDB snapshots + AOF log | None |
| Replication | Primary-replica | None (client-side) |
| Pub/Sub | Yes | No |
| Lua scripting | Yes | No |
| Max value size | 512 MB | 1 MB |
| Cluster mode | Redis Cluster (auto-sharding) | Client-side consistent hashing |
| Use when | Rich data types, persistence, pub/sub needed | Simple get/set, multi-threaded perf needed |
Redis Data Structures in Action
# Strings — basic cache
SET user:123 '{"name":"Alice","email":"alice@co.com"}' EX 3600
# Hash — structured data without serialization
HSET user:123 name "Alice" email "alice@co.com" login_count 42
HINCRBY user:123 login_count 1
# Sorted Set — leaderboard
ZADD leaderboard 1500 "player:1" 2300 "player:2" 900 "player:3"
ZREVRANGE leaderboard 0 9 WITHSCORES # Top 10
# List — recent activity feed
LPUSH feed:user:123 '{"type":"like","post_id":456}'
LTRIM feed:user:123 0 99 # Keep last 100 items
# Set — unique visitors
SADD visitors:2024-03-20 "user:123" "user:456"
SCARD visitors:2024-03-20 # Count unique
# HyperLogLog — approximate unique count (12KB per key!)
PFADD pageviews:home "user:1" "user:2" "user:3"
PFCOUNT pageviews:home # ~3 (approximate)✅Redis at Scale
Single Redis instance: ~100K-300K QPS. Redis Cluster: shards data across 3+ nodes with automatic failover. AWS ElastiCache or Redis Cloud handles the operational burden. For >1M QPS, use a combination of Redis Cluster + local in-memory caching (L1 cache) in your application servers.
Advantages
- •Redis handles 95% of caching needs
- •Rich data structures enable complex patterns
- •Persistence options for durability
Disadvantages
- •Single-threaded limits per-instance throughput
- •Memory is expensive at scale
- •Operational complexity of Redis Cluster
🧪 Test Your Understanding
Knowledge Check1/1
Which Redis data structure is best for implementing a leaderboard?