How do you debug a slow query? (EXPLAIN and N+1)
A query or endpoint is slow. How do you find and fix the problem? What is the N+1 query problem?
TL;DR
Measure first. Find the slow queries (slow query log, pg_stat_statements, APM traces), then run EXPLAIN ANALYZE to see the actual plan: look for sequential scans on big tables, row estimates far from actual rows, expensive sorts, and nested loops over many rows. Common fixes are adding the right index, rewriting the query, selecting fewer columns, and paginating. At the application level the classic problem is N+1: one query loads N parents, then the ORM runs one more query per parent to load its children. Fix it with a join or a batched WHERE id IN (...) (eager loading).
Key points
- In
EXPLAIN ANALYZE, compare estimated vs actual rows. Big gaps mean stale statistics; runANALYZE. Seq Scanon a large table with a selective filter usually means a missing or unusable index.- Avoid
SELECT *; fetch only needed columns, ideally covered by an index. - Spot N+1 by counting queries per request (ORM query logs, APM traces showing many identical queries).
- Beyond the query: connection pool exhaustion, lock waits, and missing caching.
- Fix, then measure again. Don't guess.
Example
// N+1: 1 query for posts + 1 query per post for its author
const posts = await db.post.findMany({ take: 50 })
for (const post of posts) {
post.author = await db.user.findUnique({ where: { id: post.authorId } })
}
// Fixed: 1 query with a join (or 2 queries with WHERE id IN (...))
const posts = await db.post.findMany({ take: 50, include: { author: true } })EXPLAIN ANALYZE SELECT * FROM orders WHERE customer_id = 42;
-- Seq Scan on orders (actual rows=12, rows removed by filter=4,999,988)
-- → add an index on customer_idCommon follow-ups
- How does GraphQL solve N+1? DataLoader batches all child lookups in one tick into a single
INquery. - When would you denormalize or cache instead? When the query is already well indexed but runs constantly and the data changes rarely.
What interviewers look for
Tip
A methodical process: measure, EXPLAIN ANALYZE, fix the biggest cost, verify. Plus a clear N+1 explanation with the fix.
- Red flag: jumping straight to "add a cache" or "add more servers" without looking at the plan.