Measuring Cache Hit Ratio
Redis Cache Stats
# Get Redis stats
redis-cli INFO stats
# Key metrics:
# keyspace_hits: number of successful lookups
# keyspace_misses: number of failed lookups
# hit_ratio = hits / (hits + misses)
Magento Cache Metrics
use Magento\Framework\Cache\FrontendInterface;
class CacheMetrics
{
private $cache;
private $hits = 0;
private $misses = 0;
public function getHitRatio(): float
{
$total = $this->hits + $this->misses;
if ($total === 0) return 0;
return $this->hits / $total;
}
public function load($key)
{
$result = $this->cache->load($key);
if ($result) {
$this->hits++;
} else {
$this->misses++;
}
return $result;
}
}
Monitor Cache Performance
# Redis monitoring
redis-cli MONITOR
# Check specific cache type
redis-cli GET "full_page_cache_*"
# Count cached items
redis-cli DBSIZE
Key Points
- Aim for 80%+ cache hit ratio
- Monitor hits and misses separately
- Track cache performance over time
- Identify cache-ineffective patterns
Improving Cache Hit Rates
Increase Cache Lifetime
// Cache configuration
$cacheConfig = [
'full_page_cache' => [
'lifetime' => 86400, // 24 hours
],
'block_html' => [
'lifetime' => 3600, // 1 hour
],
'config' => [
'lifetime' => 86400, // 24 hours
],
];
Reduce Cache Invalidation
// Avoid invalidating entire cache
// BAD: Cache::clean()
$this->cache->clean();
// GOOD: Invalidate specific tags
$this->cache->clean(
'tags' => ['catalog_product_' . $productId]
);
Use Appropriate Cache Types
// Different cache for different data
$fullPageCache = $this->cacheManager->getCache('full_page');
$configCache = $this->cacheManager->getCache('config');
$blockCache = $this->cacheManager->getCache('block_html');
Key Points
- Longer lifetimes for stable data
- Tag-based invalidation for precision
- Separate caches by data type
- Avoid full cache clears
Cache Warming
Pre-warm Cache
use Magento\Framework\App\Cache\TypeListInterface;
class CacheWarmer
{
private $cacheTypeList;
private $urlInterface;
public function warmCache()
{
// Warm full page cache
$urls = $this->getImportantUrls();
foreach ($urls as $url) {
$this->makeRequest($url);
}
}
private function getImportantUrls(): array
{
return [
$this->urlInterface->getBaseUrl(),
'/catalogsearch/result/?q=test',
'/customer/account/login',
];
}
}
Cron-based Warming
<!-- cron.xml -->
<group id="default">
<job name="cache_warmer" instance="Vendor\Module\Cron\CacheWarmer" method="execute">
<schedule>*/5 * * * *</schedule>
</job>
</group>
External Cache Warming
# Use wget/curl to warm cache
#!/bin/bash
URLS=(
"https://magento.example.com/"
"https://magento.example.com/category.html"
"https://magento.example.com/product.html"
)
for url in "${URLS[@]}"; do
curl -s -o /dev/null "$url"
done
Key Points
- Warm cache during low traffic
- Prioritize important pages
- Use cron for scheduled warming
- Monitor warming effectiveness
Cache Strategy
Cache Strategy Types
// 1. Cache-Aside (Lazy Loading)
$data = $cache->load($key);
if (!$data) {
$data = $database->load($key);
$cache->save(serialize($data), $key);
}
// 2. Write-Through
function save($key, $data) {
$database->save($data);
$cache->save(serialize($data), $key);
}
// 3. Write-Behind (Async)
function save($data) {
$database->save($data);
$queue->push($data); // Async cache update
}
Magento Cache Layers
// Layer 1: Full Page Cache (Varnish/Redis)
// Layer 2: Block HTML Cache
// Layer 3: Config Cache
// Layer 4: Database Query Cache
// Layer 5: Object Cache
Key Points
- Use cache-aside for most scenarios
- Write-through for data consistency
- Multiple cache layers for performance
- Monitor each cache layer separately
Practice Problems
0 / 1 solved
Improve Cache Hit Ratio
Analyze and improve a store with low cache hit ratio.
Solution
// 1. Identify issues:
// - Too many cache invalidations
// - Short cache lifetimes
// - No cache warming
// 2. Solutions:
// a) Increase cache lifetime
$cacheConfig['full_page']['lifetime'] = 86400;
// b) Use tag-based invalidation
$this->cache->clean(['tags' => ['product_' . $id]]);
// c) Implement cache warming
$cron->schedule('cache_warmer', '*/5 * * * *');
// d) Avoid full cache clears
// Instead of: $this->cache->clean();
// Use: $this->cache->clean(['tags' => [...]]) Quiz
1. What is a good cache hit ratio?
2. Why use tag-based invalidation?
3. What is cache warming?
4. What is cache-aside pattern?
Flashcards
Question
Good cache hit ratio?
Click to reveal answer
Answer
80% or higher
Question
Tag-based invalidation?
Click to reveal answer
Answer
Clears only related cache entries
Question
Cache warming?
Click to reveal answer
Answer
Pre-loading cache with frequently accessed data
Question
Cache-aside pattern?
Click to reveal answer
Answer
Check cache first, load from DB on miss
Revision Notes
Key Takeaways
- 1. Target 80%+ cache hit ratio
- 2. Use tag-based invalidation for precision
- 3. Warm cache during low traffic periods
- 4. Multiple cache layers for different data types
Interview Tips
- • Explain cache hit ratio and how to measure it
- • Discuss cache warming strategies
- • Know different cache patterns
Cheat Sheet
Cache Hit Ratio
- Target: 80%+
- Measure: Redis INFO stats
- Improve: longer TTL, tag invalidation
- Warm: pre-load important pages