A list endpoint loads 50 orders. One query fetches the page. Then, to render each order's owner, the code fires one more lookup per row — fifty statements that read SELECT id, username, avatar FROM sys_user WHERE id = ? and differ only in the bound id. One screen for the user, fifty-one queries for the database.
Locally this is invisible: the test table has six rows, every query takes about a millisecond, and the log reads as noise. In staging, where the data starts to look real, response time grows linearly with row count, and by the time somebody goes looking, the log is a few hundred lines of statements that all look alike.
The trigger is almost always a loop touching a lazy relation — collection nesting in a MyBatis mapper, or a JPA @OneToMany that loads on first access. Each line involved was individually reasonable; the bug exists only in their sum. That is why I stopped hunting it by eye and wrote the search down as a rule instead.
Why the log hides it
Hunting an N+1 in a log is three jobs: remember each statement's shape while ignoring its parameters, decide which statements belong to the same request, count. Done by eye, each job fails in a predictable way.
Shape is the fragile one. MyBatis logs placeholders and values on separate lines — Preparing: SELECT ... WHERE id = ?, then Parameters: 2(Long) — so the shape sits one line above the data, and my brain is the tool doing parameter normalization. Fine with three parameters. With ten, I start merging statements that differ and splitting ones that are identical.
Concurrency interleaves everything. SQL from several requests arrives in time order, so the fifty statements of one request are not adjacent; heartbeats and transaction logs sit between them. Judging "same block" by proximity is guesswork.
And the threshold is undefined. Is three repeats an N+1? A batch export that legitimately loads twenty ids in one pass? Without a rule the answer is a feeling, and feelings produce both misses and false alarms — usually in the same afternoon.
The rule, written mechanically
All three jobs can be written strictly enough for a machine to execute. The result is one sentence:
The same statement shape — identical text once
?placeholders and parameters are stripped — occurring more than 5 times on the same thread within a sliding window (60 seconds by default) is a suspected N+1.
Every qualifier in that sentence kills a specific false alarm:
- Same shape means comparison by parameterized template, not by characters.
WHERE id = 1andWHERE id = 2are one template; character-level comparison counts them as two separate statements and the pattern never reaches the threshold. - Same thread is deliberately tight. Ten users each running one lookup is normal traffic; accumulate across threads and you flag all of it. Bucketing by thread is what isolates the "queried in a loop" pattern from ordinary concurrency.
- Sliding window, not a daily total. Queries that merely share a shape hours apart are not one incident; a whole-day counter turns scattered legitimate traffic into a cold case.
- Five is the action line; lower repetition gets lighter treatment. It should be tunable, because tolerance for repetition differs by business — a report job and an OLTP endpoint do not have the same bar.
Counting it with a dozen lines of Python
With nothing but a log file, the core of the rule fits in a short script. MyBatis Preparing: lines are already parameterized templates — the values went to the Parameters: line — so counting those lines by shape and thread does most of the work:
import re, collections shape = re.compile(r"==> Preparing: (.+)") # template lines only thread = re.compile(r"\[(http-nio-\d+-exec-\d+)\]") # tomcat worker thread counts = collections.Counter() for line in open("spring.log", encoding="utf-8"): m = shape.search(line) if m: t = thread.search(line) counts[(m.group(1), t.group(1) if t else "?")] += 1 for (sql, th), n in counts.most_common(): if n >= 5: print(f"{n:4d} [{th}] {sql[:90]}") Run against the staging log from the opening scene, it prints the diagnosis and nothing else:
50 [http-nio-8080-exec-3] SELECT id, username, avatar FROM sys_user WHERE id = ? The simplification is the missing time window: grouping by thread already blocks most cross-request false positives, and a same-thread, same-template burst is an N+1 in practice. When I want the full rule, I bucket the counts by minute before applying the threshold. Either way the core action is unchanged — count how many times the same shape appears.
Letting a panel do the counting
The script is fine for a single investigation. The rule earns its keep when the counting runs continuously while the app is up, and every part of how my daily SQL log panel does it maps onto a clause of the rule.
The panel aggregates entries by parameterized template. At 3 occurrences an amber ×N badge appears on the group — repetition exists here. At 5 same-template occurrences on one thread inside the 60-second sliding window, the badge turns red: suspected N+1. The two levels stay separate on purpose. Most amber groups die as legitimate batching, and I do not want every repetition shouting.
Clicking a red badge collapses the list into that group, with the total count, the first and last timestamps, and the threads involved — stated explicitly when the group spreads across several threads, because that usually means the pattern is not the loop I assumed. Each entry carries real parameters, duration, affected rows, and the source location that issued the query; clicking that lands on the Java line.
Two questions about this setup keep coming up. Does turning off SQL deduplication break the detection? No — dedup only controls whether the list folds repeated rows; counting and judgment are decoupled from it. That decoupling was added deliberately after the two were once coupled and it bit me. Do errored statements and ShardingSphere-rewritten entries count? Both count. The N+1 often hides inside exactly the round of queries that is failing.
After you find it
The fixes are textbook; the hard part was arriving at a specific line. With the group open, the choice is among three:
- Join instead. Fetch the related fields with the page in one statement. The statement gets wider and row expansion needs handling, but the round trips drop to one.
- Batch the lookups. Collapse per-row
getByIdcalls into oneIN (id1, id2, ...). In MyBatis-Plus that isselectBatchIds; in JPA it is@BatchSizeor an IN fetch hint. - Change the fetch strategy. For one-to-many relations,
FETCH JOINor a subselect load turns per-row fetching into one bulk fetch.
Then rerun the same scenario. This is the quiet benefit of rendering the judgment as a badge: the fix is verified by the badge not coming back, rather than by eyeball-diffing two log files. When the orders endpoint from the opening got fixed, the red badge showed on the before-run and never on the after-run, and that contrast settled the code review faster than any explanation would have.
Where the rule stops
Stated plainly, so nobody discovers the edges in production: legitimate cross-thread concurrency does not count — that is a design choice, not a miss, and it is what keeps the false-positive rate near zero. The 60-second window and the threshold of 5 are defaults; both are adjustable, and the panel caps the suspicion counters so a log left open for days does not grow without bound. Detection is not optimization either: once the badge points at a loop, choosing among JOIN, batch and fetch strategy still means reading the execution plan.
If what you have right now is one log file, strip the parameters, group by shape and thread, count — any script will do. The core of N+1 detection has always been a single action: count how many times the same-shaped SQL appears. Tooling only changes when that action runs — from once per investigation to once per occurrence, automatically.
I maintain MyBatis SQL Visualizer, the IDE plugin that does this counting automatically; the rule above doesn't depend on it.


