{"success":true,"name":"kill-n-1-calls-batch-and-prefetch-across-the-api-boundary","description":"Code calls an API or database once per item inside a loop","category":"ai-brimind","path":"ai-brimind/kill-n-1-calls-batch-and-prefetch-across-the-api-boundary/SKILL.md","file":"SKILL.md","content":"---\nname: kill-n-1-calls-batch-and-prefetch-across-the-api-boundary\ndescription: \"Code calls an API or database once per item inside a loop\"\n---\n\n# Kill N+1 Calls: Batch and Prefetch Across the API Boundary\n\n## When to use\nYou are writing or reviewing code that loops over a list and makes one API/database call per element, or an endpoint whose consumers must call it once per item.\n\n## Example request\nFrontend fetches 50 items then calls /details/:id 50 times → one screen costs 51 requests; a batch endpoint or included details is the fix. — ORM loads orders then queries the customer per order → classic N+1; the ORM's include/join mechanism already solves it. — Enrichment loop calls a third-party API per row → rate limits hit instantly; the provider's bulk endpoint was in the docs. — 'It's fast' in dev with 5 items → production has 5000; per-item cost multiplied by real N is the honest measure.\n\n## Instructions\nAct as a round-trip accountant who counts calls per user action and refuses loops of requests. When you see per-item calls: 1) Count honestly — for a realistic N, how many network/database round-trips does one user action trigger? Write the number down; 1+N is the smell. 2) Look for the existing batch mechanism first: the ORM's eager loading/joins, the API's bulk or ?ids= endpoint, the provider's batch operations, GraphQL's field selection — these exist precisely for this and beat any custom loop. 3) If you own the API being hammered, that's the signal to design the batch shape consumers actually need (list with embedded details, or a multi-get) rather than telling them to loop politely. 4) Keep batches bounded — a batch endpoint without a max size just moves the unbounded problem. 5) Verify with realistic volume: measure round-trips and latency before and after; if you can't test at scale, flag it. Only conclude once the per-action call count is confirmed near-constant, and explain how the batching preserves the same data with fewer trips rather than caching the problem away.\n\n## Metadata\n- role: developer\n- level: tactical\n- places: vibeCoding\n- origin: ai.brimind.pro skill #906\n","linked_files":[],"origin":"ai.brimind.pro","owner_id":null,"source":"router"}