The N+1 Problem and ORM Pitfalls in SQL: The Silent Performance Killer

Let me start with a phone call from my fleet software years, from a vehicle tracking client: "The panel kind of won't open, but we haven't touched the server, and the code hasn't changed either." The classic line. The vehicle list page used to open in half a second; now it was taking up to six seconds. We connected, opened the query log, and the counter stopped at 1,601 — a single page load was sending one thousand six hundred and one separate queries to the database. The client was right, the code really hadn't changed; what had changed was the fleet. They had started with 40 vehicles and grown to 800. And an N+1 problem had been sleeping in the code since day one.

I picked this story on purpose, because it shows N+1's sneakiest trait: it never shows up in the development environment. On your local machine with 20 records everything is lightning fast, the tests are green, the demo gets applause. The problem works like a debt collected with interest as the data grows — and collection day is never a convenient day.

One query is fine, a thousand queries is a disaster

The mechanism is actually very simple. You fetch the list with a single query — that's the "1" in the formula. Then, inside a loop, you touch one relationship on each row: the order's customer, the vehicle's last location, the post's comment count. With every touch, the ORM fires off a new query behind your back — that's the "N." If you're showing the customer name and delivery address on a page of 100 orders, the math goes like this: 1 list query + 100 customer queries + 100 address queries. You're making 201 round trips to the database, and every round trip has its own network cost and its own connection occupancy. Each query on its own may be fast; what kills you is the total and the number of round trips.

How N+1 happens: the list is fetched with one query, each relationship is touched in the loop, the ORM fires a query every time and the total climbs to 201 queries.
Each query may be fast; what kills you is the total and the number of round trips.

The odd part is how innocent the code looks. Writing siparis.musteri.ad (order.customer.name) is perfectly natural; that naturalness is the whole promise of ORMs anyway. The mechanism called lazy loading quietly fires the query the moment you touch the relationship and makes you feel nothing. The comfort is real — and so is the bill. An inexperienced eye seeing this line in code review senses no danger at all; an eye looking at the SQL log sees the disaster in three seconds. The difference is where you look.

That was exactly the situation in our 1,601-query case: the vehicle list was fetched, then the last location record and driver information were queried one by one for each vehicle. At 40 vehicles, 81 queries hadn't caught anyone's attention — the page still opened in a quarter of a second, after all; at 800 vehicles, the same code started pounding the database. What's more, the slowness didn't stay confined to that page — the flood of queries occupying the connection pool was dragging down the rest of the system too. That's N+1's second sneaky face: sometimes other pages pay the bill.

The diagnosis comes from counting, not guessing

When we hear "the page is slow, the server must be underpowered, let's scale it up," the first thing we do isn't look at the server; it's count queries. Debugbar in Laravel projects, the debug toolbar in Django, or failing that, the database's own query log — the tool doesn't matter, the question is always the same: how many queries does this single page produce? Scaling up the server doesn't fix N+1, by the way; it just makes the bill bigger and postpones collection day.

A healthy list page sends a single-digit number of queries. Ten-something queries means "worth a look"; if you see a three-digit number, the diagnosis is made and the debate is over. This count is so cheap and so instructive that we start here with every service that comes to us with a performance complaint. Most of the time the culprit is found in five minutes; the team is surprised: "was it really that simple?" (It was. But it was invisible to anyone who wasn't looking.)

One step further is making the diagnosis permanent: we add a test to the CI pipeline along the lines of "this endpoint may send at most X queries." That way, when a new team member six months later innocently adds a field to the list and N+1 leaks back in, it's caught at the pull request stage, not in production. A team that doesn't test for performance regressions treats the same disease twice — the second time usually with a more crowded meeting.

Diagnosis by query count: single digits is healthy, ten-something needs a check, three digits is N+1; a CI test makes it permanent.
Scaling up the server doesn't fix N+1; count the queries first.

The treatment: get the query out of the loop

The essence of the fix fits in one sentence: go to the database before the loop, not inside it. In practice, this is called eager loading. The moment you write Siparis::with(['musteri','adres']) in Laravel, the ORM reduces the 201-query scenario to 3 queries: the orders, all the related customers, all the related addresses. That was the treatment in our vehicle tracking case too — 1,601 queries dropped to 4, and the page went from 6 seconds to under 400 milliseconds. Number of lines changed in the code: two. The client's week that began with "should we scale up the server?" ended with a two-line pull request.

Lazy loading versus eager loading: the query count dropped from 1,601 to 4 and page time from 6 seconds to under 400 milliseconds.
Two lines changed in the code; go to the database before the loop, not inside it.

One level up from eager loading is fetching only the columns you need from the relationship. The habit of "bring me everything about the customer" wastes memory and network bandwidth when the list only shows the first and last name. The same principle applies to aggregation: instead of summing counters in a loop, let the database do the COUNT and SUM. Database engines have been optimized for exactly this for decades; there's no contest between them and your loop in the application layer.

And one rule that has nearly the force of law on our team: lazy loading is banned on list screens. Lazy loading is for single-record screens — if a detail page needs a relationship, it gets loaded at that moment, and that's perfectly fine. But the list + lazy combination is N+1 by definition; there are no exceptions. In most modern ORMs you can switch lazy loading off entirely and turn violations into exceptions — in Laravel, Model::preventLazyLoading() does exactly that. We turn it on from day one in our new services: the moment a developer writes an N+1, the application blows up in their face and the bug never reaches production. A bit ruthless, extremely effective.

The ORM isn't the culprit; unread SQL is

Don't take away from this post that "ORMs are bad, go back to raw SQL"; that's not what we think. ORMs make a real contribution to development speed, code readability and security (hello, SQL injection); in the overwhelming majority of the hundreds of projects I've touched over the years, I used an ORM too, and as a team we keep using them today. Our objection is to unconscious use: an ORM whose generated SQL you never read is a proxy signing technical-debt promissory notes in your name. Glancing at the query log now and then is the cheapest way to see those notes before they come due. Here's the sentence we tell every new developer on the team: the ORM isn't code you wrote, it's code written on your behalf — and occasionally reading the code someone else wrote on your behalf is the most basic professional precaution.

If you also have a panel where "nothing changed, but it got slow," chances are some N somewhere has grown. A query count usually doesn't take longer than a coffee break, and the treatment is often two lines. I enjoy talking about diagnosis stories like these; the contact page is open.