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 in finally, or use the closure form.
  • The database and file drivers do not scale across many servers; the array driver 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

  • remember with 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

← All Laravel questions