Interview frequency: …
Short answer
Cache::remember checks for the key and returns it if found; otherwise, it runs a Closure and stores the result for the specified duration. Atomic Locks ensure only one request performs an expensive operation at a time.
Explanation
Cache::remember is the most common way to store slow query results. However, when a popular key expires on a site receiving thousands of visits, hundreds of requests may simultaneously recalculate the same result and query the database (a Cache Stampede). Cache::lock()->get() ensures that only one request updates the cache while the others wait for the ready result.
Code example
$users = Cache::remember('users.active', now()->addHours(1), function () {
return User::where('active', true)->get();
});Common mistakes
- Storing large Eloquent model objects with unloaded relationships in the cache, causing Serialization errors.
Follow-up questions
- What is Probabilistic Early Expiration, and how does it prevent a cache stampede?
- What are the main production performance commands (route:cache, view:cache, config:cache)?