Cache-aside, write-through and invalidation
Cache-aside is the default pattern because it fails safe: a cache outage becomes a slow request, not a wrong one.
Open this lesson in the learning hubKey points
- Cache-aside reads the key, and on a miss loads from the database and writes it back with
SET key val EX ttl. - On a write, delete the key after the database commits - updating the cache instead races with concurrent readers.
- Write-through updates cache and database together, which keeps them consistent but adds a Redis failure to every write.
- Write-behind acknowledges the write from Redis and flushes later, so a crash before the flush loses committed data.
- Track the hit ratio from
keyspace_hitsandkeyspace_missesinINFO stats; below roughly 80 percent the cache is barely paying for itself. - Cache the misses too: a short TTL on a "not found" marker stops one bad ID hammering the database forever.
Example
GET product:991
(nil) # miss
# ... SELECT * FROM product WHERE id = 991
SET product:991 "{...}" EX 300 NX # populate, 5 minute TTL
# on update, invalidate AFTER the database commit
DEL product:991
# or UNLINK for a large value - frees memory on a background thread
UNLINK product:991
Read through the cache, invalidate after the commit, and never write a cache key without an expiry.
This is a reading copy. The full lesson — with the visual explainer, the interactive lab and a Run button for the code — lives in the Redis Course course, and every lesson in it is listed on the Redis Course contents page.