Caching SystemsLesson 4.4
Redis vs Memcached — which cache to use
Redis data structures, Memcached simplicity, persistence options, clustering, pub/sub, atomic operations, multi-threading
Two Dominant Choices
Both are in-memory key-value stores. Choose Memcached for pure caching simplicity; choose Redis when you need more than caching.
Redis Advantages
- Rich data types: strings, hashes, lists, sets, sorted sets, streams
- Optional persistence (RDB snapshots, AOF write-ahead log)
- Pub/Sub for real-time messaging
- Atomic operations: INCR, SETNX, ZADD
- Lua scripting for complex atomic operations
- Redis Cluster for horizontal sharding
# Redis atomic counter (rate limiting)
INCR user:123:requests
EXPIRE user:123:requests 60
# Sorted set for leaderboard
ZADD leaderboard 1500 'user:alice'
ZADD leaderboard 2100 'user:bob'
ZREVRANGE leaderboard 0 9 WITHSCORES # top 10Memcached Advantages
- Multi-threaded: better CPU utilization on multi-core machines
- Simpler mental model: strings only
- Lower memory overhead per connection
When to Use Memcached
Pure read cache for simple string data at very high scale where multi-threaded performance matters. Most teams default to Redis due to its versatility. Memcached is rarely the right answer in 2024 unless you're already operating at massive scale.
