DEV Community

Cover image for Optimising your PostgreSQL database performance, understanding the Architecture, the *Why* and the *How*
Denzel Kanyeki
Denzel Kanyeki

Posted on

Optimising your PostgreSQL database performance, understanding the Architecture, the *Why* and the *How*

Most Postgres tuning guides hand you a list of settings. That works until something breaks and you have no idea why the setting you copied made things worse.

This post starts with how Postgres actually works, then goes through the changes that matter most. Every recommendation is linked back to the part of the architecture it affects, so you know why it helps, not just that it helps.

Here's what we'll cover:

  1. How Postgres is built (processes, memory, the WAL)
  2. Connection pooling with PgBouncer
  3. Replication: splitting reads from writes
  4. Finding slow queries with pg_stat_statements and EXPLAIN ANALYZE
  5. Indexes: B-tree, GIN, BRIN, partial indexes, and materialized views
  6. Table partitioning
  7. Batching writes instead of committing row by row
  8. Memory settings
  9. Logging settings
  10. Monitoring tools

1. How Postgres is built

You need three ideas before any tuning makes sense.

One process per connection

Postgres uses a process-per-connection model. A main process (the postmaster) listens for connections. Every time a client connects, the postmaster forks a new backend process dedicated to that client. That process parses, plans and runs every query for that connection until it disconnects.

Alongside the backends, Postgres runs background processes:

  • Checkpointer: periodically writes all modified ("dirty") pages from memory to disk.
  • Background writer: writes some dirty pages ahead of time so backends don't have to.
  • WAL writer: flushes the write-ahead log to disk.
  • Autovacuum launcher and workers: clean up dead rows and refresh planner statistics.
  • WAL sender: streams changes to replicas (only when replication is set up).

Postgres process architecture: postmaster, backends, shared memory and background processes

Click the diagram to open a zoomable version.

Why this matters for tuning: a process is expensive. Each connection costs memory and CPU time even when it's idle. A thousand connections means a thousand processes competing for the same CPU cores and shared memory. That's the problem connection pooling solves.

Two layers of caching

Postgres keeps recently used data pages (8 KB blocks) in shared buffers, a memory area shared by all backends. When a page isn't there, Postgres asks the operating system for it, and the OS may already have it in its own page cache. Only if both miss does the read go to disk.

How Postgres finds a data page: shared_buffers, then the OS page cache, then disk

Click the diagram to open a zoomable version.

This two-layer design is why shared_buffers should not be set to most of your RAM. The OS cache is doing real work too.

The Write-Ahead Log (WAL)

Before Postgres changes a data page, it first records the change in the WAL, an append-only log on disk. When you COMMIT, Postgres makes sure the WAL record is flushed to disk. The data pages themselves can be written later by the checkpointer.

This gives you durability: if the server crashes, Postgres replays the WAL to recover. It also explains two things we'll come back to:

  • Every commit costs a disk flush. Committing one row at a time is slow because of this.
  • Replication is built on the WAL. Replicas stay in sync by receiving and replaying WAL.

MVCC and dead rows

Postgres uses a Multi Version Concurrency Control (MVCC), specifically a Snapshot MVCC strategy. An UPDATE doesn't overwrite a row; it writes a new version and marks the old one as dead. A DELETE just marks the row dead. Readers never block writers because each transaction sees the versions that were valid when it started.

The cost is that dead rows pile up. VACUUM (usually run by autovacuum) cleans them up so the space can be reused. If vacuum falls behind, tables and indexes bloat, and queries slow down because they're scanning garbage.

How a query runs

Query lifecycle: parser, rewriter, planner and executor

Click the diagram to open a zoomable version.

The planner is where most performance problems come from. It estimates the cost of different plans (sequential scan vs. index scan, hash join vs. nested loop) using statistics about your data. Bad or stale statistics lead to bad plans.

2. Connection pooling with PgBouncer

Because every connection is a process, opening thousands of them hurts. Apps with many instances (web servers, serverless functions, workers) can easily reach that number.

