PostgreSQL guide

PostgreSQL performance tuning: a practical guide for production

Find what actually limits your database, fix it in the right order, and prove the change worked. With a parameter table, the SQL to run, and lessons from real production incidents.

By João Victor Oliveira, PostgreSQL DBA · Updated · 20 min read · Leia em português

What PostgreSQL performance tuning is

PostgreSQL performance tuning is the process of measuring how the database behaves under its real workload, finding the resource or wait that limits it, and changing queries, indexes, configuration, maintenance or infrastructure — then measuring again to confirm the change helped.

It is not copying a list of values into postgresql.conf. The same setting that fixes one server can take another one down: a bigger work_mem removes a disk sort on a reporting box and causes an out-of-memory kill on a busy OLTP server. Every change in this guide starts from a measurement and ends with another one.

Short answer: start with the queries that use the most total time and the waits sessions spend on. Fix indexes and queries first, then size memory from real concurrency, then WAL, autovacuum and connections. Change one thing at a time and compare against a baseline.

The order that works

Most of the gain comes from the first steps. Tuning in this order avoids spending a week on parameters while a missing index or an open transaction is the real problem:

  1. Measure latency, throughput, waits, CPU, I/O, temp files and WAL so you have something to compare against.
  2. Queries: find the few statements that consume most of the time.
  3. Indexes: add the missing ones, drop the unused ones.
  4. Memory: size shared_buffers and work_mem from concurrency, not from total RAM alone.
  5. WAL and checkpoints: stop write spikes.
  6. Autovacuum: keep bloat and statistics under control, table by table.
  7. Connections and locks: pool connections and remove long transactions.
  8. Operating system and hardware: swap, huge pages, storage latency — and only then a bigger server.

1. Measure a baseline before changing anything

Write down, for a normal day and for the peak hour: transactions per second, p95 latency of the main endpoints, CPU, read and write IOPS, storage latency, active connections, temp files, WAL generated and checkpoint frequency. Without this, "it feels faster" is the only result you will have.

Two views give most of what you need from inside PostgreSQL. pg_stat_activity shows what every session is doing and waiting on right now; sample it every few seconds and keep the samples, because the slowdown at 4:25 pm is gone by the time someone looks.

-- What sessions are waiting on, right now
SELECT wait_event_type, wait_event, state, count(*)
FROM pg_stat_activity
WHERE backend_type = 'client backend'
GROUP BY 1, 2, 3
ORDER BY count(*) DESC;

If most active sessions show Lock, the problem is contention, not configuration. If they show IO (DataFileRead), you are reading from disk more than you should. Client/ClientRead on idle in transaction sessions means the database is waiting on the application. On PostgreSQL 16 and later, pg_stat_io breaks I/O down by backend type and context.

2. Find the queries that cost the most

Rank by total time, not by the single slowest run: a 5 ms query called two million times a day loads the server more than a 30-second report that runs once. The pg_stat_statements extension keeps these counters (it needs shared_preload_libraries = 'pg_stat_statements' and a restart):

SELECT left(query, 80)                    AS query,
       calls,
       round(total_exec_time / 1000)      AS total_s,
       round(mean_exec_time::numeric, 1)  AS mean_ms,
       temp_blks_written,
       shared_blks_read
FROM pg_stat_statements
ORDER BY total_exec_time DESC
LIMIT 20;

For each query at the top, read its plan with real numbers:

EXPLAIN (ANALYZE, BUFFERS) SELECT ...;  -- BUFFERS is included by default from PostgreSQL 18

Look for four things: estimated rows far from actual rows (stale or missing statistics), a Seq Scan that returns a few rows from a big table (missing index), Sort Method: external merge (sort spilling to disk) and a Nested Loop with a huge loop count. Our free PostgreSQL EXPLAIN analyzer ranks the nodes by self time and flags these for you, in the browser, without uploading the plan. The guide How to read EXPLAIN ANALYZE walks through each case.

