Tag: databases

  • Stop Debugging Query Performance Manually: Find N+1s with Claude

    Stop Debugging Query Performance Manually: Find N+1s with Claude

    Your app is slow. You profile it. Nine times out of ten, the culprit is an N+1 query: one SELECT fetches a user, then the code loops and does another SELECT for each user’s posts, each post’s comments, each comment’s author. One request becomes 1,000 database hits.

    You can hunt these manually, but it’s tedious: dig through logs, grep for repeated query patterns, trace the code path, refactor. Hours. Claude finds them in minutes.

    Step 1: Enable query logging. Most ORMs have a debug mode. Rails: add set_property(Arel::Visitors::ToSql, 'log_sql', true) to your config. Node Prisma: use `logLevel: “query”` in your schema. Python Django: set DEBUG=True and read django.db.backends logs. Run your app under realistic load so the pattern shows up.

    Step 2: Load logs and code into Claude. Paste your query log and the controller/resolver that triggered it. Ask: Which queries repeat with different parameters?

    Step 3: Claude spots the pattern. It finds the SELECT that runs once per item in a loop. It traces back to your code: usually a loop over a list of items, with a separate query inside. N+1.

    Step 4: Claude proposes the fix. Eager load the associations (Rails: add `.includes(:posts)` to your find). Use a batch query operator. Denormalize. Move to a subquery. Claude will show the exact refactored code.

    Step 5: Verify the win. Run the profiler again. Watch the query count drop from 1,000 to 2. App goes from 8 seconds to 200ms.

    Common in Rails, Django, Node (Prisma, Sequelize, TypeORM), Java Hibernate. Works on any ORM that exposes query logs. The gotcha: enable logging BEFORE profiling, or you won’t see the pattern.

    ——

    Book your free AI clarity call, NOW!
    https://buff.ly/TpWy277

    ——

    Repost this. Thanks.