Caching · Stage 2 of 3
TTL & Write Invalidation
Delete on write for freshness, and keep a TTL as the safety bound
Foundations
In the first lesson, cached data almost never changed, so a copy stayed correct. Now, what if the data is edited sometimes, and readers must not see the old value for long after an edit?
Two tools bound staleness. A time to live, TTL, makes each entry expire a fixed time after it is filled, so a stale copy cannot outlive it. Invalidation deletes the entry when the data changes: write the store first, then delete the cached key, so the next read misses and reloads the new value. Invalidation gives freshness; the TTL bounds the damage when an invalidation is lost.
Take key k cached with value v1 and a 60-second TTL. At second 30 it is edited to v2: the store commits v2, then k is deleted, so a read at second 45 misses and loads v2. With the TTL alone, that read would still return v1 until second 60.
v2 before deleting k, so the next read misses and reloads the new value. The 60-second TTL only matters if that delete is lost.- Open lesson
Caching
Cache-aside is the read path everything here builds on.
Case Scenario
The design brief
Cache a profile
A profile page is read constantly and edited rarely. Followers should not see a stale name for long after an edit.
- Input
- ttl = 60, db = {"u1": "Ana"}
- Output
- ["Ana", "Ana", None, "Ana Lee", "Ana Lee", "Ana Lee"]
To see how invalidation and a TTL keep cached data fresh, consider a social profile like Instagram's: a profile page is read constantly and edited rarely, and followers should not see an old name for long after an edit. Committing the new name and then deleting the cached profile makes the next read fresh, while a 60-second TTL bounds a lost delete.
Ana’s profile is read constantly and edited rarely. A copy that still says “Ana” after she changes her name to “Ana Lee” is fast but wrong, and a long expiry can expose that wrong name to every follower. Normal post-edit reads should reload “Ana Lee” immediately, while a TTL must still bound stale data if invalidation is lost or races with a read.
Pro
The rest of this is on Pro
The idea above is free. The walkthrough, the cost, and the practice are on Pro.