exercises and solutions
Caching exercises
Caching exercises should start with the reason for caching and the invalidation rule. Reading and writing a key is easy; deciding when stale data is acceptable is the real application skill.
Practical Example
<?php
declare(strict_types=1);
$cache = [];
$key = 'product:123';
$cache[$key] = ['name' => 'Notebook', 'expires_at' => time() + 300];
echo $cache[$key]['name'] . PHP_EOL;
// Prints:
// Notebook
Cache data that is expensive to compute or fetch, but design invalidation first. A stale cache bug can be worse than a slow query.
Ask learners to describe the key shape, lifetime, miss behaviour, and update path. Later exercises can add stampede protection or shared-cache failure handling.
Practice
Design A Product Cache Entry
Describe the key, value, lifetime, miss behaviour, and invalidation rule for caching a product detail read.
Show solution
The invalidation rule matters more than the storage syntax because stale product details can mislead users.
Prevent A Stale Permission Cache
Describe how a cached permission result can become unsafe after an administrator revokes access. Define a key, invalidation rule, and failure behaviour.
Show solution
Use a key that identifies the user and protected resource or role version. Delete affected keys when permissions change, and keep a short TTL as a backstop. For sensitive decisions, prefer a safe fallback when the cache is unavailable.
Permission caching is not only a performance concern. A stale allow result can become an authorisation defect.