Skip to content
intermediate Phase 69 · Cache Advanced

Cache Invalidation — When and How Cache Clears

Understanding cache invalidation in Magento 2: when cache clears, tag-based invalidation, cache stampede prevention, and invalidation strategies

45m
1 problems
Topic Progress 0%

When Cache Clears

Automatic Cache Clearing

Action Cache Types Cleared
Module install/upgrade config, layout, compiled_config
Config change config
Product save catalog_product_*, fpc
Category save catalog_category_*, fpc
CMS page save cms_page, fpc
Static file deploy All
setup:di:compile compiled_config, di

Manual Cache Clearing

# Clear specific type
php bin/magento cache:clean config

# Clear multiple types
php bin/magento cache:clean config layout

# Flush all cache
php bin/magento cache:flush

Cache Clearing Events

// When cache is cleared
$this->eventManager->dispatch('clean_cache_after');

// When cache is invalidated (tag-based)
$this->eventManager->dispatch('invalidate_cache', [
    'tags' => $tags
]);

Tag-Based Invalidation

How Tag Invalidation Works

1. Cache entry saved with tags ['product_123', 'products']
2. Product 123 updated
3. Invalidate tag 'product_123'
4. All entries with that tag are cleared
5. Other entries with 'products' tag remain

Implementation

// Save with tags
$cache->save($data, $key, ['product_123', 'products'], 3600);

// Invalidate by specific tag
$cache->clean('tags', ['product_123']);

// Invalidate by multiple tags
$cache->clean('tags', ['product_123', 'product_456']);

Tag Invalidation Flow

// Product save triggers invalidation
public function afterSave()
{
    parent::afterSave();
    $this->cache->clean('tags', [
        'catalog_product_' . $this->getId(),
        'product_list'
    ]);
}

Tag Hierarchy

// Specific tag
catalog_product_123       // Product 123 only

// General tag
catalog_products          // All products

// Page tag
page_product_123          // Product 123 page

Invalidation Scope

// Fine-grained (precise)
$cache->clean('tags', ['catalog_product_123']);

// Coarse-grained (broad)
$cache->clean('tags', ['catalog_products']);

// Hybrid (both)
$cache->clean('tags', ['catalog_product_123', 'catalog_products']);

Cache Stampede Prevention

What is Cache Stampede?

When a cache key expires and many requests try to regenerate the same cached data simultaneously.

Cache expires -> 100 concurrent requests -> All try to regenerate
-> Database overload -> Slow response times

Prevention Strategies

1. Lock File Pattern

public function getData(string $key): string
{
    $lockFile = BP . '/var/cache/lock_' . md5($key);
    
    if (file_exists($lockFile)) {
        // Wait for lock release
        while (file_exists($lockFile)) {
            usleep(10000); // 10ms
        }
        return $this->cache->load($key);
    }
    
    // Acquire lock
    file_put_contents($lockFile, 'locked');
    
    try {
        $data = $this->generateData();
        $this->cache->save($data, $key);
        return $data;
    } finally {
        unlink($lockFile);
    }
}

2. Early Expiration

// Expire cache before actual expiry
$ttl = 3600;
$earlyExpiration = $ttl * 0.9; // 90% of TTL

$cache->save($data, $key, $tags, $earlyExpiration);

3. Redis Locking

$lockKey = 'cache_lock_' . $key;
$acquired = $redis->set($lockKey, '1', ['NX', 'EX' => 5]);

if (!$acquired) {
    // Another process is regenerating
    return $cache->load($key);
}

try {
    $data = $this->regenerate();
    $cache->save($data, $key);
} finally {
    $redis->del($lockKey);
}

Stampede Monitoring

// Log regeneration attempts
if (!$this->cache->load($key)) {
    $this->logger->warning('Cache miss for: ' . $key);
}

Invalidation Strategies

Strategy 1: Immediate Invalidation

// Invalidate immediately on data change
public function afterSave()
{
    $this->cache->clean('tags', ['product_' . $this->getId()]);
}

Pros: Immediate consistency
Cons: May over-invalidate

Strategy 2: Deferred Invalidation

// Queue invalidation for batch processing
$this->publisher->publish('cache.invalidate', [
    'tags' => ['product_' . $this->getId()]
]);

Pros: Batch efficiency
Cons: Temporary inconsistency

Strategy 3: TTL-Based

// Let cache expire naturally
$cache->save($data, $key, [], 3600);
// No explicit invalidation needed

Pros: Simple
Cons: Delayed updates

Strategy 4: Event-Based

// Invalidate on specific events
$this->eventManager->dispatch('cache_invalidate', [
    'tags' => $tags,
    'type' => 'product_save'
]);

Decision Matrix

Scenario Strategy
Product catalog Tag-based immediate
User sessions TTL-based
Configuration Immediate
Search index Deferred
Static content TTL-based

Practice Problems

0 / 1 solved
Cache Stampede Fix

A popular product page causes cache stampede when cache expires. Implement stampede prevention.

Quiz

1. What is cache stampede?

Question 1 options

2. How does tag-based invalidation work?

Question 2 options

3. What is early expiration?

Question 3 options

4. When should you use immediate vs deferred invalidation?

Question 4 options

Flashcards

Question

What is cache stampede?

Answer

Multiple concurrent requests regenerating the same expired cache entry simultaneously

Question

How does tag-based invalidation work?

Answer

Clears all cache entries that have the specified tag

Question

What is early expiration?

Answer

Proactively regenerating cache before TTL expires to prevent stampede

Question

What causes config cache to clear?

Answer

Module install/upgrade, config changes, setup:di:compile

Question

How to prevent cache stampede?

Answer

Use Redis locking, early expiration, or lock file patterns

Revision Notes

Key Takeaways

  • 1. Cache invalidates automatically on data changes, config changes, and module operations
  • 2. Tag-based invalidation clears specific cache entries by tag label
  • 3. Cache stampede occurs when concurrent requests regenerate same cache entry
  • 4. Prevention: Redis locking, early expiration, lock files
  • 5. Choose invalidation strategy based on consistency vs performance needs
  • 6. Monitor cache misses and regeneration attempts for stampede detection

Interview Tips

  • Explain when and why cache invalidates in Magento
  • Describe tag-based invalidation with examples
  • Discuss cache stampede prevention strategies
  • Know the difference between immediate and deferred invalidation

Cheat Sheet

Cache Invalidation Cheat Sheet

Auto-clear triggers:

  • Module install/upgrade
  • Config changes
  • Product/category save
  • setup:di:compile

Tag invalidation:
$cache->clean('tags', ['tag_name'])

Stampede prevention:

  1. Redis lock: SET NX EX
  2. Lock file pattern
  3. Early expiration (90% TTL)

Strategies:

  • Immediate: precise, over-invalidation
  • Deferred: batch efficient, temporary inconsistency
  • TTL: simple, delayed updates
  • Event: flexible, decoupled