{"success":true,"name":"kill-the-n-1-pattern-never-query-the-database-inside-a-loop","description":"Writing code that loops over records and fetches related data for each one","category":"ai-brimind","path":"ai-brimind/kill-the-n-1-pattern-never-query-the-database-inside-a-loop/SKILL.md","file":"SKILL.md","content":"---\nname: kill-the-n-1-pattern-never-query-the-database-inside-a-loop\ndescription: \"Writing code that loops over records and fetches related data for each one\"\n---\n\n# Kill the N+1 Pattern: Never Query the Database Inside a Loop\n\n## When to use\nYou are writing backend code (or an API-calling frontend loop) that first fetches a list, then runs another query or request PER ITEM in that list to get related data — one query becoming N+1 queries.\n\n## Example request\nFetch 50 orders, then inside a loop fetch each order's user → 51 queries where 2 would do; this classic has a name: the N+1 problem. Dashboard loops over products calling the API once per product for its stock → 100 network round-trips make a 5-second page; one batch endpoint returning all stocks is the shape. The fix exists in the tools: SQL joins, Mongoose populate, or one query with 'id IN (list)' then matching in memory → the DB layer already solved 'fetch related data in one go'. The loop runs over 3 fixed items ever → fine, N+1 is a growth problem; the danger is loops over user-generated lists that grow.\n\n## Instructions\nAct as a developer whose alarm bell rings the moment a query, fetch, or await appears inside a loop over records — because each innocent iteration is a full round-trip to the database or network, and round-trips are what make pages slow, not CPU. When you catch this shape (in code you are writing OR code you are about to copy), do this: (1) Name it out loud: 'this is N+1 — one query for the list, then N more for the details'. Count what N will be with real data, not test data: 50 orders means 51 round-trips per page load. (2) Reach for the mechanism your stack already has instead of the loop: in SQL, a JOIN or a single 'WHERE id IN (...)' query; in MongoDB/Mongoose, populate or an aggregation with $lookup, or one find with { _id: { $in: ids } } followed by matching in memory with a map. Collecting IDs first and fetching related records in ONE batch is almost always the answer, and it is built in — do not hand-roll per-item fetching when the ORM/driver has a word for this. (3) Apply the same rule to HTTP: a frontend looping requests per item is N+1 over the network, the most expensive kind; the fix is a backend endpoint that accepts the list and returns the batch. (4) After batching, verify: count the actual queries or requests for one page load (log them, or watch the network tab) — the number should be small and FIXED, not proportional to the data. (5) If the loop is over a tiny constant set that can never grow, say so and leave it — this discipline targets lists that scale with users. Only move on once the per-item query is gone and you can state the fixed number of round-trips one page load costs, and why that number stays the same at 10 items and at 10,000.\n\n## Metadata\n- role: developer\n- level: tactical\n- places: vibeCoding\n- origin: ai.brimind.pro skill #199\n","linked_files":[],"origin":"ai.brimind.pro","owner_id":null,"source":"router"}