DEV Community

Cover image for Catch N+1 Queries Before They Catch You
zintrust Zin
zintrust Zin

Posted on Edited on

Catch N+1 Queries Before They Catch You

A common N+1 example: load 100 records, then run one more query per record to fetch a relation. One line of application code can result in 101 database queries.

It's the most common performance bug in ORM-based backends, and it's easy to miss because each query is fast on your laptop.

ZinTrust provides an N+1 detector in RequestProfiler. It analyzes SQL entries in QueryLogger; it does not automatically intercept every ORM/database query. Instrument the queries you want to inspect, then use eager loading with with() to avoid one relation query per record.

Three rules that keep N+1 out of your app:

  1. Load relations you'll use with with() in the same query chain.
  2. Capture and inspect query logs for new list endpoints before you merge.
  3. Add indexes on foreign keys and columns you filter on.

The detector is only as useful as the query log you give it. Make query capture part of profiling when you want it to flag repeated SQL.

Try it: npm install -g @zintrust/core && zin new my-app
https://zintrust.com/profiling

Top comments (0)