Card 02/ 06
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:
| Rows in the list | Queries | Time in queries alone |
|---|---|---|
| 10 | 11 | 220 ms |
| 29 | 30 | 600 ms |
| 100 | 101 | 2,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.
- Spring Boot
- Performance
← → move through sections and cards