Solution and explanation
- A very common 5-year scenario.
- Don't immediately say "use Redis"; first identify the bottleneck.
- Step 1, database: check slow queries, missing indexes, N+1 queries, large SELECT *, unnecessary joins and poor pagination.
// Only one row is needed:
User::where('email', $email)->first();
// Add an index:
$table->index('email');
- Step 2, Eloquent: eager load and select only required columns.
Order::with(['user', 'items.product'])->get();
User::select(['id', 'name', 'email'])->get();
- Step 3, cache frequently requested data (Redis in distributed, high-traffic setups).
$products = Cache::remember('products', 3600, fn () => Product::latest()->get());
- Step 4, queues: don't do slow work during the HTTP request.
User places order → save order → return response
↓ queue: email, invoice, SMS, notifications
SendOrderConfirmation::dispatch($order);
- Step 5, pagination and chunking instead of Product::all() on millions of rows.
Product::paginate(50);
Product::chunkById(1000, function ($products) {
//
});
- Step 6, HTTP and API: pagination, caching, compression, CDN, HTTP caching and lean JSON responses.
- Step 7, infrastructure for high traffic:
Load Balancer
↓
Laravel Server 1 / Server 2 / Server 3
↓
Redis
↓
Database (with read replicas where appropriate)
- Use PHP OPcache, Redis, queue workers under Supervisor or systemd, Horizon where applicable, database indexes, a CDN and horizontal scaling.
- Strong 5-year answer: "I don't optimize Laravel blindly.
- First I identify whether the bottleneck is CPU, database, memory, network or external services.
- For database issues I inspect slow queries, indexes and N+1 problems.
- For repeated reads I add caching, usually Redis in a distributed environment.
- For expensive work I use queues.
- I also optimize pagination, eager loading, selected columns and API payloads, and at infrastructure level I use OPcache, multiple application instances behind a load balancer and appropriate database scaling."