3. Fix indexes: add what is missing, drop what is unused

An index is the cheapest large win in PostgreSQL tuning and also a cost on every write. Start with tables that are read mostly by sequential scans:

-- Big tables read mostly by sequential scans
SELECT relname, seq_scan, idx_scan, n_live_tup
FROM pg_stat_user_tables
WHERE n_live_tup > 100000
ORDER BY seq_scan DESC
LIMIT 20;

-- Indexes never used since the statistics were last reset
SELECT indexrelid::regclass AS index, relid::regclass AS table,
       pg_size_pretty(pg_relation_size(indexrelid)) AS size
FROM pg_stat_user_indexes
WHERE idx_scan = 0
ORDER BY pg_relation_size(indexrelid) DESC;
  • Put equality columns first in a composite index, then the range or sort column.
  • Use a partial index (WHERE status = 'pending') when queries always filter the same small subset.
  • B-tree covers most cases; GIN is for JSONB, arrays and full-text search; BRIN is for huge, append-only tables ordered by time. See B-tree vs GIN vs BRIN.
  • Before dropping an "unused" index, check replicas: idx_scan is per server.
  • Create indexes in production with CREATE INDEX CONCURRENTLY.

4. PostgreSQL tuning parameters: starting points

These are starting points for a dedicated server with SSD or NVMe storage, to adjust from measurements — not final values. The free PostgreSQL Configuration Planner calculates them for your RAM, CPU, workload and version, and adds a work_mem concurrency guardrail.

ParameterDefaultStarting pointApplies with
shared_buffers128MB~25% of RAMrestart
effective_cache_size4GB50–75% of RAM (a planner hint, allocates nothing)reload
work_mem4MB16–64MB, from the concurrency formula belowreload, role or session
hash_mem_multiplier2.0 (PG 15+)keep 2.0; lower it if memory is tightreload
maintenance_work_mem64MB512MB–2GBreload
max_wal_size1GB4–16GB on write-heavy serversreload
checkpoint_timeout5min15minreload
checkpoint_completion_target0.9 (PG 14+)0.9reload
random_page_cost4.01.1 on SSD/NVMereload
effective_io_concurrency1 (16 in PG 18)200 on SSD/NVMereload
max_connections100as low as the workload allows, with a pooler in frontrestart
autovacuum_vacuum_scale_factor0.20.01–0.05 on large tables (per table)reload or ALTER TABLE
autovacuum_vacuum_cost_limit-1 (uses 200)1000–2000 on fast storagereload
max_parallel_workers_per_gather22–4 for analytical queriesreload

Apply and check changes from SQL:

ALTER SYSTEM SET random_page_cost = 1.1;
SELECT pg_reload_conf();

-- What changed, and what still needs a restart
SELECT name, setting, unit, context, pending_restart
FROM pg_settings
WHERE source NOT IN ('default', 'override')
ORDER BY name;

5. Size memory from concurrency, not from total RAM

shared_buffers is PostgreSQL's own cache. Around 25% of RAM is a common start; above about 40% rarely helps because PostgreSQL also relies on the operating system's page cache, and both hold the same pages.

work_mem is the one that takes servers down. It is allocated per sort or hash operation, and a single query can run several of them, in each parallel worker. Hash operations can use work_mem × hash_mem_multiplier, and that multiplier is 2.0 by default since PostgreSQL 15. Size it like this:

memory for queries ≈ RAM − shared_buffers − OS cache you want to keep
work_mem ≈ memory for queries ÷ (active sessions × ~3 operations × hash_mem_multiplier)

Example: 32GB RAM, shared_buffers 8GB, keep 8GB for the OS cache
         → 16GB ÷ (100 × 3 × 2) ≈ 27MB  → start at 24–32MB

Then give more memory only where it is needed, instead of raising it for every connection:

ALTER ROLE reporting SET work_mem = '256MB';   -- reports only
SET work_mem = '512MB';                           -- one session, one heavy job

