A Regression Test for N+1 Queries

You fixed the slow orders page. Two weeks later you ask your AI tool to add a “paid” badge to each order, and it rewrites the file. The page is slow again, and nothing told you. The loop that makes one request per row came back inside a change that looked unrelated.
That pattern is called an N+1: one query for the list, then one more for each row. A test can catch it. Test how many queries a page makes, not how long it takes, because “a small table and a large table cost the same number of queries” is true on every machine. Your App Is Slow Because of N+1 Queries explains the problem and the fix; this post is the safety net for that fix.
Why isn’t one test enough?
A query-count test alone has a hole. The fastest way to get the count down is to delete the work. A “fix” that drops rows, or joins in a way that hides some of them, makes the page quick and wrong, and a count test happily passes it.
So the setup is two tests that guard two different things:
| Test | It protects | Fails when |
|---|---|---|
| Behavior test | What the user sees | A rewrite drops rows, reorders them or attaches the wrong customer |
| Count test | Performance, as a property | The number of queries grows with the number of rows |
The behavior test does not care how the data is fetched. That is on purpose: it keeps passing through any rewrite that is correct. It only fails on what it covers, so the edge cases you seed are the edge cases you are protected against. This is the idea behind testing behaviors, not code.
What does the test look like?
These were run in a scratch project with Node’s built-in test runner and PGlite, which is Postgres compiled to run inside Node (npm i @electric-sql/pglite, then node --test). PGlite is real Postgres but not Supabase: it has no row level security, no role grants and no PostgREST. Treat it as a way to test your query logic, not your whole stack.
The page under test lists the newest 50 orders with each customer’s name. One order is a guest checkout with no customer, because real data always has one of those. Put this in orders.test.js, and export listOrders(db) from orders.js:
import { test } from 'node:test'import assert from 'node:assert/strict'import { PGlite } from '@electric-sql/pglite'import { listOrders } from './orders.js'
// Wrap the database so every query is counted.function counted(db) { const counter = { n: 0 } const wrap = (target) => ({ query: (...args) => { counter.n++; return target.query(...args) }, exec: (...args) => { counter.n++; return target.exec(...args) }, }) return { counter, ...wrap(db), // Queries inside a transaction go through `tx`, so count those too. transaction: (fn) => db.transaction((tx) => fn(wrap(tx))), }}
async function seed(orderCount) { const db = new PGlite() await db.exec(` create table customers (id serial primary key, name text not null); create table orders (id serial primary key, customer_id int references customers(id), total int); insert into customers (name) select 'customer ' || g from generate_series(1, 200) g; insert into orders (customer_id, total) select (g % 200) + 1, g from generate_series(1, ${orderCount}) g; -- one guest checkout: an order with no customer insert into orders (customer_id, total) values (null, 999); `) return db}
test('newest 50 orders, right customer on each, guest orders still listed', async () => { const db = counted(await seed(60)) const orders = await listOrders(db) assert.equal(orders.length, 50) assert.equal(orders[0].total, 999) assert.equal(orders[0].customerName, 'Unknown') for (const o of orders.slice(1)) assert.equal(o.customerName, `customer ${o.customer_id}`)})
test('query count does not grow with the number of rows', async () => { const PAGE_SIZE = 50 const small = counted(await seed(5)) const smallRows = await listOrders(small) const large = counted(await seed(60)) const largeRows = await listOrders(large) // Guard: the small page must be shorter than a full page and the large one full, // otherwise both pages could cost the same for the wrong reason. assert.ok(smallRows.length < PAGE_SIZE && largeRows.length === PAGE_SIZE) assert.equal(large.counter.n, small.counter.n, `small table: ${small.counter.n} queries, large table: ${large.counter.n} queries`)})The guard line keeps the count test honest: if the page size ever drops below the small seed, both pages would cost the same for the wrong reason. Run each version of listOrders in its own node --test run, because Node caches imported modules and swapping the file inside one process can test stale code.
The count test never mentions a number like “2”. It compares a small table with a larger one, so it does not break when you legitimately add a second query to the page. It only breaks when the count depends on the data. It does not survive a second query per row, and it should not: that is an N+1 again.
What does it do to the loop?
Run it against the loop version, the one that fetches each customer inside a for. The failing and passing outputs in this post are pasted from real runs of this exact test file:
export async function listOrders(db) { const { rows: orders } = await db.query('select id, customer_id, total from orders order by id desc limit 50') for (const order of orders) { const { rows } = await db.query('select name from customers where id = $1', [order.customer_id]) order.customerName = rows[0] ? rows[0].name : 'Unknown' } return orders}ok 1 - newest 50 orders, right customer on each, guest orders still listednot ok 2 - query count does not grow with the number of rows small table: 7 queries, large table: 51 queries# pass 1# fail 1The small table has 5 numbered orders plus the guest order, so 6 rows and 7 queries. The large table page shows 50 rows and costs 51. The loop is correct but slow, so the behavior test passes and the count test fails. That is the proof the count test can catch the bug it was written for. The same loop written inside db.transaction(async (tx) => ...) fails the count test in the same way, because the wrapper hands the callback a counted tx. A wrapper that counted only the transaction() call would miss every query inside it.
What does it do to a wrong fix?
Now the tempting fix: replace the loop with a join.
export async function listOrders(db) { const { rows } = await db.query(` select o.id, o.customer_id, o.total, c.name as "customerName" from orders o join customers c on c.id = o.customer_id order by o.id desc limit 50`) return rows}not ok 1 - newest 50 orders, right customer on each, guest orders still listed expected: 999 actual: 60ok 2 - query count does not grow with the number of rows# pass 1# fail 1Here it is the other way round. A plain join in SQL is an inner join, which keeps only rows that have a match on both sides, so the guest order, which has no customer, disappears. One query, fast, and a customer’s order is missing from the page. The count test passes this change. The behavior test is what stops it.
The correct version keeps those rows:
export async function listOrders(db) { const { rows } = await db.query(` select o.id, o.customer_id, o.total, coalesce(c.name, 'Unknown') as "customerName" from orders o left join customers c on c.id = o.customer_id order by o.id desc limit 50`) return rows}Both tests pass. Showing “Unknown” for a guest order is a product choice, so decide it yourself and write it into the test. If your product hides guest orders, the inner join is right and the test changes with it.
How do I do this in a Supabase app?
The idea is the same: count what leaves the app. supabase-js lets you pass your own fetch when you create the client (global.fetch in the client options), so a wrapper that counts calls counts requests:
import { createClient } from '@supabase/supabase-js'
function countingClient(url, key) { const counter = { n: 0 } const countingFetch = (...args) => { counter.n++; return fetch(...args) } const supabase = createClient(url, key, { global: { fetch: countingFetch } }) return { supabase, counter }}Then call your page’s data function with that client against a local or test project, and assert counter.n stays small. As a check of the counter itself, it was run against a fake fetch that returns canned rows: the loop version from the top of the N+1 post made 51 requests for a 50 row page, and the nested select (select('id, customer_id, customers(name)')) made 1. Nothing in this section was run against a live Supabase project, so the first run on yours is also a test of the wrapper.
A fake-fetch check does not prove that every supabase-js feature (auth refresh, storage, realtime) goes through global.fetch, so confirm on your own project that the counter moves when the page loads. One more limit: this counts every request the client makes, including any that are not your page’s data. If your number is higher than expected, print the URLs the wrapper sees and count only the data requests.
A prompt to set this up
Find the page in my app that lists rows with related data, for example orders with customer names. Write two tests for its data function. First, a behavior test with seeded data that includes an edge case such as a row with no related record, asserting exactly what the user should see: which rows, in what order, with which names. Second, a count test that seeds 5 rows and 60 rows and asserts the number of database queries or requests is the same for both. Show me both passing on the current code. Then temporarily reintroduce a per-row query inside a loop and show me the count test failing, and revert it. Do not change any app code except to make it testable.
Writing the failing test before the change is the habit from TDD with AI. Asking the AI to break the code and watch the test fail is the only way to know the test is not decoration.
The one check an engineer does by hand
Before you trust any test you did not write, break the thing it guards. Put a loop back, run the test, and see it go red. Then undo it. It takes two minutes, and it is the difference between a safety net and a picture of one. The same habit runs through Stop pasting the error back.
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.