Your App Is Slow Because of N+1 Queries (Here Is How to Spot Them)

An N+1 query is when your app asks the database for a list (1 query), then asks again for every item on that list (N more queries). A page with 50 orders that should take one trip to the database takes 51. It feels fine with five rows on your laptop and slow with five hundred in production.
It is a classic reason a page is slow in a way nobody can explain, because every individual query is fast. Here is how to see it, fix it, and avoid three traps after the fix. It is one of four causes covered in why your app gets slower with every new user.
What does it look like in code?
Say you have an orders page. You ask your AI tool for “a list of orders with the customer’s name on each one.” A very natural thing to generate:
const { data: orders } = await supabase.from('orders').select('*').order('id', { ascending: false }).limit(50)
for (const order of orders) { const { data: customer } = await supabase .from('customers') .select('name') .eq('id', order.customer_id) .single() order.customerName = customer.name}Read it as a person. One request for the orders, then one more inside the loop for each order. That is the “1” and the “N”. It passes your click-through test and reads like plain English.
The same shape hides in a component per row (an <OrderRow> that runs its own useEffect to fetch its own customer) and in ORM lazy loading, where reading order.customer in Rails, Django or SQLAlchemy quietly runs a query the first time you touch it (SQLAlchemy docs).
Why does it only hurt in production?
Because the cost is not the query. It is the trip.
The same loop, run against a real Postgres inside a test script with no network in between (a 100,000 row orders table, 2,000 customers, 50 orders on the page). The 51 queries took about 12 milliseconds in total. One join took about 1. At that speed nobody notices anything, and this is the whole trap: on your laptop, N+1 is invisible.
In production, each of those 51 queries is a separate network request from your app to your database, usually through an API in between. Suppose one round trip costs 60 ms (an assumption; the Network tab shows your real number, so multiply it by the request count). Fifty-one trips, one after another, is about three seconds of waiting before the page can draw. One trip is 60 ms. The database was never the slow part. The commuting was.
How do I spot it in two minutes?
You do not need a profiler. You need your browser.
- Open the slowest page of your app in Chrome. Open DevTools, then the Network tab.
- Filter by Fetch/XHR and reload.
- Look at the list. If you see the same request repeated down the page and only the id changes (
customers?id=eq.17,customers?id=eq.18,customers?id=eq.19…), that is an N+1. - The confirming test: add one more row to the data and reload. If the request count goes up by one, the count is tied to your row count. That is the signature.
If your queries run on a server (Next.js server components, an API route), the Network tab will not show them. Use the database side: Supabase’s Query Performance page is built on pg_stat_statements, which counts every query shape the database has run (Supabase docs). An N+1 shows up as one query with a huge call count and a tiny time per call.
The catch: do not hunt only for the slowest queries, because each call here is fast. Look for the query called far more often than your page views explain. Requests through Supabase’s API show up as SQL starting with WITH pgrst_source AS, the wrapper PostgREST adds (PostgREST docs). Read the table name.
How do I fix it?
Ask for the related data in the same request. Supabase calls this a nested select, and it works through foreign keys:
const { data: orders } = await supabase .from('orders') .select('id, total, customers ( name )') .order('id', { ascending: false }) .limit(50)One request. Each order comes back with its customer attached. Supabase’s docs say the API “automatically detect[s] relationships” from foreign keys (joins and nesting), which has a consequence AI-built schemas run into: if the tool created the column but never declared the foreign key, there is nothing to nest on. The fix is a foreign key in the schema, not a workaround in the code:
alter table orders add constraint orders_customer_id_fkey foreign key (customer_id) references customers (id);Other stacks have the same escape hatch: in Prisma, include fetches the relation in the same call (Prisma docs). The other classic fix is two queries instead of 51: fetch the orders, then fetch all their customers at once with .in('id', ids).
What goes wrong after the fix?
1. “Promise.all” is not a fix. Running the 51 requests in parallel makes the page faster, but you still send 51 requests at the same instant, which is how you hit rate and connection limits under real traffic. Count requests, not seconds.
2. The missing index. Postgres does not index the referencing side of a foreign key for you (the full story is in what an index is). Its docs say it is “often a good idea to index the referencing columns too,” and that declaring the constraint “does not automatically create an index” (PostgreSQL docs). In that local run (PGlite, 100,000 orders), looking up the orders for 50 customers took about 277 ms without an index on orders.customer_id and about 33 ms with one. Same data, same query, one line of SQL, which you can run in the Supabase SQL editor:
create index on orders (customer_id);Supabase’s Performance Advisor flags this as “Unindexed foreign keys” (docs), rated INFO, so it is easy to scroll past.
3. Nested does not mean limited. A .limit(50) on a nested select applies to the top level. Limit the nested table separately with .limit(5, { referencedTable: 'line_items' }) (Supabase docs). The nested table also gets its own row level security check, so if the page is empty or slow after the fix, look at the policies next.
Does every loop need fixing?
No. Only loops whose count grows with your data. A settings page that makes four requests makes four forever.
How do I stop it coming back?
AI tools rewrite files without telling you, and a loop can return in a later prompt. Test the count of queries, not the speed: “5 rows and 50 rows should cost the same number of queries” is true on every machine. Pair it with a test of what the user sees, because a “fix” can get faster by dropping rows. The full setup, with a failing run, a wrong fix caught by the behavior test and a Supabase version, is in A Regression Test for N+1 Queries.
A prompt to find them
Search the codebase for every place that calls the database or an API inside a loop, a
map, aforEach, or inside a component that is rendered once per row of a list. For each one, give me the file and line, and tell me how many requests a page makes if the list has 50 rows. Do not change anything yet. Then propose, per case, whether a nested select, aninquery, or a join is the right fix, and tell me which foreign keys need an index. Once I approve a fix, first write a test that fails on the current code because the query count grows with the number of rows, show me it failing, then make the change and show me it passing, along with a test of what the user sees so a faster fix cannot quietly drop rows.
Asking for the diagnosis first, and a failing test before the fix, is the same habit as in Stop pasting the error back.
The one check an engineer does by hand
Open the Network tab on your busiest list page, then add a row and reload. If the request count moved with it, you have an N+1. Do this on every list page before launch. It takes a minute per page, and it is one of the “falls over at real traffic” items in what breaks when your vibe-coded app gets real users and the launch checklist.
The Get AI Native ebook goes deeper on this. It is free, and the expected launch is around Christmas. Join the waitlist on the homepage.