Every ORM ships with the same seductive default: load a list of rows, and load each row’s relationships the moment you touch them. It feels clean, the tests pass, and the demo screen renders in 40 milliseconds. Then the table grows to a hundred thousand rows, someone opens the list page in production, and the database starts handling thousands of queries for what should have been two. This is the N+1 query problem, and it is probably the most common database performance defect in application code that uses an ORM.
The frustrating part is that N+1 is almost invisible at the code level. The loop looks innocent. The queries are individually fast. Nothing throws an exception. The damage only shows up as aggregate load: connection pools saturating, CPU on the database climbing, p99 latency drifting upward a little more every week. In this post we’ll dissect exactly how N+1 happens, how to catch it before production does, and the three fixes that cover nearly every case — with working Go examples.
The Anatomy of N+1
The pattern is always the same: one query to fetch N parent rows, then one additional query executed per parent row to fetch something the code needs from a related table. Here is the canonical offender in Go, using GORM:
type Order struct {
ID int64
CustomerID int64
Total int64
Customer Customer // lazy: populated only when accessed
}
func RecentOrdersWithNames(db *gorm.DB) ([]OrderSummary, error) {
var orders []Order
if err := db.Limit(50).Find(&orders).Error; err != nil {
return nil, err
}
summaries := make([]OrderSummary, 0, len(orders))
for _, o := range orders {
var c Customer
if err := db.First(&c, o.CustomerID).Error; err != nil { // one query per order
return nil, err
}
summaries = append(summaries, OrderSummary{
OrderID: o.ID,
Total: o.Total,
CustomerName: c.Name,
})
}
return summaries, nil
}
That inner loop executes 50 extra queries. Combined with the initial fetch, the request issues 51 round trips. With lazy loading — where the ORM fetches the relation on first field access — the loop can hide even better, because the query fires inside an accessor rather than next to an explicit First() call. The page still works. It just quietly burns 50× the database work it needs.
The cost isn’t really the 50 queries themselves. It’s what each one costs: a full network round trip, connection checkout and check-in, query parse and plan, and one index seek. At 50 rows you pay it 50 times per request; at 50 concurrent users you’re issuing 2,500 extra queries per second for data that fits in two queries. This is why N+1 problems tend to appear in the load graphs weeks before anyone opens the offending page deliberately.
The Fixes, In Order of Preference
1. Eager loading
Every mature ORM has a mechanism for loading relationships up front. In GORM it’s Preload, which issues one additional query using an IN clause rather than joining:
var orders []Order
err := db.
Preload("Customer").
Limit(50).
Find(&orders).Error
// SELECT * FROM orders LIMIT 50;
// SELECT * FROM customers WHERE id IN (…, …, …); -- one query, all customers
Fifty-one queries become two, with no change to the shape of your code downstream. This is the fix you should reach for first, because it preserves lazy ergonomics while making the query count explicit and predictable.
2. A single join when the data is one-to-one
For one-to-one relationships that you always need, a join collapses everything into one query and lets the database do the work it’s built for:
type OrderRow struct {
OrderID int64
Total int64
CustomerName string
}
var rows []OrderRow
err := db.
Table("orders o").
Select("o.id AS order_id, o.total, c.name AS customer_name").
Joins("JOIN customers c ON c.id = o.customer_id").
Limit(50).
Scan(&rows).Error
One round trip, one plan, and the planner can use the index on customers.id directly. The trade-off is that you give up struct-mapped ORM entities for this read path — which is usually the right call anyway, because the joined projection is exactly what the view needs and nothing more.
3. Batch fetching with IN
Sometimes you can’t use the ORM’s preloader — the fetch happens in two different layers, or the IDs come from an external source. The manual fix is a batched IN query plus a map:
ids := make([]int64, 0, len(orders))
for _, o := range orders {
ids = append(ids, o.CustomerID)
}
var customers []Customer
if err := db.Where("id IN ?", ids).Find(&customers).Error; err != nil {
return nil, err
}
byID := make(map[int64]Customer, len(customers))
for _, c := range customers {
byID[c.ID] = c
}
for i := range orders {
summaries = append(summaries, OrderSummary{
OrderID: orders[i].ID,
Total: orders[i].Total,
CustomerName: byID[orders[i].CustomerID].Name,
})
}
Two caveats worth knowing. If the ID list can be huge — thousands of values — chunk it into batches of a few hundred so the statement stays small and the planner keeps using the index. And if the list can be empty, skip the query entirely; WHERE id IN () is either a syntax error or a full-table scan depending on the driver.
Catching N+1 Before Production Does
N+1 survives code review because reviewers read the loop, not the query log. You need instrumentation that makes query counts as visible as test failures.
The cheapest detection is a query counter in development. Wrap the driver or add ORM hooks that increment a counter and log a warning when a single request exceeds a threshold:
// GORM callback: count queries per request and flag runaway loops
var queryCount atomic.Int64
db.Callback().Query().Before("gorm:query").
Register("count_queries", func(tx *gorm.DB) {
n := queryCount.Add(1)
if n == 30 {
tx.Logger.Warn(nil, "query count exceeded 30 in one operation — likely N+1")
}
})
In production, two signals catch it reliably. Distributed tracing with a span per database call makes N+1 jump out visually: one request span with 50 identical child spans at 1–3 ms each is the fingerprint. And pg_stat_statements aggregates it server-side — a query shape executed tens of thousands of times per hour with a mean under 2 ms, differing only by literal parameter, is almost always a lazy-loading loop on the application side. When you see thousands of SELECT * FROM customers WHERE id = $1 executions, the fix is usually one Preload call away.
Pitfalls When Fixing
Fixing N+1 naively can create a worse problem: the join explosion. If you eagerly load two independent has-many collections through a single SQL join — orders × items × tags — you get a cartesian row count, 50 orders with 20 items and 10 tags each produce 10,000 rows that the ORM then deduplicates in memory. The dedicated batched-query approach most ORMs use for preloading avoids this precisely because each relationship is fetched in its own query. When you need two nested collections, prefer two preload queries over one giant join, and load the deepest collection only if the view actually renders it.
The second pitfall is overcorrection: sprinkling eager loads on every query “just in case.” Each preload is a real query that runs whether or not the data is touched, and preloading collections you never read converts an N+1 into a different form of waste. Eager-load what the request path uses; leave the rest lazy.
Finally, remember that N+1 is a request-shape problem, not a schema problem. Adding an index helps each individual lookup, and caching the related table helps the hottest ones, but neither changes the fact that you’re paying 50 round trips for a job that needs two. Fix the shape first; optimize the remaining queries after.
Wrapping Up
The N+1 pattern is the default failure mode of every ORM, because lazy loading optimizes for code ergonomics and lets query count scale with row count. The fixes are mechanical — preload, join, or batch-fetch with IN — and the detection is a solved problem once you treat queries-per-request as a first-class metric alongside latency. If you do only one thing after reading this, make it the dev-mode query counter: it turns the invisible into an assertion that fails while the fix is still a one-line change.