Complete the code to set a cache key with an expiration time to prevent stale data.
redis.set('user:123', user_data, ex=[1])
Setting an expiration time (in seconds) like 3600 ensures the cache expires after one hour, helping prevent stale data.
Complete the code to acquire a lock key before regenerating cache to prevent cache stampede.
if redis.setnx('lock:user:123', '1'): redis.expire('lock:user:123', [1]) # regenerate cache
Setting a short expiration (like 10 seconds) on the lock prevents deadlocks if the process crashes.
Fix the error in the code that tries to get cached data and falls back to regeneration if missing.
data = redis.get('user:123') if data is [1]: # regenerate cache
Redis returns None if the key does not exist, so checking for None detects cache miss.
Fill both blanks to implement a safe cache regeneration with lock and expiration.
if redis.setnx('lock:user:123', '1'): redis.expire('lock:user:123', [1]) data = regenerate_data() redis.set('user:123', data, ex=[2]) redis.delete('lock:user:123')
Lock expiration is short (10 seconds) to avoid deadlocks. Cache expiration is longer (3600 seconds) to keep data fresh.
Fill all three blanks to implement cache stampede prevention with lock check, regeneration, and fallback.
data = redis.get('user:123') if data is [1]: if redis.setnx('lock:user:123', '1'): redis.expire('lock:user:123', [2]) data = regenerate_data() redis.set('user:123', data, ex=[3]) redis.delete('lock:user:123') else: time.sleep(0.1) data = redis.get('user:123')
Check for None to detect cache miss. Lock expiration is short (10 seconds). Cache expiration is longer (3600 seconds) to keep data fresh.