PostgreSQL ships with conservative defaults, and it is tempting to start tuning by changing configuration. In practice, the biggest gains almost always come from queries and indexes. Work in this order.
1. Find the expensive queries
Enable pg_stat_statements and rank by total time; a query that takes 5 ms but runs millions of times can cost more than one that takes 2 seconds once.
SELECT calls, round(total_exec_time) AS total_ms, round(mean_exec_time::numeric, 1) AS mean_ms,
rows, left(query, 100) AS query
FROM pg_stat_statements ORDER BY total_exec_time DESC LIMIT 15;
From the application side, traces show which endpoints run which queries and how often per request, which reveals N+1 patterns. See how to find slow database queries.
2. Fix queries and indexes
- Add missing indexes, especially on foreign keys and filter-and-sort combinations; see database indexing for developers.
- Remove N+1 patterns with joins or batched IN queries.
- Select only the columns you need; paginate large results with keyset pagination rather than large OFFSETs.
- Rewrite queries that EXPLAIN shows doing sequential scans or large sorts.
3. Memory settings
| Setting | What it does | Starting point |
|---|---|---|
shared_buffers | PostgreSQL's own cache | Around 25% of RAM on a dedicated server |
effective_cache_size | Planner's estimate of OS + PG cache | 50–75% of RAM |
work_mem | Memory per sort/hash operation | Modest (e.g. 16–64 MB); it is per operation, per connection |
maintenance_work_mem | For VACUUM, CREATE INDEX | Larger (e.g. 512 MB–2 GB) |
Be careful with work_mem: a complex query can use several multiples of it, across many connections.
4. Connections
Each connection is a process with its own memory. Hundreds of connections waste memory and increase contention. Keep max_connections moderate and use a pooler such as PgBouncer when many application instances connect. See database connection pooling.
5. Autovacuum
PostgreSQL's MVCC leaves dead rows that vacuum cleans up. If autovacuum falls behind, tables and indexes bloat and queries slow down. On busy tables, make autovacuum more aggressive (lower scale factors) and watch n_dead_tup and last_autovacuum in pg_stat_user_tables. Never disable autovacuum.
6. Checkpoints and WAL
Frequent checkpoints cause IO spikes. Raising max_wal_size and setting checkpoint_completion_target near 0.9 spreads writes out. Watch for "checkpoints are occurring too frequently" warnings in the log.
7. Storage and the planner
On SSDs, lowering random_page_cost (for example to 1.1) tells the planner that random reads are cheap, which often leads to better index use. Keep statistics fresh; run ANALYZE after big data loads.
Worked example
A reporting endpoint took 4 seconds. pg_stat_statements showed a query scanning an events table of 80 million rows. EXPLAIN revealed a sequential scan and an on-disk sort. An index on (account_id, created_at), a narrower SELECT list and keyset pagination brought it to 40 ms. Only afterwards did the team tune work_mem for a nightly batch job that still sorted on disk.
Monitoring after tuning
Track query latency from the application side (p95 database time per endpoint), connection usage, cache hit ratio, dead tuples, replication lag and disk. See PostgreSQL monitoring; VitalRix APM shows per-statement call volume and p95 from your traces, and a ready-made Postgres check confirms the database answers from the network your app uses.
Common mistakes
- Tuning configuration before fixing queries.
- Huge work_mem that runs the server out of memory under load.
- Too many connections instead of a pooler.
- Disabling autovacuum to "save IO".
Partitioning and archiving
Very large append-heavy tables (events, logs, audit records) benefit from declarative partitioning by time: queries that filter by date touch only recent partitions, and old data can be detached and archived instead of deleted row by row. Partitioning adds complexity, so consider it once a table reaches hundreds of millions of rows or retention requires dropping old data regularly. Combined with good indexes and autovacuum settings, it keeps large tables fast. See log retention policy for deciding how long to keep data.
What is the single biggest PostgreSQL performance win?
Usually adding the right index to the most expensive query, found with pg_stat_statements and traces.
How much shared_buffers should I set?
A common starting point is about 25% of RAM on a dedicated database server, then measure.
Should I use a connection pooler?
Yes, when many application instances connect. PgBouncer in transaction mode is the common choice.
Try VitalRix free
Uptime monitoring, APM, logs, real user monitoring and status pages in one place. No credit card needed.