From production: a report that ran SET work_mem = '2GB' was started by three users at the same time on an 8GB server with no swap. With hash_mem_multiplier at 2.0, each hash node could take up to 4GB. The kernel's OOM killer ended a backend, and systemd's default OOMPolicy=stop then stopped the whole PostgreSQL unit. ALTER ROLE ... SET work_mem only sets a default; it cannot stop a session from running its own SET. Watch temp_files in pg_stat_database to see where more memory really helps.

6. WAL and checkpoints: stop write spikes

Every checkpoint writes all dirty pages to disk. Too frequent, and you get I/O spikes plus extra full-page writes in WAL; too rare, and crash recovery takes longer. The goal is checkpoints triggered by time, not by WAL volume.

-- Requested (by WAL volume) vs timed checkpoints; PostgreSQL 17+
SELECT num_timed, num_requested, write_time, sync_time
FROM pg_stat_checkpointer;
-- On PostgreSQL 16 and earlier: checkpoints_timed, checkpoints_req in pg_stat_bgwriter

If requested checkpoints are a large share, raise max_wal_size. log_checkpoints is on by default since PostgreSQL 15, and the log warns when "checkpoints are occurring too frequently". On write-heavy servers, wal_compression = lz4 (PostgreSQL 15+) reduces WAL volume at a small CPU cost. Keep checkpoint_completion_target at 0.9 so writes are spread across the interval.

7. Planner and I/O settings: tell PostgreSQL what storage you have

The default random_page_cost of 4.0 was chosen for spinning disks. On SSD or NVMe, random reads are nearly as cheap as sequential ones, so a value around 1.1 lets the planner choose index scans when they are really faster. effective_io_concurrency around 200 on SSD lets bitmap heap scans prefetch pages.

Bad estimates come from statistics more often than from cost settings. Run ANALYZE after bulk loads, and for columns with skewed data raise the sample size for that column only:

ALTER TABLE orders ALTER COLUMN customer_id SET STATISTICS 1000;
ANALYZE orders;

When two columns are correlated (city and zip code, for example), extended statistics fix the row estimate: CREATE STATISTICS orders_city_zip (dependencies) ON city, zip FROM orders;

8. Autovacuum: tune it per table, never turn it off

Every UPDATE and DELETE leaves a dead row. Autovacuum removes them, refreshes statistics and protects against transaction ID wraparound. With the default autovacuum_vacuum_scale_factor of 0.2, a 100-million-row table only gets vacuumed after 20 million dead rows — by then scans are slower and the table has grown.

-- Tables with the most dead rows and when they were last vacuumed
SELECT relname, n_live_tup, n_dead_tup,
       round(100.0 * n_dead_tup / nullif(n_live_tup + n_dead_tup, 0), 1) AS dead_pct,
       last_autovacuum
FROM pg_stat_user_tables
ORDER BY n_dead_tup DESC
LIMIT 20;

-- Large, busy table: vacuum at 1% instead of 20%
ALTER TABLE orders SET (autovacuum_vacuum_scale_factor = 0.01,
                        autovacuum_analyze_scale_factor = 0.02);

If autovacuum runs all the time but never catches up, it is throttled: raise autovacuum_vacuum_cost_limit (to 1000–2000 on fast storage) before adding workers, because the cost limit is shared among them. Long transactions also stop vacuum from removing rows, which is why they belong in the next section. The autovacuum tuning guide covers the details.

9. Connections and locks: often the real bottleneck

Each PostgreSQL connection is a separate process with its own memory. Hundreds of mostly idle connections waste RAM and make contention worse. Keep max_connections modest and put PgBouncer in transaction pooling mode in front of applications that open many connections.

Long transactions hold locks and stop vacuum. Find them and who they block:

-- Transactions open for more than 5 minutes
SELECT pid, usename, state, now() - xact_start AS xact_age, left(query, 60)
FROM pg_stat_activity
WHERE xact_start < now() - interval '5 minutes'
ORDER BY xact_start;

