Group
  • Database

    Fix my N+1 query problems

    Finds loops that query per item and rewrites them as joins, eager loads, or batched lookups.

    • Debug & fix
    • Improve quality
    • Intermediate
    • Cursor
    • General

Free Prompt

Hunt down N+1 query patterns in my app. Look for the signature: a query that loads a list, then a loop that runs another query per item (loading each post's author, each order's line items, each comment's vote count). Also check ORM lazy-loading, which hides the same pattern inside templates and serializers. For each one, rewrite using the right tool: a join or include/eager-load for related records, a single batched query with an IN clause grouped in code afterward, or a subquery/aggregation for counts. Verify the fix by counting queries: enable query logging (or my ORM's query counter), load the affected page, and confirm the count is flat regardless of how many items render (1 to 3 queries, not 1 + N). Do not denormalize or restructure the schema to fix N+1s; query shape is the fix. Do not break pagination on the affected endpoints. Deliver: each N+1 found with file and line, the rewrite applied, and the before/after query counts for a page with 50 items. Rank them by how often the endpoint is hit so I know which fixes mattered most.

What This Does / How This Helps

Finds the loops that fire a query per item and rewrites them as joins and batched lookups, with query counts proving the fix. N+1 is the most common reason vibe-coded apps get slow. A page rendering 50 comments fires 51 queries: one for the list, one per comment for the author. It works fine with five comments in dev, so it ships, and every page load hammers the database harder as content grows. The verification is objective: query logging on, load the page with 50 items, and the count stays flat instead of scaling with the list.

Want to skip doing this by hand?

Fortivibe audits your app for all of the areas these prompts cover (and more).

See What We Check

Related Prompts