A connection pooler sits between your app and Postgres. Your app opens as many connections as it wants to the pooler, and the pooler shares a small number of real Postgres connections between them.

PgBouncer pooling 600 client connections into 20 Postgres connections

Click the diagram to open a zoomable version.

Six hundred client connections become twenty Postgres backends.

Pooling modes

PgBouncer has three modes. The mode decides when a server connection goes back into the pool.

Mode Connection is returned when... Use it for
Session the client disconnects Apps that rely on session state. Least savings.
Transaction the transaction ends Most web and API workloads. Best savings.
Statement each statement ends Rare. Multi-statement transactions aren't allowed.

Transaction mode is what most people want, but it has a catch. Your next transaction might run on a different server connection, so anything tied to a session can break:

  • SET session variables
  • Temporary tables
  • LISTEN / NOTIFY
  • Session-level advisory locks
  • SQL-level PREPARE / EXECUTE

Protocol-level prepared statements (the kind most drivers and ORMs use) used to break too. PgBouncer 1.21 added support for them in transaction mode through the max_prepared_statements setting, so on a recent version this is much less of a problem.

A starting config

[databases]
appdb = host=127.0.0.1 port=5432 dbname=appdb

[pgbouncer]
listen_port = 6432
pool_mode = transaction
max_client_conn = 2000
default_pool_size = 20
max_prepared_statements = 200
Enter fullscreen mode Exit fullscreen mode

Sizing the pool: start small. More server connections than your CPU can actually run at once just adds context switching. A pool of a few times your CPU core count is a common starting point; then measure.

Run migrations and admin tools against Postgres directly, not through the pooler in transaction mode.

3. Replication: splitting reads from writes

Streaming replication keeps one or more standby servers in sync with a primary by shipping WAL to them.

Streaming replication: writes to the primary, reads from replicas

Click the diagram to open a zoomable version.

Here's how it works:

  1. The primary writes changes to its WAL, like always.
  2. A WAL sender process on the primary streams those records to each replica.
  3. A WAL receiver on the replica writes them to its own WAL.
  4. The replica's startup process replays them, applying the same changes.

With hot_standby = on (the default), replicas accept read-only queries.

What it does and doesn't scale

  • Reads scale. Send reports, dashboards and heavy SELECTs to replicas.
  • Writes don't. Every write still goes to the single primary, and replicas have to replay all of it. If your bottleneck is writes, replicas won't fix it.

Things to watch

Replication lag. By default replication is asynchronous: the primary commits without waiting for replicas. A replica can be a few milliseconds (or under load, seconds) behind. That causes the classic bug: a user saves something, the next page load reads from a replica, and their change "isn't there." Route reads that must see the latest data to the primary.

Check lag on the primary:

SELECT client_addr, state, write_lag, flush_lag, replay_lag
FROM pg_stat_replication;
Enter fullscreen mode Exit fullscreen mode

Synchronous replication. Setting synchronous_standby_names makes the primary wait for a replica to confirm before a commit returns. You won't lose committed data if the primary dies, but every write now pays the network round trip.

Replication slots. Slots make the primary keep WAL until a replica has consumed it. If a replica goes away and its slot isn't dropped, WAL keeps piling up until the primary's disk fills. Check for inactive slots:

SELECT slot_name, active, restart_lsn
FROM pg_replication_slots;
Enter fullscreen mode Exit fullscreen mode

4. Finding slow queries: pg_stat_statements and EXPLAIN ANALYZE

Don't tune blind. Find out which queries cost the most, then look at why.

pg_stat_statements: which queries hurt

This extension ships with Postgres. It tracks every query shape (constants are replaced with $1, $2) with call counts, total time, rows and buffer usage.

Enable it in postgresql.conf (needs a restart):

shared_preload_libraries = 'pg_stat_statements'
Enter fullscreen mode Exit fullscreen mode

Then in your database:

CREATE EXTENSION pg_stat_statements;
Enter fullscreen mode Exit fullscreen mode

