N+1 Query Pattern That Collapsed Under Load

An ORM-generated N+1 query pattern that ran fine in staging (10 records) caused 8,400 database queries per user request in production.

Overview

An orders endpoint that looked fine on average fired 1,681 SQL queries for a single power user, and three such requests at once drained the connection pool for everyone.

What happened

The endpoint listed orders with their products and customers. With lazy loading on by default, every association access became its own SELECT. Lazy loading means the ORM fetches a related row only at the moment the code touches it, so a loop over a list quietly becomes a loop of queries.

Here is one request from a power user, step by step.

  • The orders endpoint asks the ORM for the user's orders.
  • The ORM runs 1 SELECT for the orders and gets 840 rows back.
  • For each of the 840 orders, the ORM runs one SELECT for the product.
  • For each of the same 840 orders, it runs one more SELECT for the customer.

That is 1 + 840 + 840 = 1,681 queries for one request. This shape, one query for the list plus N more for its items, is what gives the N+1 problem its name.

Key concepts

  • N+1 query problem
  • Eager loading
  • Query batching
  • Percentile latency monitoring

Interview questions

  • How do you detect and fix N+1 query problems in an ORM-based application?

Sign up free to read the full topic

More War Stories topics

Start free on Cariara · Coding problems · System design studio