Postgres Performance Tuning: Read Query Plans, Fix Slow Queries
On this page
Postgres performance tuning for startups: read EXPLAIN plans and test indexes and keyset pagination on a 1,000,000-row database with measured timings.
Postgres performance tuning pays off fastest when you work in a fixed order: find the slow query, read its plan, change one thing, then measure again. This guide follows that loop on a test database we built on PostgreSQL 14.20 with 1,000,000 orders and 20,000 customers. Every plan and timing below comes from that run of the queries a typical startup app sends.
The guide is for a founder or small team whose pages have started to feel slow, and for the engineer who has to explain why. It covers how to find the queries that cost the most, how to read an EXPLAIN plan, four fixes with measured results, and where connection pools fit. Our guide to scaling Supabase for startups covers connection limits and foreign key indexes in depth, so this one links there instead of repeating it.
Our numbers come from a laptop with the whole 87 MB table in memory. A cold cache on your host will make the slow versions slower, so expect the plan shapes and ratios to carry over and the milliseconds to differ. Timings are the range across four warm runs in psql with \timing on. The Execution Time lines inside plans come from EXPLAIN ANALYZE, which times every plan node and reads higher.
Key takeaways
- Sort
pg_stat_statementsby total time and by call count. In our test the costliest query ran 20 times, and the most frequent ran 300 times at 0.003 ms each. EXPLAIN ANALYZEruns the statement. Wrap any write in a transaction and roll it back.- A large
Rows Removed by Filternumber marks a missing index. Our worst query read about one million rows to keep 48. - A composite index on
(customer_id, created_at DESC)cut one query from about 20 ms to about 0.1 ms, and the buffers it touched from 8,410 to 23. - A query on
created_atalone ignored that index and ran as a sequential scan of about 58 ms on 14.20, becausecreated_atis the second column. - A deep
OFFSETof 900,000 took about 47 ms. Keyset pagination returned the same page in about 0.1 ms.
What does Postgres performance tuning involve for a startup?
It involves four steps in a fixed order: find the queries that cost the most, read their plans, make the smallest fix that changes the plan, and measure again. None of them needs a bigger server. Server settings such as memory allocation come after this loop, and this guide leaves them out.
For the locking rules when you ship an index through a migration, read our walkthrough of changing a schema without downtime.
How do you find the slow queries?
Use the two tools that ship with Postgres. The pg_stat_statements documentation describes a module that tracks planning and execution statistics for every statement. On a self-hosted server you add pg_stat_statements to shared_preload_libraries, which needs a restart. Each database you want to query then runs CREATE EXTENSION pg_stat_statements. On a managed service, follow your provider's page for the exact steps.
The second tool is the log_min_duration_statement setting. It logs every statement that runs at least as long as the value you give it, and the default of -1 turns it off. PostgreSQL's own example is 250 ms, and the documentation calls the setting helpful for tracking down unoptimized queries.
What does pg_stat_statements show?
It shows one row per normalized query, with the call count and the time spent. We ran a small workload against the test database and ranked the rows by total execution time:
SELECT calls,
round(total_exec_time::numeric, 1) AS total_ms,
round(mean_exec_time::numeric, 3) AS mean_ms,
query
FROM pg_stat_statements
ORDER BY total_exec_time DESC
LIMIT 4;
| Calls | Total ms | Mean ms | Query |
|---|---|---|---|
| 20 | 914.7 | 45.733 | SELECT count(*) FROM orders WHERE created_at > now() - interval $1 |
| 1 | 44.8 | 44.825 | SELECT * FROM orders ORDER BY id LIMIT $1 OFFSET $2 |
| 50 | 1.6 | 0.032 | SELECT * FROM orders WHERE customer_id = $1 ORDER BY created_at DESC LIMIT $2 |
| 300 | 1.0 | 0.003 | SELECT * FROM customers WHERE id = $1 |
The count query tops the list with 914.7 ms of server time across 20 calls. The 300 customer lookups cost 1.0 ms combined, so a ranking by total time puts them last. Look at them next. Three hundred single-row lookups in one page load are an N+1 pattern, and the server-side timer does not count the 300 network round trips your application pays. Sort by calls too.
How do you read an EXPLAIN plan?
Start with EXPLAIN, which shows the plan the planner chose and its cost estimates, then add ANALYZE to run the query and see real row counts and times. PostgreSQL's EXPLAIN reference warns that the statement executes, so side effects happen. For a write, wrap the command like this: BEGIN; EXPLAIN ANALYZE ...; ROLLBACK;
We write EXPLAIN (ANALYZE, BUFFERS) in full. Buffer counts are off by default on the 14.20 release we ran, and they show how many pages a query touched, a steadier measure than time on a busy laptop.
What does a slow plan look like?
This is the plan for the query behind a customer's order history page, before any index existed. We trimmed the output to the lines that matter:
SELECT * FROM orders
WHERE customer_id = 4242
ORDER BY created_at DESC
LIMIT 20;
Workers Launched: 2
Parallel Seq Scan on orders (actual time=1.466..20.571 rows=16 loops=3)
Filter: (customer_id = 4242)
Rows Removed by Filter: 333317
Buffers: shared hit=8334
Execution Time: 24.090 ms
Read it from the scan node. Seq Scan means Postgres read the whole table. loops=3 counts the leader and the two workers that launched, so the filter discarded about 333,000 rows in each of them. The query read about one million rows to return 48, and a Sort node above the scan then ordered them for the LIMIT.
Which plan signals should you check first?
| Signal in the plan | What it tells you | Next step |
|---|---|---|
Seq Scan with a large Rows Removed by Filter |
The query reads far more rows than it returns | Index the filtered column |
| Estimated rows far from actual rows | The planner works from stale statistics | Run ANALYZE on the table |
High loops on an inner node |
The same work repeats for each outer row; multiply time by loops | Check for an N+1 pattern or a join that needs an index |
A Sort node above a scan that feeds a LIMIT |
The database sorts many rows to return a few | Add an index that matches the ORDER BY |
Large shared read next to small shared hit |
Pages came from outside the cache | Check memory and the size of the working set |
We hit an estimate mismatch in our test. We switched off autovacuum on the orders table for one demonstration and inserted 200,000 rows with a new status value. The planner estimated one row and the scan returned 66,667 per loop. After ANALYZE orders the estimate read 201,600 against 200,000 actual rows. On a normal setup autovacuum runs ANALYZE for you, so you meet a mismatch like this after a bulk load that lands before its next pass, or on a table it skips, such as a partitioned parent.
Which fixes move the numbers?
We measured four fixes.
| Fix | Before | After |
|---|---|---|
Composite index on (customer_id, created_at DESC) |
About 20 ms, 8,410 buffers | About 0.1 ms, 23 buffers |
Expression index on lower(email) |
About 3.9 ms (scan of 20,000 rows) | About 0.05 ms |
Keyset pagination instead of OFFSET 900000 |
About 47 ms | About 0.1 ms |
| One batched lookup instead of 300 single lookups | 300 queries, 1.0 ms of server time | 1 query, 0.45 ms of server time |
How do you add an index that matches the filter and the sort?
Put the equality column first and the sort column second. The index below serves the order history query, because Postgres can walk the matching entries in created_at order and stop after 20 rows:
CREATE INDEX CONCURRENTLY orders_customer_created_idx
ON orders (customer_id, created_at DESC);
After the index, the plan is one Index Scan with Index Cond: (customer_id = 4242). It has no Sort node and touched 23 buffers. The CONCURRENTLY option builds the index without locking out writes. It takes longer than a plain build and cannot run inside a transaction block. A failed build leaves an invalid index that you drop and retry. Our scaling guide lists the same caveats next to the foreign key indexes that generated schemas can lack.
Column order matters. The multicolumn index documentation says a multicolumn B-tree index works best when the query constrains the leading columns. We confirmed it: a query that counts orders from the last day filters on created_at alone. With our index in place it ran as a Parallel Seq Scan at about 58 ms on 14.20 and removed about 332,000 rows per loop. That query needs its own index on created_at. Newer releases add a skip scan optimization that the same page describes, so test on your version.
How do you index a function such as lower(email)?
Index the expression itself. A login lookup that compares lower(email) to a lowercase address cannot use a plain index on email. We ran it on 20,000 customers before and after:
CREATE INDEX CONCURRENTLY customers_lower_email_idx
ON customers (lower(email));
Before the index, the scan filtered 19,999 rows and took about 3.9 ms. After it, a bitmap index scan found the row in about 0.05 ms.
Why does a contains search stay slow?
A search like email LIKE '%777@%' starts with a wildcard, and in our test it stayed a sequential scan at about 1.3 ms on 20,000 rows. PostgreSQL's index documentation limits B-tree support for LIKE to patterns anchored at the start. Our guide to full-text search for startups compares the database-native options with a search engine.
How do you replace a deep OFFSET?
A page request such as OFFSET 900000 forces the server to produce every skipped row. PostgreSQL's LIMIT and OFFSET documentation explains why: the server must compute the rows an OFFSET clause skips, so a large OFFSET can be inefficient. Our plan showed an index scan that returned 900,020 rows to hand back 20, and the query took about 47 ms. With timing on, EXPLAIN ANALYZE reported 89 ms for it.
Keyset pagination remembers the last key the client saw and asks for the rows after it:
SELECT * FROM orders
WHERE id > 900000
ORDER BY id
LIMIT 20;
That version touched 7 buffers and finished in about 0.1 ms. It needs an ORDER BY on a unique, indexed column, and it gives up jumping straight to page 400.
How do you batch repeated lookups?
Fetch the rows for one page with a single query instead of one query per row. In our test, 300 lookups by primary key became one WHERE id = ANY(...) statement that ran in 0.45 ms of server time. Ask your ORM for eager loading or write the batched query yourself. Then confirm with pg_stat_statements that the call count dropped.
Do connection pools affect performance?
Yes. A pool controls how many clients hold a database connection at once. Postgres limits connections through max_connections, and the documentation gives 100 as the typical default. A serverless app that opens a connection per request reaches that limit before the queries slow down.
PgBouncer is a common pooler. Its feature list describes three modes. Session pooling holds a server connection for the whole client session. Transaction pooling holds one for the length of a transaction, and the feature table marks SET, LISTEN, PREPARE and session-level advisory locks as unsupported in that mode. Protocol-level prepared statements work in transaction mode when max_prepared_statements is set above zero. Statement pooling is the strictest mode and forbids multi-statement transactions. PgBouncer keeps about 2 kB per connection by default. See our guide to scaling Supabase for startups for the pooler modes and connection limits on a managed platform.
How do you keep the fixes honest?
Measure again after every change, and measure on data that looks like production. Postgres updates each index whenever its table changes, so an index that no query uses costs time on every write. The pg_stat_user_indexes view reports idx_scan, the number of scans each index has served, and an index with zero scans over a representative period is a candidate to drop.
Alert on slow queries before your users report them. Our guide to logging, metrics and alerting on a small team covers where that alert belongs.
Common mistakes
- Ranking queries by mean time alone and missing the 300-call lookup that runs on every page.
- Creating an index on
(customer_id, created_at)and expecting it to serve a query oncreated_atalone. - Reading plan cost numbers as milliseconds. Costs use arbitrary units, while the actual time is in milliseconds.
- Adding an index for every slow query and never checking
idx_scanagain.
Frequently asked questions
How do I find slow queries in Postgres without a paid tool?
Enable pg_stat_statements and rank its rows by total_exec_time. Add log_min_duration_statement to catch single slow executions in the log. Both ship with Postgres, and the first one needs a server restart on a self-hosted install.
Is EXPLAIN ANALYZE safe to run in production?
It runs the statement for real. A SELECT costs one more execution. A write changes data, so wrap it in BEGIN and ROLLBACK, or run it against a copy.
Why does Postgres ignore my index?
Four causes cover most cases: stale statistics, a filter on a column that is not the index's leading column, a function wrapped around the column, or a table small enough that a sequential scan wins. Run ANALYZE first, then time the query with and without the index.
When should a startup add PgBouncer?
Add it when the number of application connections approaches max_connections, which can happen on serverless hosting, or when your provider recommends it. Pick transaction mode if your code avoids the session features listed above.
Does Postgres performance tuning need a bigger server?
Run the loop first. A larger instance makes a sequential scan faster, and it stays a sequential scan over every row. In our test the gains came from indexes and query shape on one unchanged machine.
Where to start this week
- Enable
pg_stat_statementsand let it collect a few days of real traffic. - Rank the rows by total time and by calls, and pick the top query from each list.
- Run
EXPLAIN (ANALYZE, BUFFERS)on each and read the scan node and the row estimates. - Change one thing and measure again on production-sized data. Write the result in your runbook.
If you want senior engineers to run this loop on your database and hand you the findings, AlgoSmiths works on fixed-price projects with a working demo every week. Our backend and API engineering work covers query tuning, indexing, pooling and the rest of the production database setup.
Topic: Backend, data & architecture