Chapter 14: Data and failure

N+1 query

One query to fetch a list, then one more for each item in it. A page of 50 orders that looks up each order's customer separately makes 51 trips to the database. Each is fast, and the page is slow. One query can usually fetch them all.

This is the signature performance bug of agent-written code, because the code reads perfectly: loop over the orders, show each customer's name. It passes with 3 rows in the test database. Only a real list shows it, and only if something is counting queries.

Say it to your agent

“This list page has an N+1. Fetch the customers in one query with WHERE id IN (...) or a join. Add a test that loads the page with 50 orders, counts the SQL statements, and fails if there are more than 3.”

The workshop

Name a word, or describe what you mean in everyday language.