n1scan
by alex00010
README.md
# n1scan
[](https://github.com/alex00010/n1scan/actions/workflows/ci.yml)
[](https://github.com/alex00010/n1scan/releases)
[](LICENSE)
[](https://github.com/alex00010/n1scan/labels/good%20first%20issue)
**Find N+1 queries by watching your app's PostgreSQL traffic (or the server logs you already have), prove which query caused each loop, and fail CI only when a new one appears. One binary, no code changes, any language or ORM.**
n1scan is a small local proxy. Point your app at it instead of at Postgres; it forwards every byte unchanged and tells you when the same query shape runs again and again with different values (the N+1 pattern), which query ran just before the loop, and, from a read-only `EXPLAIN`, which index would make it cheap. Query values never appear in its output unless you ask for them.

On a real app (the [Prisma example](examples/prisma-blog), PostgreSQL 18):
```text
$ n1scan run -- npm run demo
N+1 03:56:27 conn 1: same query 5+ times in 50.0ms
SELECT COUNT(*) AS "_count$_all" FROM (SELECT "public"."posts"."id" FROM "public"."posts" WHERE "public"."posts"."author_id" = $1 OFFSET $2) AS "sub"
after: SELECT "public"."authors"."id", "public"."authors"."name" FROM "public"."authors" WHERE ?=? ORDER BY "public"."authors"."id" ASC LIMIT $1 OFFSET $2
parent proven: 5/5 values of $1 came from its column "id", in row order
values: 5 distinct so far (hidden; --show-values prints them)
index: CREATE INDEX CONCURRENTLY ON public.posts (author_id);
sequential scan on public.posts (~200000 rows) filtering on author_id, run once per repetition; the index also adds a little work to every write on the table
slow: 50 authors in 738 ms
n1scan summary: 51 queries on 1 connection in 2.40s
1. N+1 50 executions in 1 burst(s), largest 50, 412.6ms spent
select count(*) as "_count$_all" from (select "public"."posts"."id" from "public"."posts" where "public"."posts"."author_id" = ? offset ?) as "sub"
after: SELECT "public"."authors"."id", "public"."authors"."name" FROM "public"."authors" WHERE ?=? ORDER BY "public"."authors"."id" ASC LIMIT $1 OFFSET $2
parent proven: 50/50 values of $1 came from its column "id", in row order
index: CREATE INDEX CONCURRENTLY ON public.posts (author_id);
```
`after:` is the "1" of the N+1: the query whose rows your code iterates over. n1scan keeps salted hashes of the first rows each query returns and checks whether the loop's parameters came out of them, so when it can, it proves the link instead of guessing: `parent proven: 50/50 values of $1 came from its column "id", in row order`. That also works when the parent ran on another connection of a pool.
The loop is a `prisma.post.count()` per author that looks harmless in code. The fixed version (`include: { _count: … }`) is one query, and `n1scan diff` confirms it:
```text
$ n1scan run --report before.json -- npm run demo
$ n1scan run --report after.json -- npm run demo:fast
$ n1scan diff --allow-different-command before.json after.json
n1scan diff: 0 new, 0 worse, 1 fixed, 0 unchanged; queries 51 -> 1
FIXED N+1 50 -> 0 executions select count(*) as "_count$_all" from (select ...
```
## Why
N+1 queries are individually fast, so slow-query logs and `auto_explain` never show them on their own (with every statement logged, `n1scan logs` finds them there: see [below](#in-staging-or-production-read-the-server-logs)). ORM-specific detectors exist (Bullet for Rails, nplusone for Django, debug toolbars), but each one covers one framework and runs inside your process. APM tools catch them in production, after your users did.
n1scan sits on the wire, so it works the same for Prisma, Drizzle, SQLAlchemy, Django, pgx, psycopg, raw SQL, or anything else that speaks the PostgreSQL protocol. In CI it compares each run with a baseline, so a project that already has N+1 queries can adopt it today and only fail on the ones a pull request adds.
## Try it in ten seconds
```sh
npx n1scan demo # or: uvx n1scan demo, or n1scan demo with a downloaded binary
```
A small app with an N+1 runs against a simulated PostgreSQL inside the binary (nothing to install, no network): you see the finding, the proven parent query, then the fixed version and the before/after numbers.
## Install
- Download a binary for Linux, macOS or Windows from the [Releases page](https://github.com/alex00010/n1scan/releases).
- `npx n1scan` or `uvx n1scan` (thin launchers that download the release binary and check its SHA-256).
- With Go 1.25+: `go install github.com/alex00010/n1scan/cmd/n1scan@latest`
## Use
### Wrap a command (easiest)
```sh
export DATABASE_URL=postgres://me:secret@localhost:5432/app
n1scan run -- npm test # or: pytest, go test ./..., rails test, ...
```
`run` starts the proxy, rewrites `$DATABASE_URL` for the child process so it connects through n1scan, and prints a report when the command exits. Use `--env NAME` if your app reads another variable. The same connection string is used for the read-only `EXPLAIN` behind index suggestions. If the command never connects through the proxy, n1scan says so instead of reporting a clean run.
### In CI: the GitHub Action
```yaml
name: n1scan
on: [pull_request]
permissions:
contents: read
pull-requests: write # for the PR comment; without it the report goes to the job summary
jobs:
n1scan:
runs-on: ubuntu-latest
services:
postgres:
image: postgres:18
env:
POSTGRES_PASSWORD: postgres
ports: ["5432:5432"]
options: >-
--health-cmd pg_isready --health-interval 2s --health-timeout 5s --health-retries 20
env:
DATABASE_URL: postgres://postgres:postgres@127.0.0.1:5432/app?sslmode=disable
steps:
- uses: actions/checkout@v4
- run: npm ci
- uses: alex00010/n1scan@v0.6.0
with:
command: npm test
baseline: n1scan.baseline.json
```
The action downloads the release binary for the runner (Linux, macOS or Windows), checks it against the release's `checksums.txt`, runs the command through n1scan, writes the report to the job summary and keeps one comment on the pull request up to date. On the first run the baseline file does not exist, so it is written from that run: commit it, and from then on only findings that are not in it fail the job. This repository runs the action on its own pull requests ([workflow](.github/workflows/n1scan.yml)), so any open pull request shows the comment it leaves. Inputs: `command`, `baseline`, `env`, `fail-on`, `fail-kinds`, `args`, `comment`, `version`, `binary`.
### In CI: any other system
```sh
# fail on any N+1
n1scan run --ci -- npm test
# accept today's findings once (commit the file)
n1scan run --ci --baseline n1scan.baseline.json --update-baseline -- npm test
# from then on, fail only on new ones; n1scan.md is ready for a PR comment
n1scan run --ci --baseline n1scan.baseline.json --report n1scan.md -- npm test
```
Exit status: `0` clean; `1` an N+1 was found (with `--baseline`, one that is not in the baseline); `2` bad usage, or with `--ci` the command never connected through n1scan, so nothing was measured. If the command itself fails, its own exit status is returned unchanged.
Findings have a stable `id` derived from the normalised query, so a baseline survives reruns, data changes and refactors that do not change the SQL. `--fail-on worse` also fails when a known N+1's largest burst grows by more than `--allow-growth` percent (default 20). Only `n+1` findings fail by default; `--fail-kinds n+1,batchable` adds write loops.
### Query budgets a coding agent cannot quietly raise
Query-count assertions in tests (`assertNumQueries(4)`) live next to the code, so a change, or a coding agent trying to get CI green, can bump the number in the same commit. Put the limits in `.n1scan.yaml` at the repository root instead, and protect that file with CODEOWNERS:
```yaml
# .n1scan.yaml
mode: fail # or warn
budgets:
- name: whole test suite
max_queries: 2000
max_unique_queries: 300
max_n1: 0
- route: GET /api/orders # needs sqlcommenter / query-log tags
max_queries: 40
max_burst: 3
```
```text
# .github/CODEOWNERS
/.n1scan.yaml @your-team
/n1scan.baseline.json @your-team
```
n1scan reads `.n1scan.yaml` when it exists (or `--config FILE`), reports every limit in the summary and the PR comment, and with `--ci` fails when one is exceeded. Unknown keys are an error, so a typo never disables a budget. A useful pattern: seed 50-100 rows in an integration test and set a flat limit, which catches anything that grows with the number of rows without breaking on one extra constant query.
### In staging or production: read the server logs
The proxy is for development and CI. Where you can't put one in front of the database, `n1scan logs` finds the same loops in PostgreSQL's own log, with no proxy and no change to the app:
```sh
n1scan logs /var/log/postgresql/postgresql-18-main.log
n1scan logs --format csv --db shop postgresql-*.csv.gz # csvlog, jsonlog and .gz work as they are
kubectl logs db-0 | n1scan logs --ci --report n1.md # stdin; --baseline and budgets work here too
```
Each query of a loop is fast, which is why the slow-query log never catches it, so the server has to log every statement for a while: `log_min_duration_statement = 0` (or `log_statement = 'all'`), per database if you like (`ALTER DATABASE shop SET log_min_duration_statement = 0`). Bind parameters are logged by default and tell a loop over different ids from the same query repeated. Statements are grouped per session (`%p` or `%c` in `log_line_prefix`; the default `'%m [%p] '` works, `%t` works with coarser grouping), and `--dsn` adds index suggestions from a read-only `EXPLAIN`.
From logs n1scan shows the statement each session ran before the loop, but cannot prove it is the parent: the proof needs the rows, which only the proxy sees. Tested against the real logs of all 13 clients of the matrix, in stderr, csvlog and jsonlog, with both settings ([results](clients/MATRIX-RESULTS-LOGS.md)).
### Verify a fix
```sh
n1scan run --report before.json -- npm test
# change the code
n1scan run --report after.json -- npm test
n1scan diff before.json after.json # --format md or json for agents and PR comments
```
`diff` exits `0` when nothing new appeared, `1` when the change added a finding, and `2` when the comparison proves nothing: the second run captured no queries, the commands differ, or the command failed.
### With a coding agent
n1scan measures; your agent writes the fix. Three ways to wire it in:
- **Claude Code plugin** (skill + MCP server):
```sh
claude plugin marketplace add alex00010/n1scan
claude plugin install n1scan@n1scan
```
- **MCP server** for any MCP client: `n1scan mcp` serves three tools over stdio, `n1scan_scan` (run a command through n1scan, get the findings, the proven parent and a report path), `n1scan_logs` (the same from a PostgreSQL log file) and `n1scan_diff` (compare two reports, say whether the fix is verified). For Claude Code: `claude mcp add --transport stdio n1scan -- npx -y n1scan mcp`.
- **Skill only**: copy [`skills/n1scan`](skills/n1scan/SKILL.md) into `.claude/skills/` or `.agents/skills/` (read by Claude Code, Codex, Cursor and others that support `SKILL.md`).
The skill gives the agent one protocol: measure, fix the loop in the ORM, measure again with the same command, and report "verified" only when `diff` says so; never raise thresholds, edit the baseline or touch `.n1scan.yaml` to get a green check.
### Point to the request and the line of code
The wire does not know which line of your code sent a query. If your app adds a [sqlcommenter](https://google.github.io/sqlcommenter/) comment (`/*route='%2Fapi%2Forders',traceparent='00-…'*/`) or a Rails query-log comment (`/*application:Blog,controller:posts,action:index*/`, built into Rails 7 with `config.active_record.query_log_tags_enabled = true`), n1scan reads it:
- findings say where they happened: `in GET /api/orders (app/services/orders.rb:42)`, from `route`/`http.method`, `controller`/`action`, `job` or `n1scan_scope`, and `source_location`, `file`/`line` or the OpenTelemetry `code.*` keys;
- with a W3C `traceparent`, repetitions are grouped per request instead of per connection, so a loop that one request spreads over a pool is one burst, and the same query from many independent requests is never mistaken for one.
Without tags, n1scan falls back to the connection and to lineage.
### Live screen

```sh
n1scan --dsn postgres://me:secret@localhost:5432/app
# then point the app at 127.0.0.1:5433 with sslmode=disable
```
The live screen shows findings (worst first), the selected finding's index suggestion, and a stream of recent queries with latency bars. `q` quits, `p` pauses, `c` clears. Without a terminal (or with `--log`) it prints plain lines instead.
### What it reports
| Kind | Meaning | Fails `--ci` by default |
|---|---|---|
| `n+1` | one read query shape, run `--threshold` times in a burst with different values | yes |
| `batchable` | one INSERT/UPDATE/DELETE per row in a loop: use a multi-row INSERT, `unnest` or `COPY` | no |
| `duplicate` | the same query with the same values, again and again (only with `--duplicates` or `--all`) | no |
| `parallel` | the same lookup from independent requests overlapping on several connections, with no parent query its values came from (only with `--all`) | no |
| `pagination` | each execution's value came from the previous execution's rows, as in keyset pagination (only with `--all`) | no |
### The fix, in your ORM's words
Each N+1 in the summary, the JSON report, the PR comment and the MCP tools comes with a fix. When the SQL shows which ORM wrote it, the fix uses that ORM's API:
```text
fix (looks like Prisma): load the relation with the parent query, e.g. findMany({ include: { posts: true } }) (use your relation's name), or run one findMany({ where: { author_id: { in: ids } } }) with the ids from the authors query
```
Recognised today, each checked against real SQL from the [client matrix](clients/MATRIX-RESULTS.md): Prisma, Django, SQLAlchemy and Drizzle. Other code gets the batched SQL form (`WHERE author_id = ANY($1)`). Names are taken from the SQL, so the relation name may differ in your schema. Each ORM is one YAML file in [`internal/hints/rules`](internal/hints/rules); adding yours is a small pull request (see [CONTRIBUTING.md](CONTRIBUTING.md#add-your-orm)).
### Detection quality
[`eval/`](eval/RESULTS.md) holds 20 query patterns with a known answer (classic loops, nested and pooled loops, paced and slow loops, batched fixes, independent parallel requests, pagination, test transactions, health checks, traced requests) and runs them through n1scan against PostgreSQL in CI. Current result: precision 1.00, recall 1.00, parent proven in 7 of 7 loops that have one. The scenarios were written by the project, so treat this as a regression gate rather than an independent benchmark; a false positive or a miss you hit is welcome as a new scenario.
### Options
| Flag | Default | Meaning |
|---|---|---|
| `--listen` | `127.0.0.1:5433` | where the proxy listens (loopback only unless `--allow-remote`) |
| `--upstream` | from `--dsn` | the real server, `host:port` |
| `--dsn` | | connection string of the real server; enables index suggestions |
| `--upstream-ssl` | from `--dsn` | `disable`, `prefer`, `require`, `verify-full` |
| `--threshold` | `5` | repetitions of one query shape that count as N+1 |
| `--gap` | `200ms` | longest pause between repetitions in one burst |
| `--scope` | `conn` | group per connection, or `global` (catches N+1 spread over a pool) |
| `--duplicates` | off | also report identical queries repeated with identical values |
| `--all` | off | also report duplicate, parallel and pagination patterns (they never fail `--ci`) |
| `--ignore` | | regexp on the normalised query; repeatable |
| `--min-rows` | `1000` | only suggest indexes on tables at least this big |
| `--no-explain` | off | never run EXPLAIN |
| `--show-values` | off | print literal values and query parameters (hidden by default) |
| `--json` / `--json-queries` | off | JSON lines on stdout (findings, suggestions, summary; optionally every query) |
| `--report FILE` | | write a report when done: `.md` gives Markdown for PR comments, anything else the JSON document (`n1scan/report/v1`); repeatable |
| `--ci` | off | exit 1 when an N+1 was found, 2 when nothing was measured |
| `--baseline FILE` | | compare with an earlier report; with `--ci` only new findings fail |
| `--update-baseline` | off | write `--baseline` from this run instead of comparing |
| `--fail-on` | `new` | with a baseline: `new`, `worse` (new or grown) or `any` |
| `--fail-kinds` | `n+1` | kinds that can fail: `n+1`, `batchable`, `duplicate`, `parallel`, `pagination` |
| `--allow-growth` | `20` | percent a known finding's largest burst may grow before it is `worse` |
| `--config FILE` | `.n1scan.yaml` if present | query budgets (see above) |
## How it works
1. **Proxy.** n1scan answers the client's SSL request with "no", so local clients talk plain text to it, and opens its own connection to the server (with TLS if the server wants it). Every message is forwarded unchanged; decoding happens on a copy. If decoding ever fails, the connection falls back to raw byte copying: n1scan should never be the reason a query fails.
2. **Protocol tracking.** Simple queries (`Q`, split at top-level semicolons) and the extended protocol (`Parse`/`Bind`/`Execute`/`Sync`, including pipelining and errors in the middle of a pipeline) are matched with the server's `CommandComplete`/`ErrorResponse`/`ReadyForQuery` to get each statement's text, parameters and duration.
3. **Fingerprints.** Literals and `$n` placeholders become `?`, `IN (…)` and `VALUES` lists collapse, comments (including sqlcommenter tags) and whitespace disappear. `WHERE id = 1` and `WHERE id = -42` get the same fingerprint. The format is versioned (`fingerprint_version` in reports) and frozen: a change that alters fingerprints bumps the version, and `diff` refuses to compare across versions instead of reporting everything as new.
4. **Bursts.** When one fingerprint runs `--threshold` times on the same connection with no pause longer than `--gap`, and with more than one distinct set of values, it is an N+1 (or `batchable` for writes). A burst stays open while its connection is still running a statement, so loops of slow queries are caught too; it also survives pauses of up to 10 s while each new value keeps coming from the same parent column, so loops that do work between queries are caught. A `ROLLBACK` ends it, so lookups in separate tests that each roll back are not merged into one.
5. **Lineage.** The first 500 rows of every result are hashed (salted, in memory, values up to 64 bytes; text and binary forms compare equal). A loop whose values are found in one column of an earlier result, on its connection or on any other, gets that query as its proven parent. A burst with no such parent that overlapped the same query on other connections is independent traffic (`parallel`), not an N+1. Without lineage, `after:` falls back to the statement that ran on the connection right before the burst, skipping sibling loop bodies (posts and comments fetched per author), and no "parent proven" line is printed.
6. **Suggestions.** n1scan opens a separate connection, starts a `READ ONLY` transaction with a 2 s `statement_timeout`, and runs `EXPLAIN (FORMAT JSON, VERBOSE)` (parameterised queries: `GENERIC_PLAN` on PostgreSQL 16+, `PREPARE` with a forced generic plan on 12-15; never `ANALYZE`, so the query is not executed). A sequential scan with an equality/range filter, or a `lower(col)`/`upper(col)` filter, on a big table without a matching index becomes a `CREATE INDEX CONCURRENTLY` suggestion.
Overhead, measured with `pgbench -S` on a Windows laptop with server and proxy on the same machine ([details](bench/overhead/README.md)): +35 to +54 µs per query for one client, zero failed transactions in simple, extended and prepared modes; a query over a real network takes 1-5 ms. With 16 busy clients latency through the proxy roughly doubles (as it did in v0.1.0). A profile shows why: a build that forwards bytes with no analysis at all costs the same, more than half the CPU goes to socket writes, and n1scan's own analysis is about 5%. The proxy belongs in development and CI, not in front of production traffic; for production, [read the logs](#in-staging-or-production-read-the-server-logs) instead.
## Tested clients
Every client runs an N+1 loop and a fixed version, straight to Postgres and through `n1scan run --json`; results must be identical, the loop must be reported with the right index, and the fixed version must not be reported. Both with plain-text and TLS upstream connections ([results](clients/MATRIX-RESULTS.md), [TLS](clients/MATRIX-RESULTS-TLS.md)):
| Go | Node | Python | Other |
|---|---|---|---|
| pgx, database/sql + pgx, lib/pq | node-postgres, postgres.js, Prisma 6 (Rust engine), Prisma 7 (adapter-pg), Drizzle | psycopg 3, SQLAlchemy 2, asyncpg, Django | psql (libpq) |
Run it yourself: `node clients/matrix.mjs` (see [CONTRIBUTING.md](CONTRIBUTING.md)).
## Compared with
| | Works for any stack | No code changes | Finds N+1 | Suggests index | CI baseline / diff | Windows |
|---|---|---|---|---|---|---|
| **n1scan** | yes (PostgreSQL wire) | yes | yes, with the parent query | yes | yes, plus a GitHub Action | yes |
| [sql-tap](https://github.com/proto-tap/sql-tap) | yes (PostgreSQL, MySQL, TiDB wire) | yes | yes | no | `diff` of reports | no |
| ORM-specific detectors (Bullet, nplusone, debug toolbars) | one framework each | add a library | yes | no | varies | yes |
| `pg_stat_statements` | yes | server extension | shows totals, not bursts | no | no | yes |
| `auto_explain` / slow-query log | yes | server config | no (each query is fast) | no | no | yes |
| APM N+1 detection | per-language SDK | add an SDK | yes | varies | no | yes |
sql-tap is the closest tool: also a wire proxy, with MySQL and TiDB support and a live web UI, which n1scan does not have. A side-by-side run on nine query patterns, with the script and the cases where each tool wins or fails, is in [bench/vs-sql-tap](bench/vs-sql-tap/README.md).
## Limitations
- PostgreSQL only (MySQL is a wanted contribution).
- `n1scan logs` needs every statement in the log for the period you analyse (`log_min_duration_statement = 0` costs log volume on a busy server), groups by session rather than by request, and cannot prove the parent query (no rows in a log).
- The app must connect to n1scan without TLS (`sslmode=disable`; `run` does this for you). The leg to the server can use TLS, but SCRAM channel binding (`SCRAM-SHA-256-PLUS`) cannot work across a proxy, so n1scan removes it from the server's offer; a client configured with `channel_binding=require` will refuse to connect.
- Unix-socket connections are not supported; use TCP.
- Index suggestions cover sequential scans filtered on columns (equality columns first, then ranges) and on `lower(col)` / `upper(col)`; other expressions are skipped. They are proposals: nothing is created, and the cost before/after is not measured.
- Parameterised queries are explained with `EXPLAIN (GENERIC_PLAN)` on PostgreSQL 16+, and with `PREPARE` plus a forced generic plan on PostgreSQL 12-15.
- Loops spread over many pooled connections are grouped per connection by default; use `--scope global` if your app's loop hops between connections.
- Without lineage (the parent's rows never crossed the wire, for example ids from a cache), detection falls back to timing and repetition: a loop that pauses longer than `--gap` is then missed, and a loop spread over a pool in parallel is reported as `parallel`.
- Lineage compares values, not meaning: a loop over small consecutive integers can match an unrelated result that holds the same integers.
- Redaction hides string, number and dollar-quoted literals, bound parameters and quoted parts of server errors. Identifiers and comments (such as sqlcommenter tags) are kept.
## Security
n1scan sees every query and parameter, so by default it refuses to listen on anything but loopback, and it replaces literal values and bound parameters with `?` before anything is printed or written to a report (`--show-values` turns that off for local debugging). `EXPLAIN` runs in a read-only transaction with a timeout and only for single `SELECT`/`WITH` statements without data-modifying parts. Nothing is sent anywhere; there is no telemetry.
## Contributing
n1scan is young and contributions are very welcome: pick a [good first issue](https://github.com/alex00010/n1scan/labels/good%20first%20issue), add your ORM or framework to the [client matrix](clients/MATRIX-RESULTS.md), or tell us which client it misses in [Discussions](https://github.com/alex00010/n1scan/discussions). `docker compose up` starts the Postgres the tests expect; see [CONTRIBUTING.md](CONTRIBUTING.md) for the rest. Issues and pull requests get an answer within two days.
## License
MIT
This server cannot be deployed
Maintenance
ActivityMaintained
ResponsivenessNo recent community issues