What is the N+1 query problem and how do I fix it?
The name describes the shape of the problem. One query fetches a list of records, and then one additional query runs for each record in that list to load something related. Fetching a hundred posts and then reading each post's author issues a hundred and one queries where two would have done.
It shows up most often with object-relational mappers that load relationships lazily. The code looks entirely innocent, because accessing a related object is just a property access, and nothing in the source suggests a network round trip is happening inside a loop. That invisibility is what makes the problem so common.
The standard fix is to tell the data layer up front which relationships you intend to use, so it can fetch them together. Most ORMs offer this as eager loading, and it typically resolves to either a join or a second query that collects all the related records at once. Either way the query count stops growing with the size of the result set, which is the property that actually matters.
In GraphQL the same problem arises naturally because resolvers run per field per item. The usual answer is a batching loader that collects the individual lookups occurring within one tick and issues a single query for all of them.
Detection is the part teams neglect. The symptom rarely appears in development, where the seed database has a handful of rows and a hundred fast queries still feel instant. It becomes visible in production, where latency scales with data volume. Log queries in development, or count them per request and fail a test when a route exceeds a threshold. That turns an invisible scaling problem into something a code review can catch.
It is worth noting that a small number of extra queries is not automatically a bug. The problem is specifically that the count grows with the result set, so it degrades exactly as the application succeeds.