patternpythonredisModeratepending
Redis caching patterns with TTL and invalidation
Viewed 0 times
cache asidewrite throughcache invalidationttlredis patterns
Problem
Need caching strategies that balance freshness and performance, with proper invalidation.
Solution
Common Redis caching patterns:
TTL guidelines:
import redis
import json
import hashlib
r = redis.Redis(decode_responses=True)
# Pattern 1: Cache-aside (Lazy loading)
def get_user(user_id):
key = f'user:{user_id}'
cached = r.get(key)
if cached:
return json.loads(cached)
user = db.query('SELECT * FROM users WHERE id = %s', user_id)
r.setex(key, 3600, json.dumps(user)) # TTL: 1 hour
return user
# Pattern 2: Write-through
def update_user(user_id, data):
db.query('UPDATE users SET ... WHERE id = %s', user_id)
r.setex(f'user:{user_id}', 3600, json.dumps(data)) # Update cache too
# Pattern 3: Cache invalidation on write
def update_user_v2(user_id, data):
db.query('UPDATE users SET ... WHERE id = %s', user_id)
r.delete(f'user:{user_id}') # Delete, let next read re-populate
# Pattern 4: Tag-based invalidation
def cache_with_tags(key, value, ttl, tags):
pipe = r.pipeline()
pipe.setex(key, ttl, json.dumps(value))
for tag in tags:
pipe.sadd(f'tag:{tag}', key)
pipe.execute()
def invalidate_tag(tag):
keys = r.smembers(f'tag:{tag}')
if keys:
r.delete(*keys)
r.delete(f'tag:{tag}')
# Usage:
cache_with_tags('product:123', product, 3600, ['products', 'category:electronics'])
invalidate_tag('products') # Clears all product caches
# Pattern 5: Request-scoped dedup
def cached_query(query, params, ttl=300):
key = f'query:{hashlib.md5(f"{query}:{params}".encode()).hexdigest()}'
cached = r.get(key)
if cached:
return json.loads(cached)
result = db.query(query, params)
r.setex(key, ttl, json.dumps(result))
return resultTTL guidelines:
- User sessions: 30 min
- API responses: 5-15 min
- Static config: 1-24 hours
- Computed aggregates: 1-5 min
Why
Cache invalidation is one of the two hard problems in CS. Using TTL as a safety net with explicit invalidation on writes provides good balance.
Context
Adding caching to web applications
Revisions (0)
No revisions yet.