Find the queries using the most total time:

SELECT
    query,
    calls,
    round(total_exec_time::numeric, 2) AS total_ms,
    round(mean_exec_time::numeric, 2)  AS mean_ms,
    rows,
    shared_blks_hit,
    shared_blks_read
FROM pg_stat_statements
ORDER BY total_exec_time DESC
LIMIT 10;
Enter fullscreen mode Exit fullscreen mode

Sort by total_exec_time, not just mean_exec_time. A 5 ms query called a million times costs more than a 2-second query called twice.

EXPLAIN ANALYZE: why a query is slow

EXPLAIN shows the plan the planner chose. EXPLAIN ANALYZE actually runs the query and shows real timings and row counts next to the estimates.

EXPLAIN (ANALYZE, BUFFERS)
SELECT * FROM orders WHERE customer_id = 42;
Enter fullscreen mode Exit fullscreen mode

On Postgres 18 and later, BUFFERS is included automatically with ANALYZE. On older versions, add it yourself.

What to look for:

  • Seq Scan on a large table where you expected few rows. Often a missing index.
  • Estimated rows far from actual rows. If the planner expected 10 rows and got 500,000, its statistics are wrong. Run ANALYZE on the table.
  • shared hit vs. read. Hits came from shared buffers; reads came from the OS cache or disk. Lots of reads means the data isn't cached.
  • Sort Method: external merge Disk: ... means the sort didn't fit in work_mem and spilled to disk.

Careful: EXPLAIN ANALYZE really executes the statement. Wrap UPDATE or DELETE in a transaction and roll it back:

BEGIN;
EXPLAIN ANALYZE DELETE FROM orders WHERE created_at < '2020-01-01';
ROLLBACK;
Enter fullscreen mode Exit fullscreen mode

5. Indexes

An index lets Postgres find rows without scanning the whole table. Postgres has several index types, each built for a different kind of query.

B-tree (the default)

A balanced tree of sorted values. It handles equality (=), ranges (<, >, BETWEEN), sorting (ORDER BY) and prefix LIKE 'abc%'.

CREATE INDEX idx_orders_customer ON orders (customer_id);
Enter fullscreen mode Exit fullscreen mode

For multi-column indexes, column order matters. An index on (customer_id, created_at) helps WHERE customer_id = 42 and WHERE customer_id = 42 AND created_at > .... It's much less useful for WHERE created_at > ... alone.

Covering indexes store extra columns so Postgres can answer the query from the index alone (an "index-only scan"):

CREATE INDEX idx_orders_customer_cover
ON orders (customer_id) INCLUDE (status, total);
Enter fullscreen mode Exit fullscreen mode

GIN (Generalized Inverted Index)

GIN indexes the elements inside a value, such as each key in a jsonb document, each item in an array or each word in a text document. Use it for jsonb containment (@>), array searches and full-text search. It's fast to read but slower to update.

CREATE INDEX idx_events_data ON events USING GIN (data);
Enter fullscreen mode Exit fullscreen mode

BRIN (Block Range Index)

BRIN stores a min/max summary for each range of table blocks instead of indexing every row, so Postgres can skip ranges that can't match.

It only works when values follow the table's physical order, like timestamps on an append-only events table. When they do, it's tiny compared with a B-tree.

CREATE INDEX idx_events_created_brin ON events USING BRIN (created_at);
Enter fullscreen mode Exit fullscreen mode

Partial indexes

A partial index covers only the rows that match a condition, so it's smaller and cheaper to maintain. The planner uses it only when the query's WHERE clause matches that condition.

CREATE INDEX idx_orders_pending ON orders (created_at) WHERE status = 'pending';
Enter fullscreen mode Exit fullscreen mode

Other built-in types

  • Hash: equality (=) lookups only. A B-tree usually does the same job and more.
  • GiST: geometric data, ranges and nearest-neighbour searches. PostGIS uses it.
  • SP-GiST: data that splits into non-overlapping parts, such as IP addresses or phone-number prefixes.

