Skip to content
All posts

· 4 min read · Muhammad Shah

Cutting query times by up to 40%: composite indexes and N+1 fixes in Laravel

At Kazmi Global Systems I led a database performance overhaul for Forte Commercial Cleaning's invoicing system. Restructuring schemas, adding composite indexes and eliminating N+1 queries cut average query time by up to 40% under peak load. These are the steps I'd repeat on any Laravel app.

1. Find the N+1 queries first

An N+1 happens when you load a list, then run one extra query per row to fetch a relation. It looks fine with ten rows and falls over with ten thousand. Turn on query logging or a debug toolbar and look for the same query repeated with different IDs.

// N+1: one query for invoices, then one per invoice for its client
$invoices = Invoice::latest()->get();

// Fixed: two queries in total
$invoices = Invoice::with('client')->latest()->get();

Laravel can also stop you from shipping new ones: Model::preventLazyLoading() throws in development whenever a relation is lazy-loaded.

2. Index for the queries you actually run

Single-column indexes rarely match real filters. If a screen filters by company and status and sorts by date, a composite index in that order lets the database answer it from the index alone.

Schema::table('invoices', function (Blueprint $table) {
    $table->index(['company_id', 'status', 'issued_at']);
});

Check with EXPLAIN before and after. If the plan still shows a full table scan, the column order doesn't match the query.

3. Load less

  • Select only the columns a screen needs.
  • Paginate or chunk large lists instead of loading everything.
  • Use withCount or aggregate queries instead of counting loaded collections.
  • Cache expensive, rarely-changing results in Redis.

4. Measure under realistic load

Slow queries often only appear with production-sized data. Test against a copy with realistic volumes and track the slowest endpoints before and after each change, so you know which fix earned the improvement.