--- name: n-plus-one-finder description: Find database queries running inside loops — the N+1 pattern that is invisible on seed data and quadratic in production — plus unbounded queries with no limit and repeated identical reads in one request. Use when a page is slow, before a launch, after adding a list view, or when database load rises without traffic rising. --- # N+1 Finder ## Install Save this file as `~/.claude/skills/n-plus-one-finder/SKILL.md`, or `.claude/skills/n-plus-one-finder/SKILL.md` to scope it to one repo. Claude Code auto-discovers it. Invoke with `/n-plus-one-finder` or by asking "why is this page slow?". ## Why this exists N+1 is the most common serious performance bug in application code and the easiest to ship, because it is invisible exactly where you develop. With 10 seed rows it costs 11 fast local queries and nobody notices. With 10,000 rows and network latency it is 10,001 round trips and the page times out. It is also the bug that scales with your success. It appears the week traffic arrives, which is the week you can least afford to be debugging it. The tell is structural, not intuitive: **a query inside an iteration.** Find those and you have found most of it. ## Step 1 — Find queries inside loops ``` rg -n -B6 "await (prisma|db|knex|sequelize|supabase|pool)\." | rg -B6 "(\.map\(|\.forEach\(|for \(|for await|while \()" rg -n "\.map\(async" rg -n "for (const|await const).*\{[\s\S]{0,300}?await .*(find|select|query|get)" -U ``` Then read each hit, because the grep over-reports. You are confirming three things: 1. A query genuinely executes per iteration. 2. The collection is unbounded, or bounded only by something that grows. 3. The data could have been fetched in one query instead. `Promise.all` around per-item queries is **not** a fix. It converts a serial N+1 into a parallel one: still N queries, now arriving simultaneously, which exhausts the connection pool instead of the clock. It usually looks like the most optimised code in the file. ## Step 2 — Find the lazy-relation version The subtler form has no visible query. An ORM lazily loads a relation when a field is touched, so the loop looks like plain property access: ``` rg -n "\.(products|items|orders|user|author|seller|comments|tags)\b" --type-add 'src:*.{ts,tsx,js,rb,py}' -tsrc ``` Read the ones inside render loops or list mappers. In Prisma this is usually a missing `include`/`select`; in ActiveRecord a missing `includes`; in SQLAlchemy a missing `joinedload`. The fix is to fetch relations with the parent, once. ## Step 3 — Find unbounded reads A query with no limit is a time bomb whose fuse is your own growth: ``` rg -n "findMany\(|SELECT |\.all\(|\.filter\(" -A4 | rg -v "take:|limit|LIMIT|first:|\.take\(" ``` Flag any list read on a table that grows without bound (orders, events, logs, messages, downloads) and has no `take`/`LIMIT`. Fine at 30 rows, fatal at 300,000, and the transition is silent. Pay attention to reads that then discard most of what they fetched: selecting every row to count them, or to find one. Push that work into the database. ## Step 4 — Find repeated identical reads in one request Different from N+1: the same row fetched several times while rendering one page, usually because separate components each resolve the current user or the same product. ``` rg -n "getCurrentUser\(\)|findUnique\(\{ where: \{ id" -tsrc ``` Count how many times a single request path can hit each. The fix is request-scoped memoisation (React `cache()`, a DataLoader, or a per-request map), not another index. ## Step 5 — Measure, do not guess Static reading identifies candidates. Only measurement ranks them. Turn on query logging and load one real page: ``` # Prisma new PrismaClient({ log: ["query"] }) # then count what one request emits ``` Two numbers per page: total queries, and whether that total grows with the number of rows displayed. **The second is the whole diagnosis.** A page issuing 40 fixed queries is worth a look. A page issuing 3 + 1-per-item is the bug, even if it is faster today. Seed enough rows to see it. Testing N+1 against 5 records proves nothing. ## Step 6 — Report ``` Pages/endpoints measured: N+1 CONFIRMED -> 1 + N queries, N = measured: queries at rows fix: PARALLEL N+1 (Promise.all over queries) -> N concurrent queries, exhausts the pool rather than the clock UNBOUNDED READS no limit -> grows forever REPEATED IDENTICAL READS x per request -> memoise per request ``` Give each entry the query count at two different row counts. "12 queries at 10 rows, 102 at 100" ends the argument immediately; "possible N+1" starts one. ## Rules - Confirm by reading; the greps over-report by design. - `Promise.all` over N queries is still N queries. Say so explicitly. - Rank by measured growth, not by how bad the code looks. - Never add an index as the fix for N+1. The problem is the number of round trips, not the speed of each. - If a page's query count is constant as rows grow, it is not N+1. Say it is fine and move on. --- From [Toolbay](https://toolbay.ai/product/n-plus-one-finder). Free to use, modify, and share. Keep this line and others can find it too.