Materialized views

Not an index, but related: a materialized view stores a query's result on disk, so expensive aggregations are computed once and read like a table. The data is only as fresh as the last refresh.

CREATE MATERIALIZED VIEW daily_revenue AS
SELECT date_trunc('day', created_at) AS day, sum(total) AS revenue
FROM orders
GROUP BY 1;

CREATE UNIQUE INDEX ON daily_revenue (day);

-- Refresh without blocking readers (requires a unique index)
REFRESH MATERIALIZED VIEW CONCURRENTLY daily_revenue;
Enter fullscreen mode Exit fullscreen mode

The cost of indexes

Every index slows down INSERT, UPDATE and DELETE, because each index has to be updated too. It also uses disk and memory. Find indexes that are never used:

SELECT relname AS table_name, indexrelname AS index_name, idx_scan
FROM pg_stat_user_indexes
WHERE idx_scan = 0
ORDER BY pg_relation_size(indexrelid) DESC;
Enter fullscreen mode Exit fullscreen mode

Check this on replicas too before dropping anything. An index unused on the primary may be serving reads on a replica.

6. Table partitioning

Partitioning splits one large table into smaller physical tables (partitions) while your queries still use a single table name.

CREATE TABLE events (
    id         bigint,
    created_at timestamptz NOT NULL,
    payload    jsonb
) PARTITION BY RANGE (created_at);

CREATE TABLE events_2026_10 PARTITION OF events
    FOR VALUES FROM ('2026-10-01') TO ('2026-11-01');

CREATE TABLE events_2026_11 PARTITION OF events
    FOR VALUES FROM ('2026-11-01') TO ('2026-12-01');
Enter fullscreen mode Exit fullscreen mode

Partition pruning on a range-partitioned events table

Click the diagram to open a zoomable version.

What you get

  • Partition pruning. The planner skips partitions that can't match the WHERE clause. This only happens if your queries filter on the partition key.
  • Cheap data removal. Dropping an old partition is nearly instant. Deleting millions of rows with DELETE creates dead rows and vacuum work.
  • Smaller indexes per partition, which are more likely to fit in memory.
  • Vacuum works per partition, so maintenance on hot recent data doesn't have to churn through years of cold data.
-- Remove a month of data instantly
DROP TABLE events_2026_10;

-- Or detach it first to archive it somewhere else
ALTER TABLE events DETACH PARTITION events_2026_10;
Enter fullscreen mode Exit fullscreen mode

Choosing a strategy

  • Range: time-series data, logs, events. The most common choice.
  • List: discrete values such as region or tenant.
  • Hash: spreads rows evenly when there's no natural range.

Don't partition small tables. Partitioning adds planning overhead and complexity. It starts paying off when a table is large enough that its indexes no longer fit in memory, or when you regularly delete old data in bulk. pg_partman can create future partitions and drop old ones for you.

7. Batch your writes

Remember: every COMMIT forces a WAL flush to disk. If you insert rows one at a time with autocommit on, you pay that flush once per row.

-- Slow: each INSERT is its own transaction, with its own disk flush
INSERT INTO sales (id, amount) VALUES (1, 10.00);
INSERT INTO sales (id, amount) VALUES (2, 12.50);
INSERT INTO sales (id, amount) VALUES (3, 8.75);
Enter fullscreen mode Exit fullscreen mode

Postgres itself doesn't have an "autocommit" switch. Every statement outside an explicit transaction is its own transaction. Autocommit is a client-side behavior, so check what your driver does. Then group work into transactions with BEGIN and COMMIT:

-- Better: many rows, one transaction, one flush at COMMIT
BEGIN;
INSERT INTO sales (id, amount) VALUES
    (1, 10.00),
    (2, 12.50),
    (3, 8.75);
INSERT INTO sales (id, amount) VALUES
    (4, 15.00),
    (5, 9.20);
COMMIT;
Enter fullscreen mode Exit fullscreen mode