-- Who is blocking whom
SELECT blocked.pid AS blocked_pid, now() - blocked.query_start AS waiting_for,
       blocker.pid AS blocker_pid, blocker.state AS blocker_state
FROM pg_stat_activity blocked
CROSS JOIN LATERAL unnest(pg_blocking_pids(blocked.pid)) AS b(pid)
JOIN pg_stat_activity blocker ON blocker.pid = b.pid;

Set guards so mistakes end on their own: idle_in_transaction_session_timeout (for example 5min) closes forgotten transactions, statement_timeout per role stops runaway queries, lock_timeout stops a migration from queuing behind a long lock, and PostgreSQL 17 added transaction_timeout.

From production: an ERP was "slow every afternoon from 4 to 5:30 pm". CPU and I/O were at the daily average. The cause was a batch routine running one transaction for 30 to 67 minutes, with a savepoint per record, holding row locks other users waited on for up to 54 minutes. No parameter fixes that; committing in small batches does. And idle_in_transaction_session_timeout did not catch it, because the session kept going between active and idle.

10. Parallel query and partitioning

Parallel query helps analytical queries that scan large tables; it does little for short OLTP queries. max_parallel_workers_per_gather (default 2) controls workers per query, limited by max_parallel_workers and max_worker_processes. Remember that each worker can use its own work_mem.

Partitioning is a maintenance tool more than a speed tool. It helps when queries filter by the partition key (so the planner prunes partitions), when you delete old data by dropping or detaching a partition instead of a huge DELETE, and when vacuum on one giant table cannot keep up. It hurts when queries do not filter by the key and have to visit every partition, or when there are thousands of partitions.

11. Operating system and hardware

  • Swap and the OOM killer: keep some swap as a safety margin, and consider vm.overcommit_memory = 2 as the PostgreSQL documentation recommends, so allocations fail instead of the kernel killing a backend. On systemd, check the unit's OOMPolicy: with continue and Restart=on-failure, PostgreSQL recovers on its own after a killed backend.
  • Huge pages: with large shared_buffers, configure vm.nr_hugepages and keep huge_pages = try (or on); disable transparent huge pages.
  • Storage latency matters more than throughput for OLTP. Measure it (iostat -x, or the cloud volume metrics) before buying more IOPS.
  • Put WAL on fast storage; mount data volumes with noatime.
  • Only after the steps above, consider a bigger server. More CPU does not help a workload that is waiting on locks.

12. Tuning PostgreSQL on Amazon RDS and Aurora

On managed PostgreSQL you change parameters in a DB parameter group, not in postgresql.conf. Parameters marked "static" apply only after a reboot. Several defaults are formulas based on instance memory (RDS sets shared_buffers to about 25% of it), and you cannot tune the operating system, huge pages or storage layout directly.

That makes the query, index, autovacuum and connection steps above even more important: they are what you control. CloudWatch shows that the instance is busy; it does not show which query, lock or table causes it. See PostgreSQL RDS monitoring for what to track beyond CloudWatch, and how to reduce RDS costs once the database is tuned — a tuned database often fits on a smaller instance.

13. Test, apply and roll back

  1. Write the hypothesis: "requested checkpoints cause write spikes at 10 am; raising max_wal_size to 8GB should turn them into timed checkpoints".
  2. Test on a copy with production-like data. pgbench works for synthetic load; replaying real queries is better.
  3. Change one thing at a time, with ALTER SYSTEM and the previous value written down.
  4. Compare against the baseline at the same hour and day of the week.
  5. Roll back with ALTER SYSTEM RESET parameter and a reload if it did not help.

