Laravel interview question · Most asked
How do you use caching in Laravel effectively, including atomic locks?
Summary
Cache::remember($key, $ttl, fn () => ...) implements cache-aside; choose Redis or Memcached in production; invalidate on writes; and use Cache::lock() atomic locks to protect critical sections or prevent cache stampedes.
Longer Answer
- Always set a TTL, and invalidate (
Cache::forget) when the underlying data changes. - Version keys (
products:v2:{$id}) to invalidate groups cheaply. Cache tags (Redis, Memcached) group keys but are not supported by every store. Cache::flexible($key, [$fresh, $stale], fn ...)(Laravel 11+) serves stale data while revalidating in the background, which avoids stampedes on hot keys.Cache::lock('report:'.$id, 60)gives a distributed mutex:get()returns immediately,block(5)waits. Release it infinally, or use the closure form.- The
databaseandfiledrivers do not scale across many servers; thearraydriver is per-request.
Do not cache Eloquent models with relationships blindly: serialised objects can be large and become stale or incompatible after a deploy. Cache plain arrays or IDs.
Code Example
$stats = Cache::flexible('dashboard:stats', [60, 300], fn () => Stats::compute());
Cache::lock('invoice:'.$invoice->id, 30)->block(5, function () use ($invoice) {
$invoice->finalize();
});
Key Points
rememberwith a TTL; invalidate on write.- Atomic locks for critical sections.
flexible(stale-while-revalidate) against stampedes.- Cache arrays, not heavy models.
Deep dive: Database Caching at Scale
More most-asked Laravel questions
- How do you validate requests in Laravel? Why use Form Requests?
- Gates or policies: how does authorization work in Laravel?
- What is mass assignment, and how do $fillable and $guarded protect against it?
- How do database transactions work in Laravel, and what pitfalls should you know?
- Which Artisan commands would you run when deploying Laravel to production, and why?
- What is the service container, and how does dependency injection work in Laravel?
- What is the N+1 query problem in Eloquent and how do you prevent it?
- How do queues work in Laravel?