Node.js Production Failure Lab · part 6
Every Query 0.04 ms, the Page Half a Second: the N+1 Query Pattern and the Cost of a Network Round Trip
The mobile app's new My Orders screen takes half a second; the database is relaxed, the API is idle and every query runs in under 0.1 ms. From the staircase-shaped trace in Jaeger we follow, step by step, the N+1 query pattern, why latency grows linearly with the number of queries, and how the fix brings it down to three fixed queries.
Node.js Production Failure Lab · Part 6 · Difficulty ★☆☆ · Reading ~20 min · Lab ~30–45 min
In 2019 on GitLab.com, Gitaly (the internal service that accesses Git repositories) latency rose, Sidekiq queues grew and web pages slowed down. According to GitLab’s root cause analysis, the degradation lasted about 9 hours 45 minutes. The cause wasn’t a crash or a slow server: some commits carried a large number of tags, and the jobs processing them made a separate Gitaly call for each tag. The analysis’s chain of “whys” ends on exactly that sentence: the jobs were processing a large number of tags, which led to “n+1 problems” for Gitaly (GitLab, RCA: Gitaly n+1 calls causing bad latency and sidekiq queues to grow). One of the permanent fixes was a new find_tag RPC that did the work instead of one lookup at a time.
Each call on its own was fast. What was expensive was the number of calls and the network trip each one paid for. In this part we’ll live through the same pattern where it shows up most often, in database queries: the mobile app’s new “My Orders” screen takes half a second, yet the database is relaxed, the API is idle and every query runs in under 0.1 ms inside PostgreSQL.
In Part 5 we followed an incident where a single query was expensive: because of a missing index, every call scanned 1.2 million rows. This time it’s the opposite: no query is expensive, and the indexes are in place. The problem is that one request sends dozens of cheap queries one after another.
What you’ll learn
- What the N+1 query pattern is and why it never shows up in development
- Latency = number of round trips × round-trip time: why time spent inside the database can be negligible
- Recognizing and counting the “staircase” of sequential
pg.queryspans in Jaeger - Finding where the time goes by comparing the query time the API sees with
pg_stat_statements’mean_exec_time - What it means when a query’s call count in
pg_stat_statementsis far larger than the request count - The fix: a batched query with
WHERE order_id = ANY($1::int[])and grouping in memory (Map.groupBy) - Why
Promise.allis “better, but not good”
Prerequisites
You can read this article without the lab. These help:
| Topic | Why | Source |
|---|---|---|
| The N+1 query problem | The subject of the article; a short, clear definition | Rails Guides, Active Record Query Interface: Eager Loading Associations (the examples are Ruby but the idea is language-agnostic) |
pg_stat_statements | Call count and mean time per query | PostgreSQL docs, pg_stat_statements |
| Reading traces and spans | To interpret the waterfall in Jaeger | Part 1, Steps 1 and 4 |
| Edge vs in-service latency, the pool panel | To read the dashboard | Part 5, Steps 1–2 |
1. Concept: cheap query, expensive trip
From the API’s point of view, a database query costs two things:
- Execution time inside the database: planning, reading from the index, preparing the rows. Microseconds for a query that reads a single row by primary key.
- The round trip (RTT): the query traveling over the network to the database, the answer coming back, plus the pool and driver work in between. ~0.1 ms on the same machine; a few milliseconds to a managed database in another availability zone.
For a single query the second one usually doesn’t matter. But if your code awaits each query inside a loop, the queries go in sequence: the next one doesn’t set off until the previous answer has arrived. Then the request’s duration is a simple product:
request time ≈ number of queries × round-trip timeN+1 is the pattern that grows the first factor of that product with the data: one query for a list (1), then one more query for every element of the list (N). This part’s code has one more level: 1 for the orders, the items of each order (N), and the product of each item (M). For a customer with 23 orders and 53 items, that’s 1 + 23 + 53 = 77 queries.
time ──────────────────────────────────────────────────────────────►
N+1: [orders][items #1][product][product][items #2][product] ... 77 round trips
batched: [orders][items + products of all orders] 2 round tripsSee it yourself: a 35-line experiment with a fake “remote database”
You don’t even need a real database. The script below sets up a small TCP server that answers every query instantly but delays the answer by RTT_MS. So the “query” runs in zero time and the entire cost is in the network:
// n1.mjs: measures N+1 queries vs a batched query against a fake "remote database"
import net from 'node:net';
import { once } from 'node:events';
const RTT = Number(process.env.RTT_MS ?? 6); // round-trip time (ms)
// "Database": runs the query instantly, but the answer spends RTT on the network
net.createServer((sock) => {
sock.setNoDelay(true);
sock.on('data', (buf) => (RTT ? setTimeout(() => sock.write(buf), RTT) : sock.write(buf)));
}).listen(5433);
const conn = net.connect(5433);
await once(conn, 'connect');
conn.setNoDelay(true);
async function query(sql) { // single connection; the next isn't sent until the answer arrives
conn.write(sql);
await once(conn, 'data');
}
const orders = 23, itemsPerOrder = [...Array(orders)].map((_, i) => (i < 7 ? 3 : 2)); // 23 orders, 53 items
let t = performance.now(), n = 0;
await query('orders'); n++;
for (let o = 0; o < orders; o++) {
await query(`items of order ${o}`); n++; // + 1 per order
for (let i = 0; i < itemsPerOrder[o]; i++) { await query(`product`); n++; } // + 1 per item
}
console.log(`N+1 : ${n} queries, ${(performance.now() - t).toFixed(0)} ms`);
t = performance.now();
await query('orders');
await query('items of all orders, JOIN products'); // ANY($1::int[])
console.log(`batched : 2 queries, ${(performance.now() - t).toFixed(1)} ms`);
process.exit(0);RTT_MS=0 node n1.mjs # "development": the database is on the same machine
RTT_MS=6 node n1.mjs # "production": the database is in another availability zoneOn my machine (Node.js 22):
RTT_MS=0 N+1 : 77 queries, 5 ms batched : 2 queries, 0.1 ms
RTT_MS=6 N+1 : 77 queries, 572 ms batched : 2 queries, 13.9 msNotice two things:
- Same code, different environment. In development 77 queries take 5 ms; nobody notices. In production the same code takes 572 ms. That’s the sneakiest thing about N+1: a bug you can’t test on a developer’s laptop.
- ~7.4 ms per round trip, not 6.
setTimeout’s own share and the loop and socket work were added to every trip. Reality is the same: getting a connection from the pool, the driver encoding the message and decoding the reply all add a bit more on top of the network for every query. In the lab we’ll measure this number at ~9 ms.
2. The incident: the My Orders screen
🔥 [FIRING] OrderHistorySlow: p95 of
GET /api/customers/:id/ordersis above 300 ms
It’s early October. On Monday the mobile team released version 3.0 of the ShopFlow app: a new My Orders screen that shows every past order with its items, product images and categories. The app reviews are good, except this one: “My Orders takes forever to open. Like a second. The website is fine.”
What you know:
- Product pages, listings and checkout are as fast as ever.
- The mobile app loads the screen with
GET /api/customers/:id/orders?limit=20; across all users, ~6 times a second. - The database is in another availability zone, ~6 ms away, and has been for a year.
- Recent deploys:
| Version | When | Change |
|---|---|---|
| 2.21.0 | Monday | order history returns every order’s items, with product image and category |
| 2.20.2 | last week | pg and express version upgrades |
| 2.20.1 | 2 weeks ago | per-product order item index (postmortem of the Part 5 incident) |
If you’ve set up the lab, start the incident:
git clone https://github.com/FARUK-YILDIRIM/nodejs-production-failure-lab.git
cd nodejs-production-failure-lab
./lab start 006💡 Want to try it yourself first? Stop here, open Grafana (http://localhost:3000) and Jaeger (http://localhost:16686) and investigate on your own for 30 minutes. The results of the steps below are in collapsed boxes. For the lab’s own hints:
./lab hint 006.
3. Investigation, step by step
Step 1: Scope: what’s slow and what isn’t?
Look at p95 by route in the dashboard’s Inside the API row. The panel next to it shows the time the API measures for each query.
What do we see?
/api/customers/:id/ordersp95 swings between 500 and 800 ms (yellow). Measured inside the API over the last 5 minutes: p50 338 ms, p95 615 ms.- The other routes are at the floor: products, categories and order detail are a few tens of milliseconds.
/api/orders(checkout, which makes an external call to the tax service) is steady at ~240 ms; it will stay the same after the fix too, so it’s not part of this incident. - In the right-hand panel, the first thing that catches the eye is
reports.sales(~240 ms): the finance report, a query that doesn’t even run several times a second and that nobody has complained about. All the other queries are bunched at the floor.

On the left, the yellow line is order history: it’s the only slow one. On the right, the only “slow” query is the finance report; order history’s queries are lost in the crowd at the floor.
Lesson: “Everything is slow” and “one endpoint is slow” are completely different investigations. Narrow the scope first.
Step 2: Is anyone working, or is everyone waiting?
In Part 5 the database CPU was at 100%. Here?
What do the resources say?
- The API’s CPU is ~0.23 cores: a quarter of its 1-core limit.
- Database sessions: 11 idle, almost no active sessions (occasional spikes of 1–2).
- Requests waiting in the connection pool: 0; most of the 10 connections are idle.

Neither the API nor the database is working. Nobody is busy, yet the request takes half a second: the time goes into waiting for something.
Slowness while the CPU is idle means something is being waited on. What?
Step 3: Are the queries slow?
The dashboard’s Database query time seen by the API panel shows p95, and the finance report squashes the scale so the small queries are unreadable. Plot the mean of order history’s four queries in Explore:
1000 * sum by (query) (rate(db_client_query_duration_seconds_sum{job="api", query=~"orders.items|products.by-id|orders.by-customer|customers.exists"}[1m]))
/ sum by (query) (rate(db_client_query_duration_seconds_count{job="api", query=~"orders.items|products.by-id|orders.by-customer|customers.exists"}[1m]))How long does a single query take?
From the API’s point of view, each one takes 8–10 ms: products.by-id ~9.0 ms, orders.items ~9.1 ms, orders.by-customer ~9.8 ms, customers.exists ~8.4 ms (average over the last 5 minutes).

All four queries sit in the 8–10 ms band, flat and very close to each other. There’s no “slow query”; they all seem to pay the same fixed price.
That’s a clue: reading a single product by primary key and grouping and counting a customer’s orders shouldn’t take the same time. If their durations are this similar, what determines the time isn’t the query itself but something common to every query.
So how do 9 ms queries add up to a 600 ms request?
Step 4: Look at the shape of the trace
In Jaeger, pick the shopflow-api service and the GET /api/customers/:id/orders operation and open a trace. Look at the shape before the numbers.
What does the trace look like?
A staircase. Under the request handler span, pg-pool.connect + pg.query pairs lined up one after another: each query starts where the previous one ended, none of them overlap. Each pg.query is 7–9 ms; getting a connection from the pool takes a few microseconds.

A customer with 6 orders and 8 items: 16 queries, each 7–9 ms, back to back. The whole trace is 128 ms; the gaps in between are microseconds. All of the time is inside the query spans.
Now count. This customer’s response has 6 orders and 8 items in total. The trace has 16 queries: 1 customer check + 1 order list + 6 (one per order) + 8 (one per item). The span count matches the data in the response one-for-one: classic N+1.
Step 5: Not one trace, a pattern
One trace is an anecdote. Take hundreds of traces of the same endpoint and plot request duration against query count (400 traces from the Jaeger API):
The relationship between query count and duration
The points sit on an almost perfect straight line: ~9.0 ms per query, with an intercept of ~1 ms. The lightest request is 11 queries and ~95 ms; the heaviest are 70–72 queries and over 600 ms. The few points above the line are moments when requests arriving at the same time waited briefly for a connection.

Each point is one request. Request time is almost exactly 9 times the query count: what sets this endpoint’s speed isn’t the database, it’s how many times it goes to the database.
This chart says two things at once:
- Latency varies by customer: a customer with many orders and items waits longer. Your most loyal customers get the worst experience.
- The way to bring p95 down isn’t making the queries faster, it’s making fewer of them.
Step 6: Look from the database’s side
The API says ~9 ms per query. What does PostgreSQL say? Look at two things: how many times per second the queries run, and how long they take inside the database.
Call counts and real execution time
First the rate. In Explore, put the queries’ calls per second on the same chart as the endpoint’s request rate:

The red line is the endpoint’s request rate: 6 per second. Orange products.by-id is ~177 per second, blue orders.items ~64. On average every request sends ~30 product queries and ~11 item queries.
Then the inside of the database (./lab psql):

Inside PostgreSQL the product query averages 0.040 ms and the item query 0.062 ms. The API measures ~9 ms for the same queries: more than 99% of the time is outside the database.
Two observations from this table:
- Call counts are far larger than the request count. The customer check (
customers WHERE id = $1) runs once per order history request: 8,199. The product query is at 177,572, the item query at 61,324. (These counters include earlier sessions too, and product pages also use the product query; the ratio comes out at roughly ~21 product queries per request. In my 6-minute window alone, as the chart shows, it’s ~30.) A query’s call count being a multiple of the request count of the endpoint that runs it is N+1’s signature inpg_stat_statements. - The database is doing almost nothing. The difference between 0.04 ms and 9 ms is spent in the network, the pool and the driver. Over the same window, the total time all queries spend inside PostgreSQL is ~46 ms per second: 5% of a single CPU.
Step 7: The latest code
Now you know where to look. customers/order-history.ts in 2.21.0:
export async function orderHistory(customerId: number, limit: number) {
const orders = await listCustomerOrders(customerId, limit); // 1 query
const history = [];
for (const order of orders) {
const items = await listOrderItems(order.id); // + 1 per order
const lines = [];
for (const item of items) {
const product = await findProduct(item.productId); // + 1 per item
lines.push({
/* ... */
image: product ? productImages(product.sku)[0] : null,
category: product?.categorySlug ?? null,
});
}
history.push({ ...order, total: formatMoney(order.totalCents), items: lines });
}
return history;
}The code is readable, tested and returns the correct result. The problem is that every await is a network trip, and they’re all waited for in sequence. What’s more, the only thing needed from findProduct is the category; the sku is already in the result of listOrderItems. The product and category are a single JOIN away from the item query.
Why wasn’t it seen in development? The development database is on the same machine (round trip ~0.1 ms) and the test customers have two orders. 6 queries × 0.1 ms is invisible; 77 queries × 9 ms isn’t. It’s the same as the demo’s 5 ms versus 572 ms.
The lab’s diagnosis questions and answers (./lab submit 006)
| Question | Answer |
|---|---|
| Which endpoint is slow? | GET /api/customers/:id/orders |
| What makes it slow? | It runs one query per order and per item, one after another |
| Where does most of each query’s time go? | The network round trip to the database |
4. Mitigation
A code change needs a review and a deploy. In the meantime:
- Shrink the page size. Lowering the
limitthe app asks for (or capping it on the server) reduces the number of orders and items, and therefore the round trips. It eases the symptom, not the cause. - Don’t: scale up the database or the API, or add indexes. Both are idle, and the queries already run in under 0.1 ms. A more powerful database turns 0.04 ms into 0.02 ms; it doesn’t touch the 9 ms trip.
5. The fix: a fixed number of queries per request
The goal: a fixed number of round trips per request, no matter how many orders and items there are. All it takes is fetching the items of all the orders, together with product and category information, in a single query and grouping them in memory.
Add a batched query to the repository. ANY($1::int[]) takes an array parameter and returns the rows that match any value in the array (PostgreSQL: Row and Array Comparisons, ANY/SOME (array)). Since the SQL text doesn’t change as the number of orders changes, it also shows up as a single row in pg_stat_statements.
// orders/orders.repository.ts
export function listItemsForOrders(orderIds: number[]): Promise<HistoryItem[]> {
return query<HistoryItem>(
'orders.items-for-orders',
`SELECT i.order_id AS "orderId", i.product_id AS "productId", p.sku, p.name, i.quantity,
i.unit_price_cents AS "unitPriceCents", c.slug AS "categorySlug"
FROM order_items i
JOIN products p ON p.id = i.product_id
JOIN categories c ON c.id = p.category_id
WHERE i.order_id = ANY($1::int[])
ORDER BY i.order_id, i.id`,
[orderIds],
);
}Group in memory and build the same response. Map.groupBy splits an array into a Map by the given key; the lab’s API runs on Node.js 24, where it’s built in:
// customers/order-history.ts
export async function orderHistory(customerId: number, limit: number) {
const orders = await listCustomerOrders(customerId, limit);
const items = Map.groupBy(await listItemsForOrders(orders.map((order) => order.id)), (item) => item.orderId);
return orders.map((order) => ({
...order,
total: formatMoney(order.totalCents),
items: (items.get(order.id) ?? []).map((item) => ({
productId: item.productId,
sku: item.sku,
name: item.name,
quantity: item.quantity,
unitPrice: formatMoney(item.unitPriceCents),
image: productImages(item.sku)[0] ?? null,
category: item.categorySlug,
})),
}));
}Now every request is 3 round trips: the customer check, the orders, the items. Whether it’s 6 orders or 23. ORDER BY i.order_id, i.id keeps the items in the same order as before; the lab’s functional check verifies the response stays byte-for-byte identical. Removing a feature doesn’t count as a fix.
The batched query takes longer inside PostgreSQL than the individual queries (a couple of JOINs, dozens of rows). It doesn’t matter: the win is going from 30–70 trips to 1.
Why isn’t Promise.all enough?
The first idea that comes to mind is “let’s run the loop in parallel”:
const history = await Promise.all(orders.map(async (order) => { /* ... */ }));This overlaps the trips: a few “waves” instead of 77 sequential rounds. Latency drops, but:
- It still sends 77 queries; the work for the database and the network doesn’t shrink.
- A single request holds most of the pool’s 10 connections at once. At 6 requests per second these requests make each other, and checkout, wait in the pool; the slowness spreads from one endpoint to the whole service.
The lab’s sample postmortem notes this as “where we got lucky”: the loops were sequential, so the problem stayed in a single endpoint.
6. Verification
./lab deploy
./lab verify 006verify runs that day’s traffic (web, mobile app and Googlebot, ~66 req/s) for 60 seconds and measures it from the client side:
| Measurement | Target | Before | After |
|---|---|---|---|
| Account (order history) p95 | < 300 ms | 665 ms | 38 ms |
| Catalog p95 | < 250 ms | 95 ms | 25 ms |
| Error rate | < 0.5% | 0% | 0% |
| API CPU | 0.29 cores | 0.22 cores | |
| Waiting in pool (max) | 0 | 0 |
Order history p95 went from 665 ms to 38 ms, about 17 times faster. CPU stayed nearly the same: there was no wasted CPU to begin with; what we removed was waiting. All 17 functional checks passed; the response for GET /api/customers/19852/orders?limit=25 is byte-for-byte identical.
The trace first. After the fix I sampled 100 traces rather than 400: every one has exactly 3 queries, median duration 29.7 ms, slowest 43.9 ms.

A customer with 10 orders and 22 items: this used to be 34 queries and ~300 ms, now it’s 3 queries and 30.2 ms. Each query is still ~9 ms; we didn’t shorten the trip, we made fewer of them.
Then the charts. The dashed orange line is the deploy at 01:34:35:

On the left, the yellow line (order history) drops to the floor at the deploy; the other routes stay put. On the right, the edge p95 and p99 of all traffic drop too, because most of the slow requests were this endpoint’s.

After 01:35 the item query (blue) is at zero, and the new batched query (orange) overlaps the request rate (purple, ~6/s): exactly one per request. The remaining ~32/s of the product query (red) comes from product pages. The colors changed when a new series was added in Explore; read them by the legend.

CPU is nearly the same; nothing was ever waiting in the pool. The only thing that changes is that idle connections (yellow) mostly approach 10: each request uses the pool 3 times, not 30–70.
7. Fixes that look right but aren’t
| Attempt | Why it falls short |
|---|---|
| Adding an index | Every query already uses the primary key or an index and runs in under 0.1 ms. The time isn’t inside the database. |
| Scaling up the database or the API | Both are idle (API ~0.23 cores, ~5% of the database CPU). The round-trip time doesn’t change with machine size. |
Rolling back the pg version (2.20.2) | A driver regression would slow down every query of every endpoint; here only one endpoint is slow. |
| “Let’s move the database into the API’s zone” | The distance has been the same for a year. What changed is how many times each request pays it. Moving shrinks the 9 ms, but latency still grows linearly with the data; the next feature will eat it up again. |
Parallelizing the loop with Promise.all | The query count stays the same, more than one pool connection is held per request, and the slowness can spread to checkout. Better, but not good. |
| Caching the response | Order history is per-customer and changes with every order; the first open (the moment people complain about most) stays slow. |
8. In production: alternatives and prevention
Different forms of the fix:
| Approach | When |
|---|---|
A batched query with WHERE id = ANY($1) + grouping in memory (this article) | The first choice in most cases: readable, a fixed number of queries. |
Building the whole history in PostgreSQL in one query with json_agg | One round trip; but harder to read and to keep in sync with the response shape. For very hot endpoints. |
Eager loading in the ORM (include, with, includes in Rails) | If you use an ORM, it’s there for exactly this. In the Rails guide’s example 11 queries go down to 2. Still look at the generated SQL. |
| DataLoader | The standard solution in GraphQL servers: it merges individual loads from the same event loop tick into a single batched call and caches per request. Resolvers naturally produce N+1. |
Measure queries per request. The most reliable way to catch N+1 is to look at the count, not the duration: duration varies with the environment, the count doesn’t.
- In tests: GitLab’s QueryRecorder approach: measure an operation’s query count, add new records to the database, measure again. If the count grows with the records, you have N+1. You can build the same idea in a few lines in any test framework: a wrapper that counts queries and a test that says “the query count is the same for a customer with 2 orders and one with 20”.
- In production: publish the query count per request as a span attribute or a histogram. Even a rough ratio from this lab’s metrics works:
- alert: QueriesPerRequestHigh
expr: |
sum(rate(db_client_query_duration_seconds_count{job="api"}[5m]))
/ sum(rate(http_server_request_duration_seconds_count{job="api"}[5m])) > 3
for: 15m
labels:
severity: ticket
annotations:
summary: "The API sends more than 3 queries per request on average; an endpoint may be N+1"The threshold is service-specific; measure your own normal first. In this lab, a rough calculation from pg_stat_statements puts the ratio at ~5.3 queries per request during the incident and (estimated) ~1.8 after the fix. With mixed traffic the average dilutes a single endpoint’s spike; the really strong signal is the query count per endpoint (a span attribute or a histogram with a route label).
- In traces: APM tools look for this pattern automatically. Sentry’s documentation describes its N+1 detector as a rule that looks for sequential, non-overlapping database spans with similar descriptions (Sentry: N+1 Queries). The same thing we did by eye in Jaeger.
Test with realistic latency. Run integration tests with a production-like round-trip time: a latency relay like the one in this lab, or Toxiproxy’s latency toxic. Make sure your test data includes customers with many orders too; a customer with two orders hides N+1.
Alerts for customer-facing endpoints should page, not open a ticket. In the lab’s sample postmortem the alert sat as a ticket for a whole day.
Code review checklist:
- Is there a query inside a loop (
await query,await repo.find…, lazy access to an association in an ORM)? - Can the data fetched in the loop be added to the query before the loop with a JOIN?
- Does the endpoint’s query count grow with the page size or with the customer’s data?
- Does a new client (mobile app, partner, crawler) change an endpoint’s traffic or page size?
Key takeaways
- Query time has two parts: inside the database and the trip. The trip is often the bigger part.
- Request time ≈ number of sequential round trips × round-trip time. If the number grows with the data, so does latency.
- Short
pg.queryspans lined up one after another in Jaeger are the N+1 staircase; count the spans and compare them with the data in the response. - If a query’s call count in
pg_stat_statementsis a multiple of the request count, it’s running in a loop. - The difference between the query time the API sees and
mean_exec_timeis time spent outside the database. - The bug development doesn’t show: a database on the same machine and a test customer with two orders.
- The fix isn’t making queries faster; it’s counting them and making fewer.
Test yourself
1. If every query takes 0.05 ms, why is the page slow?
The cost isn’t the query’s execution time, it’s the number of round trips. If the database is in another availability zone, every query pays a ~6–9 ms trip; 60 sequential queries add up to more than half a second. 0.05 ms is less than 1% of the total.
2. A customer’s order history trace has 42 pg.query spans. Before the fix, what can you say about this customer’s response?
Span count = 1 (customer check) + 1 (orders) + number of orders + number of items. The orders and items add up to 40. At ~9 ms per query, the request took ~380 ms inside the API. After the fix, 3 queries for the same customer.
3. Parallelizing the loop with Promise.all lowers latency. Why isn’t it the first choice?
The query count stays the same: the database and the network do the same work. More importantly, a single request asks the pool for many connections at once; under load, requests wait for each other in the pool, and endpoints that share the same pool, like checkout, slow down too. A fixed number of queries is both faster and safer.
4. How do you catch N+1 before it reaches production?
With tests that look at query count rather than duration: measure the query count in two scenarios, with few and many records, and expect them to be equal (GitLab’s QueryRecorder approach). Also, run integration tests with a realistic round-trip time (Toxiproxy or a similar latency relay) and test customers with many orders; and in review, question every awaited query inside a loop.
Further reading
Basics
- Rails Guides, Active Record Query Interface: Eager Loading Associations: a short definition of N+1, and
includesbringing 11 queries down to 2. Even if your ORM is different, the idea is the same. - PostgreSQL: pg_stat_statements: the official explanation of
calls,total_exec_timeandmean_exec_time. - PostgreSQL: Row and Array Comparisons:
ANY (array), the basis of the batched query.
Deep dives
- GitLab, QueryRecorder: catching N+1 in tests by counting queries.
- Sentry: N+1 Queries: the criteria of a rule that automatically detects N+1 from traces.
- DataLoader: batched loading and per-request caching in GraphQL.
- Toxiproxy: a TCP proxy for injecting network latency and failures in tests.
- MDN, Map.groupBy(): grouping the batched result in memory.
Real-world incidents
- GitLab, RCA: Gitaly n+1 calls causing bad latency and sidekiq queues to grow: one Gitaly call per tag, a 9-hour-45-minute degradation, and a fix with a batched RPC.
Next up: Hanging requests. Every few minutes the API freezes: no errors, no CPU, no logs; requests just go unanswered, and a restart fixes it for a minute. We’ll follow the anatomy of a connection pool, a connection leaking on an error path, and an idle in transaction session in pg_stat_activity.
The full lab: https://github.com/FARUK-YILDIRIM/nodejs-production-failure-lab. If you’ve solved the lab, you can generate the postmortem template with ./lab report 006 and compare it with your own write-up.