Cache-aside, TTL and eviction
A copy, not the source of truth
A cache keeps frequently requested data close to the application, often in memory. In a bookstore, reading the same product description from the database for every visitor wastes work. With cache-aside, the application checks the cache first. A hit returns a stored copy; a miss reads the database and fills the cache. The database remains authoritative. Never treat a cached stock count as permission to sell an item.
Follow a read and an update
Set a time to live (TTL) of 60 seconds when storing a description. At time 0 the first read misses, at time 20 the next read hits. At time 30 an editor changes the description in the database; after successful commit, invalidate the old cache key. The read at time 31 fetches the new value and stores it until time 91. This is a simplified sequential trace; concurrent readers can refill stale values after invalidation. Use versioned keys or coordinated updates where freshness is critical.
t=0 MISS → v1t=20 HIT → v1t=30 DB commit v2; invalidatet=31 MISS → v2t=91 TTL expired → MISSExpiration is not eviction
Expiration means a TTL has elapsed; eviction removes data under memory pressure according to engine policy, potentially before its TTL. A key may also be explicitly deleted. A cache miss is normal, not necessarily an outage. A cache stampede happens when many requests miss the same key at once. Coalesce concurrent fills, randomize expiry within a bounded range and limit fallback concurrency to protect the database. Do not retry indefinitely.
Measure the benefit and protect sessions
For 100 reads with 80 hits, the hit ratio is 80/100 = 80%. With one database read per miss, 20 database reads remain; this excludes writes, retries and refreshes. Observe hit ratio alongside database load and latency. For user sessions, use tenant-aware keys, enforce authentication before cache access, avoid logging tokens, and decide whether losing a session is acceptable. Expiring or evicting a session may require reauthentication; TTL alone is not a revocation mechanism. Practice: explain how to handle a cache outage without overwhelming the database.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Cache-aside, TTL and eviction — knowledge check
Apply cache and database decisions to fictional workloads.
A book description is absent from the cache. What should cache-aside do?
A key is removed after 10 seconds despite a 60-second TTL. Which is a plausible cause?
What should occur after a successful authoritative description update?
Many requests miss the same key simultaneously. What helps protect the database?
80 of 100 reads hit the cache. With one source read per miss, how many source reads occur?