2.3.1. Caching, Expiration, and Invalidation
💡 First Principle: A cache is a bet that the recent past predicts the near future. Expiration (TTL) bounds how long you're willing to bet; invalidation cancels the bet the moment you know it's wrong. Every caching pattern is some arrangement of those two controls.
The foundational pattern — and the exam's default — is cache-aside: the application owns the logic, the cache is a passive layer.
The operational vocabulary is a handful of commands whose semantics the exam checks precisely:
| Command | Effect |
|---|---|
SET key val EX 300 | Write with a 300-second TTL in one atomic step |
GET key | Read; nil on miss or after expiry |
DEL key | Explicit invalidation — remove now |
EXPIRE key 60 | Set/replace TTL on an existing key |
TTL key | Remaining lifetime (-1 = no TTL, -2 = gone) |
Invalidation strategy is the design decision layered on top. TTL-only accepts bounded staleness (fine for a model's cached FAQ answer). Invalidate-on-write deletes the key whenever the source changes (right for user-facing state like profiles). Key versioning sidesteps deletion by embedding a version in the key (profile:1001:v7) so stale entries simply age out. Choose by asking: how expensive is serving stale data, and can the writer reach the cache?
When memory fills, the eviction policy decides what dies: allkeys-lru (evict least-recently-used anywhere) suits pure caches; noeviction (writes fail instead) suits Redis-as-working-store. Because eviction can remove any key at any time in LRU modes, cache-miss handling isn't optional code — it's the load-bearing path.
⚠️ Exam Trap: SET without EX (then a separate EXPIRE) leaves a race window where the key exists forever if the process dies between commands — and "keys that never expire" is how caches quietly become full. The atomic SET ... EX form is the correct answer when offered.
Reflection Question: For cached RAG answers derived from documents that update weekly, which invalidation strategy fits — and what changes if documents update unpredictably?