Multi-row VALUES lists help too: one statement inserts many rows, so Postgres parses and plans once instead of once per row.

For bulk loads, use COPY. It's a single command that streams rows in, with much less overhead than individual INSERTs:

COPY sales (id, amount) FROM '/path/to/sales.csv' WITH (FORMAT csv, HEADER true);
Enter fullscreen mode Exit fullscreen mode

The official docs on populating a database add a few more bulk-load tricks:

  • Create indexes after loading, not before. Building an index once is faster than updating it for every row.
  • Drop foreign keys during huge loads and re-add them after. Checking them in bulk is cheaper than per row.
  • Raise maintenance_work_mem temporarily to speed up the index and foreign key rebuilds.
  • Raise max_wal_size temporarily so the load triggers fewer checkpoints.
  • Run ANALYZE afterwards so the planner has statistics for the new data.

Don't overdo it

One giant transaction isn't the goal either. A transaction that runs for an hour holds locks, stops vacuum from cleaning up dead rows anywhere in the database, and produces a WAL spike that replicas must replay. Batches of a few thousand to tens of thousands of rows per commit are usually a good middle ground. Measure on your own data.

8. Memory settings

These four settings control how Postgres uses RAM. The defaults are deliberately small so Postgres starts on any machine, which means they're almost always too low for a dedicated server.

How Postgres memory settings divide server RAM

Click the diagram to open a zoomable version.

shared_buffers

The size of Postgres's own page cache. The default is usually 128 MB.

The official docs suggest 25% of RAM as a starting point on a dedicated server with 1 GB or more, and say more than 40% is unlikely to help. The reason is the double caching we covered earlier: the OS page cache holds data too, and giving it all to shared_buffers means the same pages get cached twice. Changing it needs a restart.

work_mem

The memory a single sort or hash operation can use before spilling to temporary files on disk. The default is 4 MB.

This is the one people get wrong, because it's per operation, not per connection. One complex query can run several sorts and hash joins at once, each allowed its own work_mem, and many connections can do that simultaneously.

A rough worst case: 100 connections × 3 operations each × 64 MB = 19 GB. Set work_mem to 64 MB globally on a 16 GB server and a busy moment can push it into swapping or the out-of-memory killer.

A safer approach is to keep the global value modest and raise it only where needed:

-- For one heavy reporting session
SET work_mem = '256MB';
Enter fullscreen mode Exit fullscreen mode

Signs you need more: EXPLAIN ANALYZE shows external merge Disk, or log_temp_files logs lots of temporary files.

maintenance_work_mem

Memory for maintenance operations: VACUUM, CREATE INDEX and ALTER TABLE ... ADD FOREIGN KEY. The default is 64 MB.

A session runs only one of these at a time, so you can safely set it much higher than work_mem. Values from 512 MB up to a couple of GB are common on larger servers. One catch: each autovacuum worker can use this much memory too. Use autovacuum_work_mem if you want to cap autovacuum separately.

effective_cache_size

This one allocates nothing. It tells the planner how much memory is likely available for caching data, counting both shared_buffers and the OS page cache. A higher value makes the planner more willing to choose index scans, since it assumes index pages are likely cached. The default is 4 GB.

A common rule of thumb is 50% to 75% of RAM.

Example: dedicated 16 GB server

shared_buffers = 4GB             # ~25% of RAM, needs restart
effective_cache_size = 12GB      # ~75% of RAM, planner hint only
work_mem = 16MB                  # per sort/hash; raise per session if needed
maintenance_work_mem = 1GB       # VACUUM, CREATE INDEX
Enter fullscreen mode Exit fullscreen mode

These are starting points, not answers. Change one setting at a time and measure with pg_stat_statements before and after.

9. Logging settings

Good logs tell you what went wrong at 3 a.m. without needing to reproduce it.

log_min_duration_statement

Logs any statement that runs longer than the given time, with its duration.

log_min_duration_statement = 500ms
Enter fullscreen mode Exit fullscreen mode

