Middle
How was cache invalidation done in Redis?
sobes.tech AI
Answer from AI
Cache invalidation in Redis is usually done in several ways:
-
Deleting the key — when data in the main database changes, delete the corresponding key from Redis using the
DELcommand. -
Setting a Time To Live (TTL) — assign a lifespan to the key, after which it will be automatically removed.
-
Updating the cache — immediately update the value in Redis after data changes.
Example in Python using redis-py:
import redis
r = redis.Redis()
# Invalidate the key
r.delete('user:123')
# Or update with TTL
r.set('user:123', 'new_data', ex=3600) # key lives for 1 hour