PostgreSQL tuning mistakes we see in production

  • Raising work_mem globally to fix one report. Set it per role or session instead.
  • Tuning configuration when the problem is locks. If sessions wait on Lock, no memory setting helps.
  • max_connections = 1000 instead of a pooler.
  • Turning autovacuum off because it "uses resources". Bloat and wraparound cost far more.
  • Copying a calculator's output without checking concurrency, version and workload.
  • Killing long queries blindly. A query waiting on a lock is the victim; cancel the blocker. And pg_cancel_backend does nothing to an idle in transaction session.
  • Tuning once. Data grows, queries change, and last year's plan regresses after a deploy.

PostgreSQL performance tuning checklist

  • Baseline recorded: TPS, p95 latency, CPU, IOPS, storage latency, connections, temp files, WAL, checkpoints.
  • pg_stat_statements enabled; top 20 queries by total time reviewed with EXPLAIN (ANALYZE, BUFFERS).
  • Missing indexes added with CONCURRENTLY; unused indexes reviewed on primary and replicas.
  • shared_buffers ~25% of RAM; effective_cache_size 50–75%.
  • work_mem sized from concurrency; larger values only per role or session.
  • Mostly timed checkpoints; max_wal_size raised if not.
  • random_page_cost and effective_io_concurrency match the storage.
  • Autovacuum scale factors lowered on large, busy tables; cost limit raised if it cannot keep up.
  • Connection pooler in place; timeouts set for idle transactions, statements and locks.
  • Swap, OOM behavior and huge pages checked on self-managed servers.
  • Each change tested, compared against the baseline and documented with its rollback.
  • Continuous monitoring in place so regressions show up before users notice.

Tools for PostgreSQL performance tuning

  • PostgreSQL Configuration Planner (free): version-aware starting values for memory, WAL, I/O and connections, with a work_mem concurrency guardrail.
  • EXPLAIN analyzer (free): paste a plan, see where the time goes, compare before and after. Runs in your browser.
  • PG Monitoring: samples running queries every second, records lock chains, and detects plan regressions and per-query anomalies, so tuning continues after the first pass.

Need a second pair of eyes on a slow PostgreSQL?

We run this process on production databases — self-managed, RDS and Aurora: baseline, top queries, indexes, configuration, autovacuum and connections, with every change tested and reversible.

Frequently asked questions

What is PostgreSQL performance tuning?
PostgreSQL performance tuning is the process of measuring how the database behaves under its real workload, finding the resource or wait that limits it, and changing queries, indexes, configuration, maintenance or infrastructure — then measuring again to confirm the change helped.
What should I tune first in PostgreSQL?
Start with the queries that consume the most total time and the waits sessions spend on, not with postgresql.conf. A missing index or a lock held by an open transaction costs more than any parameter. Configuration comes after you know what the bottleneck is.
How much memory should shared_buffers get?
On a dedicated server, about 25% of RAM is a common starting point. Going above roughly 40% rarely helps, because PostgreSQL also relies on the operating system cache. Changing shared_buffers requires a restart.
How do I choose work_mem?
work_mem applies to each sort or hash operation, not to each session, and hash operations can use work_mem × hash_mem_multiplier (2.0 by default since PostgreSQL 15). Size it from the memory left after shared_buffers and the OS cache, divided by the number of operations that can run at the same time. Raise it per role or per session for reports instead of globally.
Do PostgreSQL configuration changes need a restart?
Some do. shared_buffers, max_connections, huge_pages and shared_preload_libraries need a restart; most others take effect with a reload (SELECT pg_reload_conf()). Check pg_settings: the context column shows what each parameter needs and pending_restart shows changes still waiting.
Is PGTune enough to tune PostgreSQL?
Calculators like PGTune give a reasonable starting configuration from RAM and CPU, but they cannot see your queries, locks, data growth or concurrency. Use one as a baseline, then tune from measurements of your real workload.
How is tuning different on Amazon RDS and Aurora?
You change parameters through a DB parameter group instead of postgresql.conf, some changes need a reboot, and you cannot tune the operating system or storage directly. Query, index, autovacuum and connection tuning work the same way and usually matter more.

Related guides

Talk to us