A query that used to be fast now takes seconds. How do you speed it up?
BackendMid-level
In shortMeasure it with EXPLAIN (ANALYZE, BUFFERS) on production-like data, find the costliest plan node, and fix the cause: a missing or mismatched index, a function on an indexed column, bad row estimates from stale statistics, OFFSET pagination, N+1 queries, or returning far more data than needed. Verify with the same plan and with pg_stat_statements.
Model answer
Measure: run EXPLAIN (ANALYZE, BUFFERS) with real parameters on production-sized data. Check pg_stat_statements too: a 5 ms query called 10,000 times per request is a bigger problem than one slow query.
Read the plan: find the node with the most time. Typical findings:
- Seq Scan with many “rows removed by filter”: a missing index, or an index the query can’t use.
- Sort (especially “external merge”): no index matching the
ORDER BY, or too littlework_mem. - Estimated vs actual rows off by orders of magnitude: stale or insufficient statistics; run
ANALYZE, raise statistics targets, add extended statistics. - Nested Loop over many rows: a join that needs an index on the inner side or a different join strategy.
Fix the cause:
- An index that matches the query: equality columns first, then sort or range; partial indexes for hot subsets;
INCLUDEfor index-only scans; expression indexes when the query uses an expression. - Rewrite index killers:
date(col) = x→ range oncol; leading%searches → full-text or trigram indexes; type mismatches. - Keyset pagination instead of large
OFFSETs; select only needed columns; fix N+1 with joins or batch fetching.
Verify: compare plans and timings before and after, watch write latency (indexes cost writes), and create indexes with CREATE INDEX CONCURRENTLY in production.
What they're looking for
A measurement-first approach, reading plans (scans, estimates vs actuals, sorts), index design rules (composite order, partial, covering, expression), common anti-patterns, statistics, and verification.
Common mistakes
- Adding indexes on every column.
- Testing on a tiny local database.
- Ignoring that the query may be fine but called thousands of times (N+1).
More backend questions
- What is the N+1 query problem, and how do you find and fix it?Mid-level
- What does Spring Boot's auto-configuration do, and how do you change what it set up?Mid-level
- How does a Spring backend authenticate requests from a mobile app, and how do you make sure users only see their own data?Mid-level
- Your Spring Boot service in Kubernetes keeps restarting with exit code 137. How do you investigate and fix it?Senior