How to Tune PostgreSQL Configuration for Better Performance
To tune
PostgreSQL configuration, edit the postgresql.conf file to adjust key parameters like shared_buffers, work_mem, and max_connections. After changes, reload the server with SELECT pg_reload_conf(); or restart PostgreSQL to apply the new settings.Syntax
The main PostgreSQL configuration file is postgresql.conf. You change settings by assigning values to parameters in this file. For example:
parameter_name = valuesets the parameter.- Values can be numbers, strings, or memory sizes (like '128MB').
- Comments start with
#and are ignored.
After editing, reload the config with SELECT pg_reload_conf(); or restart the server.
conf
# Example syntax in postgresql.conf shared_buffers = 256MB work_mem = 4MB max_connections = 100
Example
This example shows how to increase memory settings to improve query performance on a server with 4GB RAM.
conf and sql
# In postgresql.conf shared_buffers = 1GB work_mem = 16MB max_connections = 50 -- After saving, reload config in psql SELECT pg_reload_conf();
Output
pg_reload_conf
--------------
t
(1 row)
Common Pitfalls
Common mistakes when tuning PostgreSQL include:
- Setting
shared_bufferstoo high (over 25% of system RAM) can cause OS swapping and slow performance. - Setting
work_memtoo large can exhaust memory if many queries run simultaneously. - Changing parameters without reloading or restarting means changes won't apply.
- Ignoring
max_connectionscan lead to resource exhaustion.
conf
# Wrong: setting shared_buffers too high shared_buffers = 8GB # On a 4GB RAM machine, this is too high # Right: balanced setting shared_buffers = 1GB
Quick Reference
| Parameter | Description | Recommended Setting |
|---|---|---|
| shared_buffers | Memory PostgreSQL uses for caching data | 25% of system RAM |
| work_mem | Memory for internal sort operations per query | 4MB to 64MB depending on workload |
| max_connections | Maximum concurrent connections allowed | Set based on expected users, e.g., 50-100 |
| effective_cache_size | Estimate of OS disk cache available | 50% to 75% of system RAM |
| maintenance_work_mem | Memory for maintenance tasks like VACUUM | 64MB to 512MB |
Key Takeaways
Edit postgresql.conf to tune key parameters like shared_buffers and work_mem.
Do not set shared_buffers higher than 25% of your system RAM to avoid swapping.
Reload configuration with SELECT pg_reload_conf(); or restart PostgreSQL to apply changes.
Adjust max_connections carefully to prevent resource exhaustion.
Use effective_cache_size to help PostgreSQL optimize query plans based on available OS cache.