N+1 queries and how to batch them
Why a query per row explodes, loading each level of a nested menu in one batched query, assembling the tree in Go with index maps, and why one giant JOIN is worse.
Learning outcomes
- Spot an N+1 pattern and count its round trips.
- Load each level of a nested response with one IN query per table.
- Assemble nested JSON in Go with maps from parent id to slice index, keeping SQL order.
- Avoid holding pointers into a slice that may still grow.
- Explain why a single JOIN multiplies rows, and prove a query budget with a counting fake.
Why N+1 queries are a problem
Your restaurant database stores menu information across several related tables:
itemsitem_sizesoption_groupsoptionsoption_prices
When a client requests a restaurant's menu, the API needs to retrieve all of this information and assemble it into a nested JSON response.
A straightforward implementation might load the items first, then query the database separately for each item's sizes, groups, options, and prices.
It works, but it introduces a common database performance problem called the N+1 query problem.
The idea is simple: one query retrieves a collection of records, and then additional queries are executed individually for each record in that collection.
The number of database round trips grows with the amount of data being retrieved.
This becomes particularly expensive when your menu contains many items or configurable options.
Understanding the N+1 problem
Suppose a restaurant has 30 menu items.
You start by retrieving them:
SELECT id, restaurant_id, name, sort
FROM items
WHERE restaurant_id = ?
ORDER BY sort, id;This is one query.
Now imagine the application loops through the returned items and retrieves their sizes individually:
SELECT item_id, size, price_paise
FROM item_sizes
WHERE item_id = ?;For 30 items, that's another 30 queries.
You then retrieve option groups for each item, options for each group, and prices for each option.
A simplified count, assuming one group and one option per item, looks like this:
| Operation | Number of queries |
|---|---|
| Retrieve items | 1 |
| Retrieve sizes | 30 |
| Retrieve groups | 30 |
| Retrieve options | 30 |
| Retrieve option prices | 30 |
| Total | 121 |
The actual count depends on the number of groups and options. In a hierarchical implementation, options are loaded per group and prices per option, so the total can be even higher.
The important point is that query count grows with the number of records rather than remaining bounded by the number of data relationships.
Why is this expensive?
Every database query has overhead beyond executing SQL.
A typical operation involves:
- Acquiring a connection from the connection pool.
- Sending the query to MySQL.
- MySQL parsing and executing it.
- Returning the result.
- Transferring and scanning the returned rows.
Even when an individual query is fast, repeatedly paying the round-trip cost adds up.
Consider an illustrative example where each database round trip takes approximately 1 millisecond.
| Approach | Queries | Approximate round-trip time |
|---|---|---|
| N+1 implementation | 121 | 121 ms |
| Batched implementation | 5 | 5 ms |
These are simplified estimates, not guaranteed execution times. Actual latency depends on query execution, connection availability, network conditions, and database load.
However, the difference becomes significant as traffic and menu complexity increase.
Your objective is to retrieve the complete menu using a bounded number of queries.
Batching related records
The solution is batch loading.
Instead of asking MySQL for one item's related data at a time, collect the relevant IDs and retrieve all corresponding records in one query.
For example, instead of:
SELECT item_id, size, price_paise
FROM item_sizes
WHERE item_id = 1;
SELECT item_id, size, price_paise
FROM item_sizes
WHERE item_id = 2;
SELECT item_id, size, price_paise
FROM item_sizes
WHERE item_id = 3;Use:
SELECT item_id, size, price_paise
FROM item_sizes
WHERE item_id IN (1, 2, 3);One query retrieves the sizes for all three items.
The application then groups the results by item_id.
The batching strategy for your menu
Your menu has several levels of relationships.


