StoicBuilder

HandbookXI the TabulariumN+1 queries

XIthe Tabularium, Model the data

N+1 queries

1 min readUpdated 28 November

In plain words

An N+1 problem happens when code fetches a list with one query and then runs another query for each item, so a page showing 50 rows sends 51 queries instead of one or two.

Where you see it

Harbor's team page lists the members, then looks up each member's profile in a loop. It feels instant with five members on your laptop and takes three seconds for a large customer, and the query log shows the same select repeated 200 times with different ids.

app/team/page.tsxserver
// N+1: one query for the members, then one per memberconst members = await db.select().from(teamMembers).where(eq(teamMembers.teamId, teamId));for (const m of members) m.user = await getUser(m.userId); // one query with a joinconst rows = await db.select().from(teamMembers) .innerJoin(users, eq(users.id, teamMembers.userId)) .where(eq(teamMembers.teamId, teamId));
The loop looks harmless. Each await inside it is another round trip to the database.

What goes wrong

  1. Only testing with a little data

    With three seed rows, four queries take no time at all. Seed a team with hundreds of members and the problem shows up on your laptop.

  2. A loop you can't see

    An ORM relation loaded inside a map, or a list of server components that each fetch their own row, sends one query per item with no visible loop. Turn on query logging and count.

  3. Fixing it by fetching everything

    Loading the whole users table to avoid 50 small queries trades one problem for another. Fetch only the rows you need, with a join or a single where id in (...) query.

What to tell your agent

Copy this into Lovable, Bolt, Cursor or any agent
Turn on query logging, load the team page for a team with 200 members, and count the queries. If any query repeats once per row, replace it with a join or a single where id in (...) query, and show me the query count before and after.

Quick check

Sign in to earn +10 XP for it

Harbor's invoice list runs 1 query to get 100 invoices, then 1 query per invoice to fetch its team. How many queries does each page load send?

Got a prompt that touches N+1 queries?

Paste it. You get a better prompt first, then the cards that explain it.

Check your own prompt

Free, no sign-up.