What this prompt does
This prompt casts the AI as a senior backend engineer and makes it hunt for N+1 query patterns in a real request log, returning ORM-specific fixes instead of generic performance tips. You provide [orm], [framework], and the request log via [query_log]. It identifies each parent query and its repeated child query, counts repetitions per request and per minute of traffic, gives the exact eager-loading fix, shows before/after code, estimates the query-count reduction, and ranks every finding by impact.
The structure works because it ranks fixes by real per-request impact rather than treating every N+1 equally. By multiplying requests per minute against the extra queries each pattern fires, the prompt surfaces where the traffic actually hurts. [orm] determines the exact fix syntax — eager-load clauses, joins, or prefetch differ across ORMs — and [framework] provides the surrounding context for the call-site code. Feeding a real [query_log] rather than a hunch means the fixes land where the load really is.
When to use it
- A list page silently fires hundreds of queries because a relationship loads in a loop.
- You inherited an app and want to find its worst N+1 offenders from real traffic.
- You want ORM-specific eager-loading code, not a generic "use eager loading" reminder.
- You need to prioritise which N+1 to fix first by actual traffic impact.
- You want before/after code for the call site, ready to drop in.
- You are wary of over-eager-loading and want only the relationships the view renders.
Example output
You get a ranked table of findings — each row naming the parent query, the repeated child query, the repetition count, and the impact score — followed by the fixed code for the top offenders, with before/after snippets in your ORM's syntax and an estimate of the query-count reduction per request.
Pro tips
- Feed a real
[query_log]from one slow request, not a synthetic example — the ranking is only as good as the traffic it sees. - Set
[orm]precisely, since the fix syntax for eager loading differs sharply between ORMs and a near-match will not paste cleanly. - Use the impact ranking to fix the top offenders first instead of chasing every N+1 at once.
- Avoid eager-loading everything blindly; pull only the relationships the view renders, or you trade N+1 for one giant over-fetching join.
- Compare the estimated query-count reduction against a fresh log after the fix to confirm it actually landed, since the estimate is a projection, not a measurement.
- Watch for relationships loading inside a loop in the call-site code; that pattern is the classic source of N+1, and the before/after snippet should make it obvious.
- If a finding's repetition count looks low, deprioritise it — a rare N+1 on a low-traffic page rarely justifies the change, and your attention is better spent on the top of the ranked table.