N+1 Queries in Eloquent and Doctrine: One Dashboard Case

How lazy loading in Laravel and Symfony turned one dashboard request into 342 SQL queries on one project, and what helped: eager loading and a single JOIN.

· 3 min read · Erik Kubica

How Object Graphs Hide Queries

I like PHP, and I think Laravel and Symfony have some of the nicest developer ergonomics around.

One side effect of ORMs like Eloquent and Doctrine is that they make database access look like plain property access on in-memory objects.

In your template or controller, you write:

// Looks like simple PHP object traversal
foreach ($invoices as $invoice) {
    echo $invoice->customer->name;
    echo $invoice->customer->address->city;
}

It looks harmless, like reading from an array of PHP objects. In reality, each of those arrows can trigger a query.

A 342-Query Dashboard

I was once asked to look at a B2B SaaS platform hosted on a 4-core production server (4 vCPU, 8 GB RAM). The customer dashboard took 1.4 seconds to load for a single user with 50 invoices. When 20 users logged in at the same time, the PHP-FPM worker pool pinned the CPU and PostgreSQL started queueing transactions.

I opened Laravel Debugbar and checked pg_stat_statements:

Database Queries Executed: 342
Total Database Time: 890 ms
PHP Processing Time: 510 ms

That was 342 SQL queries for a single page render:

  1. Query 1: SELECT * FROM invoices WHERE tenant_id = 42 LIMIT 50;
  2. Queries 2–51: SELECT * FROM customers WHERE id = ?; (fired 50 times in a loop)
  3. Queries 52–101: SELECT * FROM addresses WHERE customer_id = ?; (fired 50 times)
  4. Queries 102–342: SELECT * FROM tax_rates WHERE country_code = ?;

Every query is a roundtrip between the PHP-FPM process and PostgreSQL. Even with low local network latency, hundreds of sequential roundtrips added up to roughly 350 to 500 ms of waiting on that setup.

Lazy loading is convenient, but it's easy to lose track of how many queries a page really runs.

From 342 Queries to One

The first fix in Eloquent is explicit eager loading:

// Eager load relationships upfront
$invoices = Invoice::with(['customer.address.taxRate'])
    ->where('tenant_id', 42)
    ->limit(50)
    ->get();

That dropped the query count from 342 to four, which on its own is often enough.

On this dashboard I went one step further and wrote the SQL by hand with a JOIN and PostgreSQL json_build_object:

SELECT 
    i.id,
    i.amount_cents,
    i.created_at,
    json_build_object(
        'name', c.name,
        'email', c.email,
        'city', a.city,
        'tax_rate', t.percentage
    ) AS customer_data
FROM invoices i
INNER JOIN customers c ON c.id = i.customer_id
INNER JOIN addresses a ON a.id = c.address_id
LEFT JOIN tax_rates t ON t.country_code = a.country_code
WHERE i.tenant_id = 42
ORDER BY i.created_at DESC
LIMIT 50;

I replaced the Eloquent loop with this single raw query. On that dashboard the numbers changed roughly like this:

  • Total database queries: from 342 to 1.
  • Query execution time: from about 890 ms to about 4.2 ms.
  • Total page response time: from about 1.4 seconds to about 38 ms.
  • Database CPU usage: from about 85% to about 4%.

The raw query is less flexible than the ORM version, so it isn't always the right call. If the page is not under load, eager loading is usually simpler to maintain.

Disabling Lazy Loading Outside Production

If you use Laravel, one cheap safeguard is this in your AppServiceProvider:

// Surface N+1 queries before they hit production
Model::preventLazyLoading(! app()->isProduction());

This throws an exception whenever someone lazy-loads a relationship in development, so you notice the problem early and either declare an eager load or write a proper JOIN.

It's a reasonable habit to keep in mind that every arrow operator on a lazy relationship can be a network roundtrip.

Tell me what you need built

Usually a reply within a day, by email or WhatsApp.