Cheat sheet · Back end and data
Redis and caching cheat sheet
Core Redis commands and the caching patterns, limits and problems you must know.
- Sections
- 4
- Items
- 20
- Area
- Back end and data
- Download
- PNG, PDF
Cheat sheet
Redis and caching
Core Redis commands and the caching patterns, limits and problems you must know.
Keys and values
SET name "Asha" EX 60- Store a value for 60 seconds
GET name- Read it
DEL name- Delete it
EXPIRE name 300 / TTL name- Set a lifetime / see time left
INCR counter- Add 1 (safe when many users do it at once)
EXISTS name- Is the key there?
Data types
HSET user:1 name Asha / HGET user:1 name- A hash: fields inside one key
LPUSH q a / RPOP q- A list used as a queue
SADD tags a b / SMEMBERS tags- A set of unique values
ZADD board 100 asha / ZRANGE board 0 9 REV- A sorted set, such as a leaderboard
PUBLISH ch msg / SUBSCRIBE ch- Send and receive messages
Caching patterns
Cache-aside- App checks the cache; on a miss it reads the database and fills the cache
Write-through- Write to the cache and the database together
Write-back- Write to the cache first, save to the database later (faster, riskier)
TTL- Every entry expires after a set time
LRU eviction- When full, remove the entry used longest ago
Common problems
Stampede- A popular key expires and many requests hit the database at once. Fix: lock, or refresh early
Penetration- Requests for keys that never exist skip the cache. Fix: cache the "not found" answer briefly
Avalanche- Many keys expire together. Fix: add a random time to each TTL
Stale data- Cache shows old values. Fix: delete the key when the data changes
Remember
- Cache data that is read often and changes rarely. Do not cache what must always be exact.
- Name keys in a pattern such as user:42:profile so you can find and delete them.
Learn it properly
A cheat sheet helps you remember. These lessons explain the ideas step by step, with examples.