Card 02/ 06

ExampleDifficulty: Intermediate1 min

N+1 Example: What the Extra Queries Cost in Milliseconds

Thirty fast queries, one after another, put 600 milliseconds under a response before anything else runs.

The cost of the N+1 query problem is simple arithmetic: the number of queries times the time each one takes, paid one after another. A query that takes 20 milliseconds is too fast to notice on its own; in a list endpoint with an N+1 pattern it runs once per row.

The table shows the time the queries alone take at 20 milliseconds each, for lists of different sizes. The first query loads the list, and one more runs for each row:

The time an N+1 pattern puts under a response, at 20 ms per query
Rows in the listQueriesTime in queries alone
1011220 ms
2930600 ms
1001012,020 ms

Those figures are a floor, not a total: converting the response to JSON, running the business logic and the network round trip to the client all come after them. With a fetch join, a query that loads the list and its related rows in one statement, the same lists would take one query each, around 20 milliseconds whatever the size.

So a list endpoint that feels sluggish "for no reason" very often has this shape underneath: not one slow thing, but many fast things that run one after another, and more of them every time the list grows.