← back to stream

Redis expiration

#backend#redis

Redis lets you attach a TTL to any key (EXPIRE key 300 — expires in 5 minutes), and it disappears automatically. This is the mechanism behind every stateful feature you'd build on top of it: sessions (TTL = session lifetime); rate limiters (counter key with window-sized TTL); OTP codes (self-destruct after 60s); cache entries (caching always needs TTLs as a safety net against stale data). How it works under the hood is worth knowing: Redis doesn't have a scheduler going through every key — it uses lazy expiration (check and drop when a key is accessed) plus periodic sampling (every 100ms, sample 20 random keys with TTL, drop expired ones, repeat if more than 25% were expired). Net effect: expired keys use memory until touched, which is fine if you size memory correctly, but occasionally surprising if you thought TTL was instant.