Full answer
A practical order of work:
- Find the query. Use slow query logs or
pg_stat_statementsto see the statement, how often it runs and its average time. Endpoint slowness is sometimes a hundred fast queries, not one slow one. - Reproduce with real parameters. A plan for
customer_id = 5can differ from one for a customer with a million orders. - Read the plan. Look for sequential scans on large tables, sorts spilling to disk, nested loops over many rows and big gaps between estimated and actual rows.
- Fix the cause. Typical fixes are a composite index matching
WHERE customer_id = ? ORDER BY placed_at DESC, keyset pagination instead of large OFFSETs, selecting fewer columns, or refreshing statistics with ANALYZE. - Verify. Rerun EXPLAIN ANALYZE, then watch the production metric after release.
Also check for lock waits, because a fast query blocked by a long transaction looks slow from the outside.
Key points
- Measure before changing anything
- Use real parameters when reading plans
- Compare estimated and actual rows
- Match indexes to filter plus sort
- Check for lock waits and N+1 patterns
Common mistakes
- Adding indexes at random
- Testing plans on a tiny development database
Follow-ups
- What does a large estimate error suggest?
- How does OFFSET pagination slow down?
Tips
- Give the steps in order