General system state
A slow database server will typically be running out of:- cpu,
- memory or
- disk.
- top (press c to see the full command line): look at CPU and memory usage
- iostat -x -m 5: look at i/o wait and service time
If you see a lot of I/O, then try adjusting these settings:shared_buffers
work_mem
effective_cache_size
checkpoint_segments
autovacuum_naptime
wal_buffers
Finding slow queries
On the database side, start by determining whether:- there is one large query holding up all of the resources or
- the number of queries is the main problem.
Then fire up psql dbname and look at the currently executing queries:stats_command_string = on
(You can also add the procid column to the query if you want to map a query to the process ID you see in top.)SELECT usename, current_query, query_start
FROM pg_stat_activity;
If you can't get anything useful out of pg_stat_activity, you may want to enable slow query logging by adding this to your postgresql.conf:
(All queries which take more than 100 ms to execute will be printed to the main Postgres log file.)log_min_duration_statement = 100
Examining a particular query
Once you have identified a slow query, you can time it by running this command before executing the query manually:To get an idea of where Postgres spends its time when executing that query, look at the query plan:\timing
The numbers you see there are estimates. To run the query and get actual numbers, use this instead:EXPLAIN your_query;
If you still can't figure out why a certain query takes so long, have a look at the ratio between live and dead rows in the relevant tables:EXPLAIN ANALYZE your_query;
Having too many dead rows is often a sign of insufficient vacuuming. You might want to turn autovacuum on if it isn't already, or to make it a bit more aggressive by tweaking these settings:ANALYZE VERBOSE tablename;
autovacuum_vacuum_scale_factor
autovacuum_analyze_scale_factor
Troubleshooting database performance is a bit of a black art, many thanks to Mark Kirkwood for sharing his Postgres wisdom with me.
If there's anything else you have successfully used to find the cause of your performance woes, please feel free to leave a comment.

