
Every Query Is Fast but the Page Is Slow: Spotting N+1 from the Database Side
- كاتب موثّق
محتويات المقال
The common misconception
log_min_duration_statement logs only statements that ran at least as long as the threshold, so a 0.05 ms query never appears. A list sorted by average duration puts the heaviest single statement on top. And each of those views is honest; it just answers a different question from "why is this page slow?".
What actually happens
Each statement is a round trip
What the database actually records
pg_stat_statements does the same by design: queries that differ only in their constants are combined into a single entry, with the constants shown as $1, and its calls column counts the executions.
The fingerprint is in the counts
Averages hide it, and fixing it makes the average look worse
Look at counts, not averages
-- "Which query is slow?" sorted by average durationSELECT TOP (10) qt.query_sql_text, rs.avg_duration / 1000.0 AS avg_msFROM sys.query_store_runtime_stats AS rsJOIN sys.query_store_plan AS p ON p.plan_id = rs.plan_idJOIN sys.query_store_query AS q ON q.query_id = p.query_idJOIN sys.query_store_query_text AS qt ON qt.query_text_id = q.query_text_idORDER BY rs.avg_duration DESC;-- Tested: the N+1 statements (0.02-0.05 ms) rank last-- How often, how much in total, how many rows each timeSELECT TOP (10) qt.query_sql_text, SUM(rs.count_executions) AS executions, SUM(rs.count_executions * rs.avg_duration) / 1000 AS total_ms, SUM(rs.count_executions * rs.avg_rowcount) / SUM(rs.count_executions) AS rows_per_callFROM sys.query_store_runtime_stats AS rsJOIN sys.query_store_plan AS p ON p.plan_id = rs.plan_idJOIN sys.query_store_query AS q ON q.query_id = p.query_idJOIN sys.query_store_query_text AS qt ON qt.query_text_id = q.query_text_idGROUP BY qt.query_sql_textORDER BY executions DESC;-- Tested: lines query 2,500 runs x 3 rows; orders query 50 runspg_stat_statements gives the same view. It needs shared_preload_libraries = 'pg_stat_statements' and CREATE EXTENSION pg_stat_statements; the columns below are from the PostgreSQL 18 docs, and the query wasn't run for this article:
SELECT calls, round(total_exec_time) AS total_ms, round(mean_exec_time::numeric, 3) AS mean_ms, rows / NULLIF(calls, 0) AS rows_per_call, queryFROM pg_stat_statementsORDER BY calls DESCLIMIT 10;How to apply it in your project
Sort by executions and total time Make the weekly check in Query Store or pg_stat_statementssort by execution count and total duration. Look for statements with tiny averages near the top.Match the counts For each suspect, find the statement whose count divides it cleanly, and check the rows per call. That pair is the loop and its parent. Fix it in the application Replace the loop with a join or a projection, or batch the ids into one query. For EF Core, the .NET path's article "Beyond Include: Fixing N+1 in EF Core With Projections and Split Queries" covers the code side. Verify with both numbers After the fix, the statement count per request should drop and the client-side latency should follow, even if the slowest average goes up.
Key takeaways
A fast query can still make a slow page: the cost of N+1 is round trips, which no per-query statistic includes. In the test, the page waited about 73 ms while the server executed about 3.5 ms of it. The database records an N+1 as one parameterized statement with a huge count and few rows per call, often an exact multiple of another statement's count. Sort by executions and total time; sorting by average duration ranks N+1 last and makes the fix look like a regression. If values are typed into the SQL text, group SQL Server's statistics by query_hash.
📚 المصادر
pg_stat_statements — PostgreSQL Documentation Monitor Performance by Using the Query Store — SQL Server, Microsoft Learn sys.dm_exec_query_stats — SQL Server, Microsoft Learn sys.query_store_runtime_stats — SQL Server, Microsoft Learn Error Reporting and Logging: log_min_duration_statement — PostgreSQL Documentation
التعليقات (0)