Caching without the guesswork
A fictional teaching module about freshness, expiry and observable cache behavior.
40-minute learning session2 practice exercisesA fictional teaching module about freshness, expiry and observable cache behavior.
40-minute learning session2 practice exercisesDevelopers who can read a small function and want to reason about stale data.
A fast answer is useful only when its freshness matches the task.
A freshness window is the maximum acceptable age of a stored result for a stated use.
A training weather widget may tolerate five minutes; a different task may not.
A cached response is not automatically wrong. Its age must be compared with the requirement.
An entry is fresh while now is earlier than its expiresAt timestamp.
An entry expiring at minute 15 is a hit at minute 14 and expired at minute 15.
An expiry timestamp is not the same as the time the entry was created.
Use fictional integer-minute timestamps. The cache holds result = 42 and expiresAt = 15.
At minute 14: { kind: 'hit', value: 42 }.
function read(now, entry) {
if (entry && now < entry.expiresAt) {
return { kind: 'hit', value: entry.value };
}
return { kind: 'refresh-needed' };
}
read(14, { value: 42, expiresAt: 15 });Follow the supplied example from its starting state to its result.
| Step | State | Why it changes |
|---|---|---|
| Read the clock | now = 14 | The caller supplies the comparison time. |
| Compare | 14 < 15 is true | The entry is still inside its freshness window. |
| Return | kind = hit; value = 42 | No refresh is required for this example. |
What does read(15, entry) return when entry.expiresAt is 15? Explain the comparison.
Use the supplied strict less-than rule.
State the returned kind and explain equality.
Exercise ID: boundary · Compare your reasoning with the answer clinic.
A fictional dashboard accepts results at most two minutes old. Describe the expiry rule without assuming how often users visit.
Do not promise that expiry triggers a background refresh.
Separate maximum accepted age from the action on the next read.
Exercise ID: policy · Compare your reasoning with the answer clinic.
It returns { kind: 'refresh-needed' }.
At equality, 15 < 15 is false. The entry is no longer fresh.
Set the expiry to the supplied observation time plus two minutes; refresh when a later read finds it expired.
The freshness rule controls acceptance. It does not schedule work by itself.
Original synthetic teaching material in this package; not a report of a production system.
Arrow keys / Home / End to navigate · N for notes · all pages are available when printing.