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
- Cache Stampede on a Flash-Sale Product Page
- Connection Pool Exhaustion That Brought Down 12 Microservices
- DynamoDB Hot Partition That Throttled a Flash Sale
- Failover to a Lagging Replica Lost 4 Minutes of Orders
- Internal DNS Cache Poisoning That Redirected API Traffic
- Malicious npm Package Exfiltrated Environment Variables at Build Time
- NAT Gateway Port Exhaustion Under Bursty Lambda Traffic
- Node.js Memory Leak That Required Daily Restarts
- Public S3 Bucket Exposed Customer PII for 8 Months
- Silent Data Corruption from an Off-By-One Migration
- Single-Region Dependency That Caused a Global Outage
- The Cascade That Took Down Three Services
Start free on Cariara · Coding problems · System design studio