intermediate

TTL

Set expirations deliberately for caches, sessions, tokens, rate limits, and cleanup policies.

TTL (time to live) attaches expiration to keys — Redis deletes them lazily on access and actively via periodic sampling. TTL is how caches, sessions, OTP codes, rate-limit buckets, and privacy-sensitive data automatically disappear.

					SET cache:item:9 "..." EX 300        # expires in 300 seconds
SETEX session:tok 3600 "..."
TTL cache:item:9                     # seconds remaining; -1 no expire; -2 missing
EXPIRE dedup:evt:991 86400
PERSIST cache:item:9                 # remove TTL — use deliberately
				

| Policy choice | Why it matters | |---------------|----------------| | Fixed TTL | Predictable staleness bound | | TTL jitter | Spreads expirations — reduces stampede | | Per-key vs global | Sessions vs cache namespace rules | | No TTL | Only for durable Redis use cases |

Expiration is not real-time to the millisecond — plan for slightly stale reads and delayed cleanup. Sliding expiration (`EXPIRE` on each access) suits session activity; fixed TTL suits immutable cache entries.

On interviews: tie TTL to freshness SLA, security, and thundering herd risk.

Common pitfalls: identical TTL on millions of keys expiring together; assuming TTL equals strict deadline semantics; no TTL on PII; forgetting TTL refresh rules on partial updates.

The trade-off is automatic cleanup and bounded staleness versus predictable miss timing — TTL simplifies operations but requires jitter and invalidation strategy for correctness-sensitive caches.

Checklist:

  • State freshness SLA per key class.
  • Add jitter to popular key TTLs.
  • Document refresh vs fixed expiration.
  • Handle cache miss after expiry in app code.