Query Optimization
- Read an
EXPLAIN (ANALYZE, BUFFERS)plan and find the node that actually costs time - Explain when the planner chooses sequential, index, index-only and bitmap scans, and nested loop, hash or merge joins
- Fix bad plans caused by statistics: stale, too coarse, or blind to correlated columns
- Remove N+1 query patterns and replace
OFFSETpagination with keyset pagination - Size application connection pools and PgBouncer for a fleet of services
- Run a slow-query investigation from
pg_stat_statementsto verified fix
TL;DR
- The planner is cost-based: it estimates row counts from statistics and picks the cheapest plan. Most bad plans are bad estimates, so compare
rows=(estimated) withactual rowsfirst. EXPLAIN ANALYZEruns the query. Wrap DML inBEGIN … ROLLBACK. AddBUFFERSto see pages read from cache versus disk.- Nested loop: small outer input with an indexed inner side. Hash join: larger unsorted inputs joined on equality. Merge join: both inputs already sorted. MySQL has nested loop and (8.0.18+) hash join, no merge join.
- N+1 turns one page load into hundreds of round trips. Batch with
WHERE id = ANY($1)or a join. OFFSETpagination costs O(offset); keyset (WHERE (created_at, id) < ($1, $2)) costs O(page size) at any depth.- Postgres uses a process per connection: pool in the app, and add PgBouncer when pods × pool size exceeds what the server should hold.
- Workflow: rank by total time in
pg_stat_statements→EXPLAIN (ANALYZE, BUFFERS)→ fix estimate, index or query shape → verify on production-like data → guard against regression.
Why it matters
Query performance is capacity. A checkout query that reads 50,000 buffers instead of 50 does not just make one user wait: it evicts useful pages from cache, holds a connection longer, and multiplies across every request during a sale. Database CPU is usually the most expensive and least elastic resource in an e-commerce or banking platform; a replica takes minutes to hours to add, and the primary cannot be scaled horizontally at all without sharding. Finding and fixing the top ten queries by total time is often worth more than any infrastructure change.
Core concepts
How the planner decides
Cost is in arbitrary units based on settings such as seq_page_cost = 1, random_page_cost = 4, cpu_tuple_cost = 0.01 (Postgres defaults). On SSDs many teams lower random_page_cost to about 1.1–2, which makes index scans look cheaper; measure before and after. For joins of many tables, Postgres switches from exhaustive search to a genetic optimizer (GEQO) at geqo_threshold (12 relations by default), and join_collapse_limit (8) limits reordering of explicit joins.
Reading EXPLAIN ANALYZE
An illustrative plan for "a merchant's recent failed payments":
Limit (cost=0.56..152.31 rows=50 width=24) (actual time=0.041..0.212 rows=50 loops=1)
Buffers: shared hit=54
-> Index Scan using payment_merchant_status_created_idx on payment
(cost=0.56..2981.10 rows=982 width=24) (actual time=0.040..0.205 rows=50 loops=1)
Index Cond: ((merchant_id = 42) AND (status = 'FAILED'::text)
AND (created_at >= (now() - '7 days'::interval)))
Buffers: shared hit=54
Planning Time: 0.180 ms
Execution Time: 0.240 ms
How to read it:
cost=startup..totalin planner units;rowsis the estimate;widththe average row size in bytes.actual time=first..lastin milliseconds per loop; multiply byloopsfor the node's total.- Estimated vs actual rows: within a factor of a few is fine; off by 100× or more is the root cause of most bad plans.
Buffers: shared hit= pages found in shared buffers,read= pages fetched from the OS (page cache or disk).dirtied/writtenindicate writes. Postgres 18 includes buffer statistics inEXPLAIN ANALYZEby default; earlier versions needBUFFERSexplicitly.- Red-flag lines:
Rows Removed by Filter: 1200000(an index is missing or not selective),Sort Method: external merge Disk: …(sort spilled;work_memtoo small for this query, or sort can be avoided with an index),Hash … Batches: 16(hash join spilled),Heap Fetches: …on an Index Only Scan (visibility map is stale; vacuum),loops=48210on an inner node (a nested loop driven by a misestimate).
A classic misestimate:
Nested Loop (cost=0.43..120.55 rows=12 width=40) (actual time=0.05..2301.7 rows=48210 loops=1)
-> Seq Scan on orders o (cost=0.00..95.10 rows=12 width=24) (actual time=0.03..812.4 rows=48210 loops=1)
Filter: ((status = 'PAID'::text) AND (city = 'Hanoi'::text))
Rows Removed by Filter: 2951790
-> Index Scan using customer_pkey on customer c (cost=0.43..2.10 rows=1 width=16)
(actual time=0.028..0.028 rows=1 loops=48210)
The planner multiplied the selectivity of status and city as if independent and expected 12 rows, so a nested loop looked cheap; 48,210 rows arrived. Fixes are in the statistics section below.
In MySQL, use EXPLAIN FORMAT=TREE or EXPLAIN ANALYZE (8.0.18+). The traditional tabular EXPLAIN shows type (const, ref, range, index, ALL = full scan), key, rows and Extra (Using index = covering, Using filesort, Using temporary).
Scan types
| Scan | What it does | Good when |
|---|---|---|
| Seq Scan | Reads every page in order (possibly in parallel) | Large fraction of rows needed, small tables |
| Index Scan | Descends an index, fetches each matching heap tuple | Few rows, or ordered output needed |
| Index Only Scan | Answers from the index; heap only for non-all-visible pages | Covering index, well-vacuumed table |
| Bitmap Index Scan → Bitmap Heap Scan | Collects matching TIDs into a bitmap, then reads heap pages in physical order; can AND/OR several indexes | Medium selectivity, or combining indexes; shows Recheck Cond when the bitmap becomes lossy |
Join algorithms
| Join | How | Cost profile | Watch for |
|---|---|---|---|
| Nested Loop | For each outer row, look up matching inner rows (ideally via index) | Excellent for small outer sides; terrible when the outer side is underestimated | High loops on the inner node |
| Hash Join | Build a hash table on the smaller input, probe with the other | Linear in both inputs; equality joins only | Batches > 1 means spilling past work_mem (times hash_mem_multiplier) |
| Merge Join | Walk two sorted inputs in step | Great when both inputs come sorted from indexes; needs a sort otherwise | Expensive explicit sorts feeding it |
Statistics
ANALYZE (run by autovacuum, or manually) samples each table and stores, per column: null fraction, n_distinct, most common values with frequencies, a histogram of the rest, and correlation between value order and physical order. Inspect them in pg_stats.
Common estimate problems and fixes:
- Stale statistics after bulk loads or deletes. Run
ANALYZEafter large data changes; for big tables lowerautovacuum_analyze_scale_factorper table so they are re-analyzed before 10% of rows change. - Too coarse for skewed columns.
default_statistics_target = 100keeps 100 MCVs and histogram buckets. Raise it per column for skewed keys:ALTER TABLE payment ALTER COLUMN merchant_id SET STATISTICS 1000; - Correlated columns. The planner assumes independence. Tell it otherwise with extended statistics (Postgres 10+, MCV lists 12+):
CREATE STATISTICS orders_status_city (dependencies, mcv) ON status, city FROM orders;
ANALYZE orders;
- Parameter-sensitive plans. Prepared statements switch to a generic plan after five executions if it is not estimated to be worse than custom plans. For a skewed
merchant_id, the generic plan may suit small merchants and be terrible for the largest.plan_cache_mode = force_custom_plan(per session or role, Postgres 12+) is the escape hatch.
MySQL keeps index statistics per table (innodb_stats_persistent) and supports column histograms since 8.0 (ANALYZE TABLE t UPDATE HISTOGRAM ON col).
The N+1 problem
The order history page loads 50 orders, then for each order queries its lines, then for each line the product: 1 + 50 + N queries. Each is fast in isolation (≈ 0.3 ms), but the round trips add up to hundreds of milliseconds and hold a connection the whole time. ORMs with lazy loading make this invisible in code review.
Fix by fetching related data in sets:
// One query for the orders, one for all their lines.
func LoadOrdersWithLines(ctx context.Context, pool *pgxpool.Pool, customerID int64) ([]Order, error) {
rows, err := pool.Query(ctx, `
SELECT id, status, total_minor, created_at
FROM orders WHERE customer_id = $1
ORDER BY created_at DESC, id DESC LIMIT 50`, customerID)
if err != nil {
return nil, err
}
orders, err := pgx.CollectRows(rows, pgx.RowToStructByPos[Order])
if err != nil {
return nil, err
}
ids := make([]int64, len(orders))
byID := make(map[int64]*Order, len(orders))
for i := range orders {
ids[i] = orders[i].ID
byID[orders[i].ID] = &orders[i]
}
rows, err = pool.Query(ctx, `
SELECT order_id, line_no, sku_id, quantity, unit_price_minor
FROM order_line WHERE order_id = ANY($1)
ORDER BY order_id, line_no`, ids)
if err != nil {
return nil, err
}
lines, err := pgx.CollectRows(rows, pgx.RowToStructByPos[OrderLine])
if err != nil {
return nil, err
}
for _, l := range lines {
o := byID[l.OrderID]
o.Lines = append(o.Lines, l)
}
return orders, nil
}
Here Order has exported fields ID, Status, TotalMinor, CreatedAt in query order followed by Lines []OrderLine tagged db:"-" so positional mapping ignores it. A join returning orders and lines in one result is also fine when the parent rows are narrow; batching wins when parents are wide or there are several child collections (a join would multiply rows). Detect N+1 in production by looking for queries with very high calls and tiny mean_exec_time in pg_stat_statements, or many identical spans per request in tracing (see Observability & SLOs).
Pagination: OFFSET versus keyset
ORDER BY created_at DESC LIMIT 50 OFFSET 100000 must produce and discard 100,000 rows; page 2,000 of a merchant's transaction history gets slower the deeper you go, and rows shift between pages when new transactions arrive.
Keyset (seek) pagination remembers the last row of the previous page and seeks past it:
CREATE INDEX payment_merchant_created_id_idx ON payment (merchant_id, created_at DESC, id DESC);
-- first page
SELECT id, amount_minor, created_at FROM payment
WHERE merchant_id = $1
ORDER BY created_at DESC, id DESC
LIMIT 50;
-- next page: pass the last row's (created_at, id)
SELECT id, amount_minor, created_at FROM payment
WHERE merchant_id = $1 AND (created_at, id) < ($2, $3)
ORDER BY created_at DESC, id DESC
LIMIT 50;
- The
idtiebreaker makes the order total, so no row is skipped or duplicated when timestamps collide. - Postgres uses the index for the row-value comparison. In MySQL, write it expanded,
created_at < ? OR (created_at = ? AND id < ?), because row-constructor comparisons have historically not been optimized as well. - Return an opaque cursor (base64 of the last key, ideally signed) rather than raw values, so you can change the implementation later.
- Trade-offs: no "jump to page 37", and exact total counts are expensive anyway (
COUNT(*)scans in Postgres because of MVCC). Show "more results" or an estimate.
Connection pooling
Postgres forks a backend process per connection. Each costs memory (a few MB at baseline, more with large work_mem sorts and catalog caches; rough) and adds contention on shared structures; thousands of mostly idle connections hurt throughput. MySQL uses a thread per connection, cheaper but with similar contention at high counts.
Layers:
- Application pool (
database/sqlorpgxpool): reuse connections within one process. - External pooler (PgBouncer, or RDS Proxy, Pgpool-II, Odyssey): multiplex many client connections onto few server connections.
| PgBouncer mode | Server connection held for | Breaks |
|---|---|---|
| Session | The client's whole session | Nothing, but little multiplexing |
| Transaction | One transaction | Session state: SET without LOCAL, session advisory locks, LISTEN, WITH HOLD cursors, temp tables across transactions; protocol-level prepared statements unless PgBouncer 1.21+ with max_prepared_statements |
| Statement | One statement | Multi-statement transactions |
Sizing, roughly: the database needs only enough active connections to keep its CPUs and disks busy. A frequently quoted starting point (from the HikariCP pool-sizing guide) is about 2 × cores + effective spindles; tune by measurement. The failure mode in microservices is multiplication: 40 pods × pool size 20 = 800 server connections, plus migrations, cron jobs and consoles. Either cap each pod's pool so the sum fits, or put PgBouncer in transaction mode between them.
cfg, err := pgxpool.ParseConfig(os.Getenv("DATABASE_URL"))
if err != nil {
return nil, err
}
// Per pod: pods × MaxConns must fit the server's connection budget.
cfg.MaxConns = 10
cfg.MinConns = 2
// Rotate connections so they rebalance after failover or scaling.
cfg.MaxConnLifetime = 30 * time.Minute
cfg.MaxConnIdleTime = 5 * time.Minute
// Behind PgBouncer in transaction mode (pre-1.21), avoid server-side prepared statements:
// cfg.ConnConfig.DefaultQueryExecMode = pgx.QueryExecModeSimpleProtocol
pool, err := pgxpool.NewWithConfig(ctx, cfg)
Waiting for a pool connection is latency too; export pool metrics (acquire count, acquire duration, idle and in-use connections) and alert on acquire time.
Other rewrites that matter
- Select only needed columns.
SELECT *defeats covering indexes and drags TOASTed JSONB across the network. - Avoid functions on indexed columns in
WHERE(see Indexing). NOT IN (subquery)behaves unexpectedly withNULLs and plans poorly; useNOT EXISTS.- CTEs: since Postgres 12, a non-recursive CTE referenced once is inlined; before that it was an optimization fence. Use
MATERIALIZED/NOT MATERIALIZEDto control it. - Big
INlists from the app: pass an array (= ANY($1)) to keep one prepared statement shape. - JIT (Postgres 11+, on by default since 12) can add tens of milliseconds to short OLTP queries with high estimated cost; if plans show significant
JITtime, raisejit_above_costor disable it for the OLTP role. - Set timeouts:
statement_timeoutper role (for example a few seconds for the API role, longer for reporting) so one runaway query cannot hold resources indefinitely.
Trade-offs
| Option | Strengths | Weaknesses | Choose when |
|---|---|---|---|
| Add an index | Often 100–1000× faster reads | Write cost, storage, maintenance | Hot read path with selective predicates |
| Rewrite the query | No write cost, often the real fix | Needs code change and testing | N+1, OFFSET, function-wrapped predicates |
| Improve statistics | Fixes many plans at once, no code change | Planning cost slightly higher; not every misestimate is fixable | Correlated or skewed columns, stale stats |
Planner settings (random_page_cost, work_mem) | Global effect, quick | Can regress other queries; work_mem multiplies per node and per connection | Systematic mismatch with hardware |
| Denormalize or precompute | Constant-time reads | Consistency and storage costs | Dashboards, aggregates, read models |
| Read replica | Offloads reads | Replication lag, eventual consistency | Reporting, non-critical reads |
| Cache | Removes load entirely | Invalidation, staleness (see Caching) | Hot, rarely changing data |
In practice
The slow-query workflow:
Enable the tooling:
-- postgresql.conf: shared_preload_libraries = 'pg_stat_statements,auto_explain'
CREATE EXTENSION IF NOT EXISTS pg_stat_statements;
SELECT queryid, calls,
round(total_exec_time)::bigint AS total_ms,
round(mean_exec_time::numeric, 2) AS mean_ms,
rows,
left(query, 100) AS query
FROM pg_stat_statements
ORDER BY total_exec_time DESC
LIMIT 20;
-- Log plans of slow statements automatically (sampling keeps overhead down)
ALTER SYSTEM SET auto_explain.log_min_duration = '500ms';
ALTER SYSTEM SET log_min_duration_statement = '1s';
SELECT pg_reload_conf();
Rank by total time, not mean: a 2 ms query called 5,000 times per second costs more than a 3 s report run hourly. MySQL equivalents: the slow query log (long_query_time), performance_schema.events_statements_summary_by_digest, and Percona's pt-query-digest.
Always test with production-shaped data: the same row counts, skew and correlation. A plan on a 10,000-row staging table tells you almost nothing about a 300-million-row production table.
Common pitfalls
- Running
EXPLAIN ANALYZEon aDELETEin production withoutBEGIN … ROLLBACK. It executes. - Optimizing by mean time and missing the cheap query called a million times.
- Raising
work_memglobally. It applies per sort/hash node per connection; 200 connections × several nodes × 256 MB can exhaust RAM. - Deep
OFFSETpagination in APIs. Symptom: latency grows linearly with page number; scrapers walking all pages load the database. - Pool size × replicas exceeding
max_connections. Symptom:too many clients alreadyduring deploys when old and new pods overlap. - Using session features behind transaction pooling. Symptom:
prepared statement "…" does not existerrors,SET search_pathleaking between clients. - Testing on tiny datasets. Symptom: everything is a sequential scan in staging and a different plan in production.
- Ignoring planning time for very complex queries or many partitions;
Planning Timecan exceed execution time.
Interview angle
- Prompts: "This endpoint is slow, walk me through how you'd investigate", "How do you paginate a 500-million-row transaction history?", "Why did this query suddenly get slow after a data migration?", "How many database connections should each service have?"
- A strong answer is a method: measure (top queries by total time), explain (plan with real parameters), hypothesize (estimate vs actual, rows filtered), fix (index, stats, rewrite), verify, prevent regressions.
- Mention the system view: pool sizing across pods, PgBouncer trade-offs, replicas for reads, caching where staleness is acceptable (see Database Replication & Sharding).
- Follow-ups: "What does
loopsmean?", "Why might the planner ignore your index?", "What breaks in PgBouncer transaction mode?". - Red flags: adding indexes without looking at the plan, "just add a read replica" for a write-heavy problem,
OFFSETpagination for infinite scroll.
Self-check
1. In a plan, a node shows actual time=0.03..0.04 rows=1 loops=50000. How expensive is it in total and what does it suggest?
Times are per loop, so the node took roughly 0.04 ms × 50,000 ≈ 2 seconds in total. It is the inner side of a nested loop that ran 50,000 times, usually because the planner underestimated the outer side. Check the outer node's estimated versus actual rows; a hash join may be better once estimates are fixed.
2. When is a hash join better than a nested loop, and what makes a hash join slow?
When both inputs are large, or the outer input is large and the inner lookup is not a cheap index probe, and the join is on equality. It is linear in both inputs instead of outer × lookup cost. It slows down when the hash table exceeds work_mem × hash_mem_multiplier and spills into multiple batches on disk, visible as Batches > 1 in the plan.
3. Orders with status = 'PAID' AND city = 'Hanoi' are estimated at 12 rows but there are 48,000. Why, and how do you fix it?
The planner multiplies per-column selectivities assuming independence, but status and city are correlated in your data (most Hanoi orders are paid, say). Create extended statistics (CREATE STATISTICS … (dependencies, mcv) ON status, city FROM orders) and ANALYZE, so the planner uses the combined distribution. Then re-check the plan.
4. Why is keyset pagination stable and fast, and what do you give up?
It seeks directly to the position after the last seen key using an index on the sort columns, so each page costs the same regardless of depth, and new inserts do not shift pages because the cursor is a value, not a position. You give up random access to page N and cheap exact total counts; the sort must be on indexed columns with a unique tiebreaker.
5. You have 60 pods each with a pool of 25 connections to one Postgres primary with max_connections = 500. What happens and what do you change?
Up to 1,500 connections could be requested; during deploys or traffic spikes you hit too many clients already, and even below the limit hundreds of active backends contend for CPU. Reduce per-pod pools (for example 5–8) based on measured concurrency, or put PgBouncer in transaction mode in front so thousands of client connections share a few dozen server connections, accepting its session-feature limitations.
6. How do you find N+1 patterns in a production system without reading all the code?
In pg_stat_statements, look for query shapes with very high calls, tiny mean time and a high calls-per-request ratio, typically SELECT … WHERE parent_id = $1. In distributed tracing, look for requests with dozens of identical database spans. Then replace them with batched = ANY($1) queries or joins.
7. Scenario: a reconciliation report was fast yesterday and takes 40 minutes today after a bulk import of 200 million rows. What do you check first?
Whether statistics are stale: compare the plan's estimated rows with actual rows, and check last_analyze/last_autoanalyze in pg_stat_user_tables. Run ANALYZE on the imported tables and re-plan. Then check for spills (work_mem), missing indexes on new access paths, and whether the import left many dead tuples that need vacuuming.
Exercise
Build a 3-million-row order history and fix three problems.
docker run --name pg-opt -e POSTGRES_PASSWORD=pg -p 5432:5432 -d postgres:17 \
-c shared_preload_libraries=pg_stat_statements
docker exec -it pg-opt psql -U postgres
CREATE EXTENSION pg_stat_statements;
CREATE TABLE orders (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
customer_id int NOT NULL,
status text NOT NULL,
city text NOT NULL,
total_minor bigint NOT NULL,
created_at timestamptz NOT NULL
);
INSERT INTO orders (customer_id, status, city, total_minor, created_at)
SELECT (random() * 100000)::int,
CASE WHEN g % 10 < 8 THEN 'PAID' ELSE 'CANCELLED' END,
CASE WHEN g % 10 < 8 THEN 'Hanoi' ELSE 'Da Nang' END, -- status and city correlated
(random() * 5000000)::bigint,
now() - (g || ' seconds')::interval
FROM generate_series(1, 3000000) g;
ANALYZE orders;
- Correlated estimate. Run
EXPLAIN ANALYZE SELECT count(*) FROM orders WHERE status = 'PAID' AND city = 'Hanoi';and note estimated vs actual rows. Add extended statistics,ANALYZE, and compare. - Pagination. Compare
EXPLAIN (ANALYZE, BUFFERS)forORDER BY created_at DESC, id DESC LIMIT 50 OFFSET 1000000against the keyset equivalent after creating an index on(created_at DESC, id DESC). Record buffers and time. - N+1. Write a small Go program (or a psql loop with
\gexec) that loads 50 orders for a customer and then each order's lines one by one, versus one= ANY($1)query. Comparecallsand total time inpg_stat_statements. - Spill. Run a
GROUP BY customer_id ORDER BY sum(total_minor) DESCwithSET work_mem = '1MB'and then'64MB'; find theSort Methodline in each plan.
Done when you have before/after numbers for each step and can explain each change from the plan output.
Further reading
- PostgreSQL documentation, "Using EXPLAIN": postgresql.org/docs/current/using-explain.html and "How the Planner Uses Statistics".
- Markus Winand, SQL Performance Explained; "Paging Through Results" on use-the-index-luke.com.
- PgBouncer documentation, "Features" and "Configuration": pgbouncer.org.
- HikariCP wiki, "About Pool Sizing" (Brett Wooldridge).
- MySQL Reference Manual, "Optimizing SQL Statements" and "EXPLAIN Output Format".
Related
- Indexing — the structures the planner chooses between.
- PostgreSQL Deep Dive — vacuum, visibility map and tuning knobs that affect plans.
- Partitioning & Sharding in Practice — partition pruning in plans.
- Caching — removing load the database never needed to serve.
- Profiling & Performance — finding the application-side half of latency.
- Observability & SLOs — tracing database spans per request.
Do the self-check first. Marking it complete schedules spaced reviews (1, 3, 7, 14, 30… days).