URL Shortener · Stage 3 of 3
Lazy Expiry on the Read Path
Check expiry on every read, and delete expired rows in the background
Foundations
So far, a record lived forever once created. Now, what if each record dies at a timestamp, and nobody may read it after that moment, even if cleanup is running late?
Store the expiry time on the record, and check it on every read, including reads served from a cache; an expired record is answered as missing at once. Deletion is a separate, lazy job that removes expired rows in batches, off the request path, so a late cleanup never changes what readers see. A cached copy should expire no later than the record itself.
Take a record with expires_at = 100. Reads at times 10 and 50 return it, even from the cache, after checking that now < 100. A read at time 120 returns not found and evicts the cached copy, though the row is still on disk; a background job deletes it in its next batch.
- Open lesson
Requirements
Each worked system starts from a scoped list of verbs and numbers.
Case Scenario
The design brief
Design an expiring link
Links die at a timestamp. Visitors after that see a 404. Owners can see which of their links are still live.
- Input
- rows = {"x7": {"url": "/sale", "expires": 100}}, cache = {}, reads = [["x7", 10], ["x7", 50], ["x7", 120], ["q2", 5]]
- Output
- [301, 301, 404, 404]
To see how lazy expiry keeps reads correct, consider expiring links in a URL shortener like bit.ly: a short link dies at a timestamp, visitors after that see a 404, and owners can see which of their links are still live. Every redirect, even a cache hit, compares expires_at; a background job deletes dead rows later.
A link that dies at time 100 must stop redirecting at that boundary even if it was popular a moment earlier. Cleanup can run late, and an owner still needs an efficient list of live links, so deletion timing cannot define visitor behavior. A cached response for x7 must return 404 at time 120 and must never preserve a 301 past expiry.
Pro
The rest of this is on Pro
The idea above is free. The walkthrough, the cost, and the practice are on Pro.