When migrating a 100GB database from MySQL to PostgreSQL, I spent 3 days planning and 1 day executing. Everything went smoothly during the cutover. On the second day, when peak traffic hit, CPU load stayed low while disk I/O spiked through the roof. Queries occasionally stalled for 3–5 seconds.
Opening postgresql.conf, I realized the team had left the default settings untouched: shared_buffers at 128MB and work_mem at 4MB on a 64GB RAM server. PostgreSQL’s default configuration is designed to run even on a Raspberry Pi—it is definitely not built for production.
Don’t rush into tweaking a few numbers by guesswork. Before touching the config file of a live database, you need to understand the three common approaches below.
Comparing Approaches to PostgreSQL Configuration Tuning
When addressing performance at the PostgreSQL server layer, DevOps engineers typically follow one of three approaches:
- Approach 1: Keep default settings and scale up hardware. Whenever things slow down, upgrade to faster NVMe drives, add more vCPUs, and throw more RAM at the VM (e.g., upgrading from 16GB to 64GB RAM).
- Approach 2: Use an automated config generator (like PGTune). Plug in your RAM, CPU, storage type, and workload type (OLTP/OLAP), then paste the generated config block straight into
postgresql.conf. - Approach 3: Calculate a baseline and fine-tune for your workload. Start from safe baseline thresholds, then measure RAM usage, temp files, and disk write cycles to gradually tune
shared_buffers,work_mem, and Checkpoints.
Pros and Cons of Each Approach
1. Keeping Default Settings and Scaling Hardware
Operational safety is the biggest plus: no risk of a typo preventing PostgreSQL from starting, and no restart required. However, the cost is far too high. Because shared_buffers is capped at 128MB and work_mem is only 4MB, PostgreSQL constantly spills temporary files to disk during sorts or hash joins. You can upgrade to 128GB RAM, double your cloud bill, and still end up with terrible p99 latency.
2. Using Automated Tools Like PGTune
In just 30 seconds, PGTune gives you a configuration that gets you off the defaults. The problem is that these tools rely on static formulas and don’t understand your application’s specific query patterns. For example, with max_connections = 100, PGTune might suggest work_mem = 64MB. If your app frequently runs queries with 4 concurrent Sort/Hash Join operations, that alone can consume up to 25GB of RAM and trigger the OOM Killer.
3. Manual Tuning Based on Real Workload
To take this route, you need to understand how PostgreSQL allocates memory and writes WAL. Initial rollout takes longer because you have to monitor logs and metrics continuously. In return, you maintain tight control over peak RAM usage, eliminate checkpoint-induced stalls, and get the most out of the hardware you’re paying for.
Choosing the Right Approach for Production
The most practical strategy for production is combining Approach 2 and Approach 3. Use standard formulas as a baseline so the system runs reliably from day one. Then, manually tune the three core parameter groups—shared_buffers, work_mem, and Checkpoints—to match your OLTP or analytical reporting workload.
This article focuses strictly on PostgreSQL server internals. If your system is bottlenecked by too many concurrent connections, put PgBouncer in front of it. And if queries are slow due to missing indexes, inspect them individually using EXPLAIN ANALYZE.
Step-by-Step Guide to Tuning postgresql.conf
Suppose you have a typical production server: 32GB RAM, 8 vCPUs, NVMe storage, handling an OLTP workload of around 1,500–2,000 queries/second. The first step is to SSH into the machine to inspect available resources and current parameters:
# Check RAM and CPU core count
free -h
nproc
# Check the config file location and current settings in psql
sudo -u postgres psql -c "SHOW config_file;"
sudo -u postgres psql -c "SHOW shared_buffers; SHOW work_mem; SHOW effective_cache_size; SHOW max_wal_size;"
Don’t forget to back up the original file before editing so you can roll back in seconds if anything goes wrong:
sudo cp /etc/postgresql/16/main/postgresql.conf /etc/postgresql/16/main/postgresql.conf.bak
Step 1: Tune shared_buffers and effective_cache_size
PostgreSQL uses shared_buffers as its dedicated RAM area for caching frequently read and written data pages. Unlike MySQL InnoDB, which typically claims 70–80% of RAM for innodb_buffer_pool_size, PostgreSQL uses double buffering. Data passes through both shared_buffers and the Linux OS Page Cache.
Therefore, the sweet spot for shared_buffers is 25% of total RAM (i.e., 8GB on a 32GB machine). Setting it too high, such as 60–70%, starves the OS Page Cache and increases PostgreSQL’s internal memory management overhead.
Its companion parameter is effective_cache_size. It does not allocate actual RAM; instead, it tells the Query Planner how much total memory is available for caching (combining shared_buffers and the OS Page Cache) so it favors Index Scans over Sequential Scans. The recommended range is 50%–75% of total RAM (about 24GB on a 32GB machine).
# /etc/postgresql/16/main/postgresql.conf
shared_buffers = 8GB
effective_cache_size = 24GB
maintenance_work_mem = 1GB # Used for VACUUM and CREATE INDEX to speed up maintenance
Step 2: Configure work_mem Safely to Prevent OOM
Many newcomers mistakenly think work_mem is the RAM limit per connection. In reality, it is the maximum RAM allocated for each sort or hash table operation within a query. A complex SQL query with 4 ORDER BY or HASH JOIN operations on a single connection can consume up to 4 x work_mem.
Applying a safe formula for a 32GB RAM server with max_connections = 200:
- Subtract
shared_buffers(8GB) and OS overhead (4GB), leaving roughly 20GB. - Divide by (
max_connectionsx safety factor of 2.5):20,000MB / (200 * 2.5) = 40MB. - For a typical OLTP workload, setting
work_mem = 16MBor32MBis ideal.
For end-of-day reporting jobs that need to sort large datasets, never increase work_mem globally. Keep the safe value server-wide and raise it locally only within that job’s transaction:
-- Wrap in BEGIN/COMMIT so SET LOCAL takes effect and resets automatically afterward
BEGIN;
SET LOCAL work_mem = '256MB';
SELECT user_id, SUM(amount) FROM orders GROUP BY user_id ORDER BY SUM(amount) DESC;
COMMIT;
Step 3: Optimize Checkpoint Settings to Eliminate I/O Spikes
A checkpoint is when PostgreSQL flushes all dirty data pages from shared_buffers to disk and records a recovery point in the WAL. By default, max_wal_size is only 1GB and checkpoint_timeout is 5 minutes. Write-heavy systems hit that 1GB ceiling quickly, forcing PostgreSQL into frequent checkpoints and causing I/O bottlenecks.
For smoother disk writes, you need to space out checkpoints and spread out the write rate:
checkpoint_timeout = 15min
max_wal_size = 8GB
min_wal_size = 2GB
checkpoint_completion_target = 0.9
Setting checkpoint_completion_target = 0.9 instructs PostgreSQL to spread data flushing across 90% of the checkpoint_timeout interval, rather than dumping everything at once and freezing the system. Since PostgreSQL 14, this defaults to 0.9 (older versions defaulted to 0.5), though declaring it explicitly keeps your config consistent. Increasing checkpoint_timeout to 15 minutes slightly extends crash recovery time after an unexpected power loss, which is completely fine on modern NVMe drives.
Step 4: Apply the Configuration and Verify
Changes to work_mem and Checkpoint settings only require a reload to take effect. However, modifying shared_buffers requires a full PostgreSQL restart, so schedule it during off-peak hours:
# Reload dynamic parameters
sudo -u postgres psql -c "SELECT pg_reload_conf();"
# Restart PostgreSQL if shared_buffers was modified
sudo systemctl restart postgresql
# Check logs to confirm the service started normally
sudo tail -n 50 /var/log/postgresql/postgresql-16-main.log
After 1–2 days under real production load, check the ratio of forced checkpoints and the volume of temporary files generated:
-- On PostgreSQL 16 and earlier, check pg_stat_bgwriter (moved to pg_stat_checkpointer in PG 17+)
-- Ideally, checkpoints_timed should be much larger than checkpoints_req
SELECT checkpoints_timed, checkpoints_req FROM pg_stat_bgwriter;
-- Check the amount of temp files generated due to insufficient work_mem
SELECT datname, temp_files, pg_size_pretty(temp_bytes) AS temp_size
FROM pg_stat_database
WHERE datname NOT IN ('template0', 'template1');
If checkpoints_req is still higher than checkpoints_timed, increase max_wal_size further to 12GB or 16GB. And if temp_bytes grows large on a specific database, enable log_temp_files = 10240 (which logs temp files of 10MB or larger) for a few hours to catch the exact memory-hungry query and optimize it.

