0
0
Redisquery~5 mins

Cache invalidation strategies in Redis

Choose your learning style9 modes available
Introduction
Cache invalidation strategies help keep stored data fresh and accurate by removing or updating old information in the cache.
When data changes in the main database and the cache needs to reflect those changes.
When cached data becomes outdated after a certain time and should be refreshed.
When you want to avoid serving wrong or stale information to users.
When you want to improve performance by controlling how often cache updates happen.
When you want to balance between fast access and data accuracy.
Syntax
Redis
No single Redis command for cache invalidation; strategies use commands like DEL, EXPIRE, or Lua scripts.
Cache invalidation is a strategy, not a single command.
Redis commands like DEL remove keys, EXPIRE sets time limits on keys.
Examples
Deletes the cached data immediately to invalidate it.
Redis
DEL cache_key
Sets the cache to expire after 3600 seconds (1 hour), automatically invalidating it.
Redis
EXPIRE cache_key 3600
Sets a cache key with a value that expires after 60000 milliseconds (1 minute).
Redis
SET cache_key value PX 60000
Advanced method to safely invalidate cache based on custom logic.
Redis
Using a Lua script to check and delete stale cache atomically
Sample Program
This example sets a cache key with a 10-second expiry, retrieves it, deletes it manually, then tries to get it again to show it is gone.
Redis
SET user:123 "John Doe" EX 10
GET user:123
DEL user:123
GET user:123
OutputSuccess
Important Notes
Always choose the invalidation strategy that fits your app's speed and accuracy needs.
Time-based expiration (TTL) is simple but may serve stale data until expiry.
Manual deletion ensures immediate invalidation but requires extra logic.
Summary
Cache invalidation keeps cached data fresh and accurate.
Common methods include manual deletion and time-based expiration.
Choosing the right strategy balances speed and data correctness.