performance
Junior
Explain caching strategies
Short Answer
Caching stores computed results to avoid repeated expensive operations. Strategies include read-through, write-through, cache-aside, and write-behind.
Detailed Answer
Caching strategies:
1. Cache-Aside (Lazy Loading):
- Check cache first, if miss, query DB, store in cache
- Most common in Laravel (Cache::remember)
2. Write-Through:
- Write to cache and DB simultaneously
- Ensures consistency but slower writes
3. Read-Through:
- Cache automatically loads data on miss
- Similar to cache-aside but handled by the cache layer
4. Write-Behind (Write-Back):
- Write to cache immediately, DB asynchronously
- Fast writes but risk of data loss
Laravel Cache facade implements cache-aside:
- Cache::get / Cache::put / Cache::remember
- Tags for grouping related cache entries
- Multiple drivers: file, Redis, Memcached, database
Code Example
Example
<?php
// Cache-Aside (most common)
$posts = Cache::remember('posts:published', 3600, function () {
return Post::published()->with('user')->get();
});
// Tag-based caching (Redis/Memcached)
Cache::tags(['posts', 'home-page'])->put('featured', $posts, 3600);
Cache::tags(['posts'])->flush(); // Clear all post caches
// Cache invalidation patterns
// 1. Time-based: TTL expires automatically
Cache::put('key', $value, now()->addHour());
// 2. Event-based: Clear on data change
Post::created(fn () => Cache::forget('posts:all'));
// 3. Manual: Clear specific cache
Cache::forget('posts:all');
// Multi-level caching
function getDashboardData()
{
return Cache::remember('dashboard', 3600, function () {
// Expensive computation here
return $this->computeDashboard();
});
}
Interview Tip
Discuss cache invalidation: "There are two hard things in computer science: cache invalidation and naming things." Explain when each strategy is appropriate.