You can retrieve this entire structure in five queries:
| Query | What it retrieves |
|---|---|
| 1 | All items belonging to the restaurant |
| 2 | All sizes belonging to those items |
| 3 | All option groups belonging to those items |
| 4 | All options belonging to those groups |
| 5 | All prices belonging to those options |
The number of queries depends on the number of relationship levels, not the number of records within those levels.
For 30 items, 10 groups and 40 options, you still execute at most five queries rather than issuing separate queries for every item, group and option.
Using IN with sqlc.slice
Your generated query layer already supports variable-length ID lists through sqlc.slice.
For example:
-- name: ListSizesByItemIDs :many
SELECT item_id, size, price_paise
FROM item_sizes
WHERE item_id IN (sqlc.slice(item_ids))
ORDER BY item_id, price_paise;The generated method accepts:
func (q *Queries) ListSizesByItemIDs(
ctx context.Context,
itemIds []uint64,
) ([]ItemSize, error)You can supply all item IDs in one call.
The generated SQL expands the slice into the required number of placeholders. Generated query results use the column types (uint32 for INT UNSIGNED, uint8 for TINYINT UNSIGNED), so convert them with int(...) when you copy them into the response structs.
This is still parameterized SQL. You aren't inserting raw values into the query string.
The same approach applies to option groups, options and option prices.
One limitation is very large ID lists. Sending thousands of IDs in a single IN clause can create large SQL statements and consume substantial memory.
For this menu endpoint, the lists are expected to be manageable. For workloads involving thousands of IDs, split them into bounded batches and combine the results.
Also handle empty ID slices explicitly. If there are no groups, there is no reason to issue an options query with an empty slice.
Assembling nested JSON in Go
Retrieving the data efficiently is only half the problem.
The API needs to transform several flat database result sets into a nested response.
Your response structures look like this:
type Item struct {
ID int64 `json:"id"`
Name string `json:"name"`
Sizes []Size `json:"sizes"`
Groups []Group `json:"groups"`
}
type Size struct {
Size string `json:"size"`
PricePaise int `json:"price_paise"`
}
type Group struct {
ID int64 `json:"id"`
Name string `json:"name"`
MinSelect int `json:"min_select"`
MaxSelect int `json:"max_select"`
Options []Option `json:"options"`
}
type Option struct {
ID int64 `json:"id"`
Name string `json:"name"`
InStock bool `json:"in_stock"`
Prices map[string]int `json:"prices"`
}The intended response is:
{
"id": 1,
"name": "Farmhouse pizza",
"sizes": [
{
"size": "M",
"price_paise": 39900
}
],
"groups": [
{
"id": 1,
"name": "Crust",
"min_select": 1,
"max_select": 1,
"options": [
{
"id": 1,
"name": "Classic hand tossed",
"in_stock": true,
"prices": {
"*": 0
}
},
{
"id": 2,
"name": "Cheese burst",
"in_stock": true,
"prices": {
"M": 9900,
"L": 12900
}
}
]
}
]
}Notice the prices map.
The wildcard key * represents a price that applies to every size. Other options can have size-specific prices.
Why use index maps?
Each query returns a flat slice of records.
For example:
sizes := []db.ItemSize{
{ItemID: 1, Size: "R"},
{ItemID: 1, Size: "M"},
{ItemID: 2, Size: "R"},
}You need to know which item each size belongs to.
One approach would be to loop over every item for every size, checking whether the IDs match.
That introduces unnecessary repeated searching.
Instead, build a map from the item's ID to its position in the response slice:
itemAt := make(map[uint64]int)
for i := range items {
itemAt[uint64(items[i].ID)] = i
}Now, when processing a size, you can find its parent directly:
index := itemAt[size.ItemID]
items[index].Sizes = append(
items[index].Sizes,
Size{
Size: size.Size,
PricePaise: int(size.PricePaise),
},
)The map provides efficient lookup without scanning the entire item slice.
The same principle applies to the remaining levels.
For groups:
type groupPosition struct {
item int
group int
}
groupAt := make(map[uint64]groupPosition)For options:
type optionPosition struct {
item int
group int
option int
}
optionAt := make(map[uint64]optionPosition)Each map records where a particular entity lives within the nested response.
When an option price arrives, its option_id identifies the option, whose saved position identifies the exact nested object to update.
The result is a single pass over each query's results.
The slice pointer problem
There is an important Go detail when building nested slices.
Suppose you append items to a slice and save pointers to its elements:
item := &items[i]Then later append more items.
Go slices consist of a pointer to an underlying array, a length, and a capacity. When the capacity is exceeded, append can allocate a new underlying array and copy the existing elements.
Previously saved pointers remain valid, but they point to elements in the old backing array. They are no longer references to the corresponding elements in the current slice.
This can cause updates to be applied to objects that are no longer part of the final response.
Preserve SQL ordering
Your queries already specify deterministic ordering:
- Items:
sort, thenid. - Sizes:
item_id, thenprice_paise, so sizes list from smallest to largest. - Groups:
item_id, thenid. - Options:
group_id, thenid. - Prices:
option_id, thensize.
When assembling the response, append records in the order they were returned.
Use maps only for locating parents, not for generating output order.
Go map iteration order is unspecified. Iterating over an ID map to construct the final response can therefore produce inconsistent ordering.
Why not use one large JOIN?
You might wonder why the entire menu cannot be retrieved using one SQL query with several JOIN operations.
For example:
SELECT
i.id,
i.name,
s.size,
s.price_paise,
g.id,
g.name,
o.id,
o.name,
p.size,
p.price_paise
FROM items i
LEFT JOIN item_sizes s ON s.item_id = i.id
LEFT JOIN option_groups g ON g.item_id = i.id
LEFT JOIN options o ON o.group_id = g.id
LEFT JOIN option_prices p ON p.option_id = o.id
WHERE i.restaurant_id = ?;This appears attractive because it uses one query.
However, it creates another problem: row multiplication.
Suppose one item has:
- 3 sizes.
- 2 option groups.
- 4 options per group.
- 2 prices per option.
Combining these independent one-to-many relationships can produce many repeated combinations of the same item and its related records.
The application must then deduplicate and reconstruct the original hierarchy.
This creates additional complexity:
- Repeated item data.
- Repeated size data.
- Repeated group data.
- Repeated option data.
- More complicated scanning and deduplication logic.
A single query is not automatically more efficient than several carefully designed queries.
What about JSON aggregation?
MySQL also provides JSON aggregation functions such as JSON_ARRAYAGG.
You could use them to build nested JSON directly inside SQL.
That reduces the amount of assembly performed in Go, but introduces other trade-offs:
- More complicated SQL.
- Database-specific JSON construction.
- Less convenient typed result structures.
- More difficult testing of individual relationships.
- Additional parsing and type handling in Go.
For this course, keep the database responsible for retrieving relational data and Go responsible for assembling the application response.
This gives you a clear separation and makes the resulting code easier to maintain.
Handling empty relationships
Not every restaurant has a menu, and not every menu item has configurable options.
Your service needs to handle these cases without executing unnecessary queries.
The verified retrieval sequence is:
1. Retrieve items
Call ListItemsByRestaurant.
If there are no items, execute GetRestaurant to distinguish between:
- An existing restaurant with an empty menu.
- A restaurant that does not exist.
If the restaurant exists, return an initialized empty slice:
return []Item{}, nilIf GetRestaurant returns sql.ErrNoRows, return the wrapped ErrNotFound.
2. Retrieve sizes
Collect item IDs and call ListSizesByItemIDs.
Attach each size to its parent item using itemAt.
3. Retrieve option groups
Call ListGroupsByItemIDs.
If there are no groups, return the items with their sizes and empty group slices.
4. Retrieve options
Collect group IDs and call ListOptionsByGroupIDs.
If no options exist, return the assembled items and groups without querying prices.
5. Retrieve option prices
Collect option IDs and call ListOptionPricesByOptionIDs.
Attach each price to its option using optionAt.
On the normal path, this requires exactly five queries.
The additional restaurant lookup only occurs when there are no items, so the maximum remains five.
Timeouts and detecting N+1 queries
Your entire menu retrieval operation uses one 500 ms timeout.
Create a child context at the beginning of Menu:
queryCtx, cancel := context.WithTimeout(ctx, 500*time.Millisecond)
defer cancel()Pass this same context to all five generated queries.
This is important because the timeout applies to the entire operation, not 500 milliseconds independently to every query.
If earlier queries consume most of the available time, later queries have correspondingly less time remaining.
The menu service should also depend on a narrow query interface rather than directly creating its own database connection.
This makes it possible to test query counts without requiring a real MySQL database.
Detecting N+1 in tests
Create a fake implementation of the query interface.
Each method increments a counter when called.
For a complete menu, assert that:
- Each of the five query methods is called once.
- No query count increases with the number of items, groups, or options.
- No query method is invoked from inside a loop.
You can also test sparse menus to verify that unnecessary queries are skipped.
In production, query logs and distributed tracing can reveal repeated database calls within a single HTTP request.
For example, seeing the same SELECT statement executed 30 times under one request is a strong indication of an N+1 problem.
Knowledge assessment
A restaurant has 30 menu items. The service executes one query for items, followed by one query for each item's sizes and another for each item's option groups. Why is this an N+1 problem?
Practical applications
Exercise 2.12: GET /v1/restaurants/{id}/menu in five queries
You'll implement the complete menu retrieval service using the five generated sqlc query methods.
The exercise will test that:
- Menu data is retrieved in batches.
- No query executes inside a loop.
- The nested response preserves the SQL ordering.
- Sizes, groups, options and prices are attached to their correct parents.
- Empty relationships skip unnecessary queries.
- An empty menu is distinguished from a missing restaurant.
- No more than five queries are executed for any restaurant.
You'll also use a fake query implementation to verify the query count independently of MySQL.
Week 3: Order details and events
The same approach will be useful when retrieving an order with its order lines and associated events.
Instead of querying separately for every line or event, you'll collect IDs, retrieve related records in batches, and assemble the response in Go.
The underlying principle is the same: control the number of database round trips, retrieve related records in batches, and reconstruct the application response using predictable in-memory lookups.
By the end of this module, you should be able to explain why five well-designed queries can be substantially better than one hundred individually executed queries, even when both approaches return the same information.
References
Everything above is explained on this page; these are where it comes from (Go 1.25, sqlc v1.31.1, MySQL 8.4).