Back to results for “Design Patterns in PHP”
PHP › Caching Strategies in PHP

How does cache invalidation work, and why is deciding when to clear a cache often considered one of the harder problems in caching?

Intermediate

Answer

Cache invalidation means removing or updating cached data once it becomes stale or outdated, and it is considered difficult because you must carefully track every place that could change the underlying data and ensure the corresponding cache entry is cleared or refreshed at exactly the right moment, since caching data for too long risks showing users outdated information, while invalidating too aggressively defeats much of the performance benefit caching was meant to provide in the first place.
function updateProduct($id, $data) {
    $database->update($id, $data);
    $cache->delete('product_' . $id);
}
Real-world example An inventory management system explicitly clears a product's cached data immediately after any update to that product, ensuring customers never see outdated stock information even though the product listing page is otherwise heavily cached for performance.

Common follow-ups: What is cache tagging and how does it simplify invalidating related cached items together?;What is the difference between time based expiration and event based invalidation?