This is the cheapest slow-query detector you have. Start with something like 500 ms to 1 s and lower it as you fix things. Setting it to 0 logs every statement, which is too much for most production systems.

log_checkpoints

Logs each checkpoint: how many buffers were written and how long it took. It's on by default since Postgres 15.

If you see checkpoints happening much more often than checkpoint_timeout (5 minutes by default), they're being triggered by WAL volume. Raising max_wal_size will spread them out and smooth I/O spikes.

log_lock_waits

Logs a message when a session waits for a lock longer than deadlock_timeout (1 second by default). The message names the lock and which process holds it.

log_lock_waits = on
Enter fullscreen mode Exit fullscreen mode

It's cheap and very useful for answering "why is this query hanging?" Turn it on in production.

log_statement

Controls which statement types are logged regardless of duration: none, ddl, mod (DDL plus data changes) or all.

log_statement = 'ddl'
Enter fullscreen mode Exit fullscreen mode

ddl is a good production setting. It gives you a record of schema changes (who dropped that column?) without much noise. Avoid all in production: the log volume is huge and can slow the server down.

Starting point

log_min_duration_statement = 1s
log_checkpoints = on
log_lock_waits = on
log_temp_files = 0          # log every temp file: shows work_mem spills
log_statement = 'ddl'
Enter fullscreen mode Exit fullscreen mode

10. Monitoring tools

pg_stat_activity (built in)

One row per connection, showing what it's doing right now. It's the first place to look when the database feels slow.

Long-running queries:

SELECT pid, now() - query_start AS duration, state, wait_event_type, wait_event, query
FROM pg_stat_activity
WHERE state <> 'idle'
ORDER BY duration DESC;
Enter fullscreen mode Exit fullscreen mode

Sessions idle in a transaction (these hold locks and stop vacuum from cleaning up):

SELECT pid, now() - xact_start AS open_for, query
FROM pg_stat_activity
WHERE state = 'idle in transaction'
ORDER BY open_for DESC;
Enter fullscreen mode Exit fullscreen mode

Who is blocking whom:

SELECT pid, pg_blocking_pids(pid) AS blocked_by, query
FROM pg_stat_activity
WHERE cardinality(pg_blocking_pids(pid)) > 0;
Enter fullscreen mode Exit fullscreen mode

wait_event_type and wait_event tell you what a backend is waiting on: a lock, I/O, the client, and so on.

Other built-in statistics views

  • pg_stat_user_tables: sequential vs. index scans per table, plus dead row counts and the last time each table was vacuumed and analyzed.
  • pg_stat_user_indexes: how often each index is used.
  • pg_stat_io (Postgres 16+): I/O broken down by backend type and operation.

pg_top (external)

A top-style terminal tool for Postgres processes. It shows which backends are using CPU, what query each is running, and can show a query's plan. It isn't part of Postgres itself. Install it from your OS package manager (pg_top or pgtop).

PGTune (external)

A web-based calculator that suggests starting values for memory, WAL and parallelism settings from your RAM, CPU count, storage type and workload type. It isn't a Postgres tool, and its output is a starting point only. It doesn't know your queries or data. Use it to get away from the defaults, then tune with real measurements.

A practical order of operations

If you're facing a slow Postgres today:

  1. Turn on pg_stat_statements and slow-query logging. Find out what's actually slow.
  2. Run EXPLAIN ANALYZE on the top offenders. Most fixes are a missing index, stale statistics or a badly written query.
  3. Fix memory defaults (shared_buffers, effective_cache_size, then work_mem with care).
  4. Add PgBouncer if you have many connections.
  5. Batch writes and use COPY for loads.
  6. Partition large time-based tables once they get big.
  7. Add read replicas when reads outgrow a single server.

Measure before and after each change. A tuning change you can't measure is a guess.

What's the one change that made the biggest difference to your Postgres setup: an index, a memory setting, PgBouncer, or something else? And has a "best practice" ever made things worse for you? Share your stories in the comments, I'd love to hear what worked and what didn't.

References

Top comments (0)