PostgreSQL in production: performance, monitoring, WAL, scaling and restoring to a chosen minute
Application code can be deployed again, data cannot. This guide collects what is worth setting and watching in PostgreSQL 18: what WAL is, what to monitor, how to find slow queries, when and how to scale the database, and how to take backups that let you roll the database back to a chosen minute.
As of November 2026, PostgreSQL 18. Numbers in the examples are a starting point, not a recipe – check them against your own workload. Each part ends with links to the documentation it is based on.
WAL – the log everything else stands on
Every change goes first to the WAL (write-ahead log) and only later to the table files. After a crash the server replays from WAL whatever it had not written yet. The same log drives replication and point-in-time recovery, so it pays to understand how it works.
-
Segments and checkpoints
WAL is written into segment files (16 MB each by default) in the pg_wal directory. A checkpoint writes changed pages to the data files – after it, older segments are no longer needed for crash recovery. How often this happens is set by checkpoint_timeout (5 min by default) and max_wal_size (1 GB by default).
-
Checkpoints too often
If num_requested in pg_stat_checkpointer grows faster than num_timed, checkpoints are forced by WAL size, not by time. The server then writes the same pages again and again and adds full page images to WAL after every checkpoint. Raise max_wal_size. log_checkpoints is on by default and shows the same in the log.
-
synchronous_commit
On by default: a transaction is confirmed once its WAL is on disk. Setting it off speeds up writes, but after a server crash the last confirmed transactions may be lost (the database stays consistent). It can be switched off just for chosen transactions, such as logs or statistics: SET LOCAL synchronous_commit = off.
-
wal_compression
Compresses full page images written to WAL (lz4 or zstd if the server supports them). Less WAL to write, archive and send to replicas, at the cost of a little CPU. Off by default.
-
Page checksums
Since PostgreSQL 18 initdb enables data checksums by default, so a page damaged on disk is detected on read instead of silently ending up in a backup. Check with SHOW data_checksums; on an older cluster the pg_checksums tool turns them on offline.
Monitoring – what to watch and what to alert on
PostgreSQL collects its own statistics in the pg_stat_* views. All you have to do is read them regularly – best through an exporter to Prometheus, with charts and alerts – instead of looking into the database only when users report that "it's slow".
-
WAL archiving – pg_stat_archiver
Alert number one: failed_count and last_failed_time. While archiving is stuck, segments stay in pg_wal. When that disk fills up, PostgreSQL stops (PANIC) and will not start until you free space. Until then the backup cannot restore the newest data either.
-
The most expensive queries – pg_stat_statements
The extension adds up time, calls and reads for every query shape. It needs an entry in shared_preload_libraries and a restart. Sort by total_exec_time: it shows what really loads the database – often a cheap query called a million times, not a single slow one.
-
What is happening now – pg_stat_activity
Active sessions, their state and what they wait for (wait_event_type, wait_event). Look for "idle in transaction" sessions: they hold locks and hold back cleanup. idle_in_transaction_session_timeout limits them.
-
Locks – pg_locks
pg_blocking_pids(pid) shows who blocks a session. Set lock_timeout in migrations, so that an ALTER TABLE waiting for a lock does not stall all traffic behind it.
-
Cleanup – pg_stat_user_tables
n_dead_tup, last_autovacuum and last_autoanalyze. Many dead rows while autovacuum has not run for a long time is the first sign of table bloat and slowdown.
-
I/O and cache – pg_stat_io, pg_stat_database
Reads from memory (blks_hit) against reads from disk (blks_read), temporary files (temp_files) and I/O by process type. In PostgreSQL 18 pg_stat_io also covers WAL writes and reports sizes in bytes.
-
Replicas and slots – pg_stat_replication
Replica lag (replay_lag) and the state of slots in pg_replication_slots. An abandoned slot keeps WAL forever and can fill the disk – max_slot_wal_keep_size sets an upper limit.
-
Slow queries in the log
log_min_duration_statement (e.g. 500ms) logs every query longer than the threshold, and auto_explain adds its execution plan. The plan from the moment it was slow is worth more than one reproduced later.
-
Tools
postgres_exporter exposes the statistics to Prometheus, Grafana draws the charts. A minimal set of alerts: archiving, free space on the data and pg_wal disks, replica lag, connections close to max_connections, transactions open for many minutes, age of the oldest transaction.
Performance – from the query to the configuration
Fixing queries and indexes gives the most, server configuration comes next, and bigger hardware comes last. The order of work:
- Find what costs the most in pg_stat_statements – not by which screen someone complained about last.
- Run EXPLAIN (ANALYZE) on that query. In PostgreSQL 18 ANALYZE adds BUFFERS on its own, so you can see how many pages came from memory and how many from disk. Look for a gap between the estimated and the actual number of rows – usually stale statistics or a missing index.
- Add an index for the real filters and sort orders, with columns in the order of the conditions. In production: CREATE INDEX CONCURRENTLY, which does not block writes. PostgreSQL 18 uses multicolumn indexes more often thanks to skip scan, but a well-chosen index still wins.
- Run ANALYZE after a large import. After a major version upgrade, pg_upgrade in PostgreSQL 18 carries the planner statistics over, so the database does not start "cold".
- Every connection is a separate server process. Instead of raising max_connections into the hundreds, put a connection pool in front – PgBouncer in transaction mode or a pool in the application.
-
shared_buffers
PostgreSQL's own cache. On a dedicated server the documentation suggests starting at 25% of RAM; above 40% rarely helps, because the database also relies on the operating system cache. Changing it needs a restart.
-
effective_cache_size
A hint for the planner about how much data fits in cache (shared_buffers plus the system cache) – usually half to three quarters of RAM. It reserves nothing, it only changes the planner's decisions.
-
work_mem
Memory for one sort or hash table in one plan node. One query may use it several times, and there are many connections – raise it carefully. Growing temp_files in pg_stat_database show that sorts spill to disk.
-
random_page_cost
4.0 by default – an assumption of spinning disks. On SSD and NVMe it is usually lowered to about 1.1–1.5, so the planner uses indexes more readily.
-
io_method
PostgreSQL 18 has asynchronous I/O: worker by default, on Linux also io_uring if the server was built with it. It speeds up sequential scans, bitmap heap scans and VACUUM.
-
Autovacuum
By default VACUUM starts once 20% of a table has changed (autovacuum_vacuum_scale_factor = 0.2). For a table with hundreds of millions of rows that is too rare – set a smaller factor for that table with ALTER TABLE … SET (…). Never switch autovacuum off.
Scaling the database
The order matters: queries and indexes first, then a connection pool and a stronger machine, then read replicas and partitioning, and splitting data across servers at the very end.
-
Up – a stronger server
More RAM means more data in cache, fast NVMe disks mean shorter WAL writes and checkpoints. The simplest route, with no change to the application – and often enough for a long time.
-
Read replicas
A streaming replica replays WAL from the primary and, as a hot standby, takes read-only queries – reports, exports, search. It is asynchronous: data may lag by fractions of a second, so keep "read right after write" on the primary.
-
Synchronous replication
With synchronous_standby_names a commit waits for a replica: losing the primary does not lose confirmed data, but commits take longer. With a single synchronous replica its failure stops writes – which is why at least two are usually used, with ANY 1 (…).
-
Failover
PostgreSQL does not switch traffic to a replica by itself. Promotion (pg_promote) is done by a person or by a tool such as Patroni, which also makes sure two primaries never run at once.
-
Partitioning
Large tables of events, logs or measurements are split by date. Queries read only the partitions they need, and old data is removed with DETACH or DROP of a partition instead of an hours-long DELETE.
-
Logical replication
Moves chosen tables between servers, also between major versions. Useful for moving to a new version with a short break or for feeding a data warehouse.
-
Splitting across servers (sharding)
The last step, when one machine cannot keep up with writes – for example the Citus extension. It adds complexity to every query and every migration; business systems rarely need it.
Backups – three kinds, three different questions
A backup nobody has ever restored is only a hope. Before choosing a tool, settle two numbers: how much data you can afford to lose (RPO) and how long the database may be down (RTO).
-
Logical dump – pg_dump
A file with the contents of one database (pg_dumpall for roles and the whole cluster). Consistent and non-blocking; good for moving data, backing up a single database and crossing versions. The documentation says plainly that, except in simple cases, it is not the right way to back up production regularly: it restores only the moment of the dump, and for a large database it takes long.
-
Physical backup – pg_basebackup
A copy of the whole cluster from a running server – the basis of point-in-time recovery and of new replicas. Since PostgreSQL 17 also incremental backups (--incremental, needs summarize_wal = on), combined at restore time with pg_combinebackup.
-
WAL archive
A continuous copy of every completed WAL segment. Together with a physical backup it lets you restore the database to any moment between that backup and the last archived segment.
-
Tools instead of scripts
Instead of a hand-written archive_command people use pgBackRest, WAL-G or Barman: compression, encryption, storage in S3, parallel work, retention, backup verification and restoring to a chosen moment with one command.
-
RPO in practice
pg_dump once a day alone: you can lose up to a day of data. WAL archive with archive_timeout = 60: about a minute. Streaming WAL (a replica, pg_receivewal --synchronous): seconds or less. Synchronous replication: confirmed transactions are not lost.
-
The 3-2-1 rule
Three copies, on two different media, one off site. On top of that: a copy that cannot be deleted or overwritten from the database server (e.g. a bucket with object lock) – it protects against ransomware and an administrator's mistake.
A WAL archive every minute – the setup
Point-in-time recovery (PITR) needs two things: a physical backup and an unbroken WAL archive from the moment of that backup. How to set it up:
- In postgresql.conf keep wal_level = replica (the default), set archive_mode = on and an archiving command – archive_command or a tool (in pgBackRest: archive-push). Changing archive_mode needs a restart.
- Set archive_timeout = 60. A WAL segment goes to the archive only once it is full – with little traffic it could wait for hours. archive_timeout forces the segment closed every minute if anything happened in the database. The documentation calls "a minute or so" a reasonable value; shorter bloats the archive, because a forced segment is full size (it compresses well).
- The archiving command must return 0 only after the file is safely stored and must never overwrite an existing segment. Keep the archive off the database server.
- Take physical backups regularly – full or incremental. The older the base backup, the more WAL has to be replayed and the longer recovery takes.
- Watch pg_stat_archiver and free space in pg_wal. Any gap in the WAL archive cuts off the ability to restore everything after it.
# /etc/postgresql/18/main/postgresql.conf
wal_level = replica
archive_mode = on # needs a restart
archive_command = 'test ! -f /mnt/archive/%f && cp %p /mnt/archive/%f'
archive_timeout = 60 # a segment to the archive at least every minute
wal_compression = zstd
# or with pgBackRest:
# archive_command = 'pgbackrest --stanza=main archive-push %p'
Restoring to a chosen minute – step by step
Someone deleted data they should not have at 14:32? You restore a physical backup from before that moment and tell PostgreSQL to replay the WAL archive up to 14:31. Always on a copy – a new server or a new directory – never on the only copy of the data.
- Stop the server or prepare a new one. If you restore in place, move the old data directory somewhere safe – together with pg_wal, which may still hold segments that were not archived.
- Unpack the physical backup into an empty data directory (combine incremental backups with pg_combinebackup first). Remove from pg_wal the files that came with the backup (they are in the archive too), and copy back the unarchived segments from the old pg_wal.
- Set restore_command (where to fetch WAL from), recovery_target_time (the target moment, with a time zone) and recovery_target_action.
- Create an empty recovery.signal file in the data directory and start the server. PostgreSQL replays WAL up to the given moment.
- With recovery_target_action = 'pause' (the default) the server stops in read-only mode – check the data with a query. If the point is right, SELECT pg_wal_replay_resume(); ends recovery and opens the database for writes. If not – stop the server, adjust recovery_target_time and start again from step 2.
- After recovery the database starts a new timeline. Take a new physical backup straight away and check that archiving is running.
# postgresql.conf – recovery
restore_command = 'cp /mnt/archive/%f "%p"'
recovery_target_time = '2026-11-25 14:31:00+01'
recovery_target_action = 'pause'
# an empty file in the data directory
touch /var/lib/postgresql/18/main/recovery.signal
# checked? end recovery:
# SELECT pg_wal_replay_resume();
# the same with pgBackRest:
# pgbackrest --stanza=main --type=time --target-action=promote \
# --target="2026-11-25 14:31:00+01" restore
-
Only part of the data
When one table is gone and the rest of the database keeps working, restore to 14:31 on a separate server and move the missing rows over (pg_dump -t or a query). Rolling back the whole production database would erase everything written after 14:32.
Restore drills and a checklist
A backup is worth something only once someone has restored the database from it – and measured how long it took.
-
Regular drills
Automatically restore the latest backup on a separate server to a random moment and check it with a control query, e.g. the latest row in the orders table. The measured time is your real RTO.
-
Backup verification
pg_verifybackup checks a pg_basebackup backup against its manifest, pgBackRest has a verify command, and pg_amcheck finds damaged tables and indexes in a running database.
-
Encryption and access
Backups hold all the data, personal data included. Encrypt them and limit who can read and delete them – separately from access to the database itself.
-
Upgrades
Install minor releases (18.x) as they come – usually just a restart. A new major version: pg_upgrade (fast with --link, no data copy) or logical replication when the break must be minimal.
-
Documentation for your successor
Write down where the backups and the WAL archive are, how long they are kept, who can access them and what restoring looks like step by step. Failures tend to happen when the author of the setup is away.
Documentation
Tell us about your process
We reply within one working day. The first conversation about your process is free, and we prepare every quote individually.
Tell us about your process