Tune key PostgreSQL settings like shared_buffers (25% of RAM), effective_cache_size (50–75% of RAM), work_mem (start at 16MB), maintenance_work_mem (e.g., 1GB), wal_buffers (16MB), max_wal_size (2GB), checkpoint_completion_target (0.9), and random_page_cost (1.1 for SSDs), then reload PostgreSQL. 2. Optimize the Linux system by using XFS or ext4 with noatime,barrier=1, setting the I/O scheduler to deadline or none for SSDs, tuning vm.dirty_ratio (15) and vm.dirty_background_ratio (5), and optionally enabling huge pages. 3. Maintain database health by enabling autovacuum with adjusted scale factors, indexing frequently queried columns without over-indexing, updating statistics, reindexing bloated tables, and partitioning large tables. 4. Monitor performance using pg_stat_statements to identify slow queries, enable slow query logging (log_min_duration_statement = 1000), and use external tools like pgBadger or Grafana for visualization, then iterate based on observed workload to achieve optimal performance.
Optimizing a PostgreSQL database on a Linux server isn't about one magic setting—it's a combination of configuration tuning, system-level adjustments, and good database design. Here’s a practical guide focused on real-world improvements you can implement today.

1. Tune Key PostgreSQL Configuration Settings
The main configuration file, usually postgresql.conf
, holds the most impactful tuning knobs. Focus on these parameters:
-
shared_buffers: This sets how much memory PostgreSQL uses for caching data. A common recommendation is 25% of total system RAM. For a 16GB server, set:
shared_buffers = 4GB
effective_cache_size: Tells the query planner how much memory is available for disk caching (by OS and PostgreSQL). It doesn’t allocate memory but influences query plans. Set it to about 50–75% of total RAM:
effective_cache_size = 12GB
work_mem: Controls memory per sorting or hashing operation. Too high can cause memory overuse with many concurrent queries. Start with:
work_mem = 16MB
Increase only if you have complex sorts and sufficient RAM.
maintenance_work_mem: Used for vacuuming, index creation, etc. Can be much higher:
maintenance_work_mem = 1GB
wal_buffers: Should typically be 1/32nd of
shared_buffers
, but 16MB is often sufficient:wal_buffers = 16MB
checkpoint_segments / max_wal_size (depends on version): Increase to reduce I/O spikes from frequent checkpoints:
max_wal_size = 2GB
checkpoint_completion_target: Spread checkpoint writes over time to reduce I/O bursts:
checkpoint_completion_target = 0.9
random_page_cost: If using SSDs, lower this to reflect faster random access:
random_page_cost = 1.1
After changes, reload or restart PostgreSQL:
sudo systemctl reload postgresql
2. Optimize the Linux System for PostgreSQL
PostgreSQL runs on Linux, so system-level settings matter.
File System: Use XFS or ext4 with appropriate mount options. For example:
/dev/sdX /var/lib/postgresql xfs noatime,barrier=1 0 0
noatime
reduces disk writes;barrier=1
ensures WAL integrity.I/O Scheduler: For SSDs, use
deadline
ornone
(for NVMe). Check current:cat /sys/block/sda/queue/scheduler
Set temporarily:
echo deadline | sudo tee /sys/block/sda/queue/scheduler
vm.dirty_ratio and vm.dirty_background_ratio: Control how aggressively the kernel flushes dirty pages. High values can cause I/O stalls. Tune down if you see write spikes:
vm.dirty_ratio = 15 vm.dirty_background_ratio = 5
Apply via
/etc/sysctl.conf
and reload:sudo sysctl -p
Huge Pages (optional): Can improve performance with large
shared_buffers
. Enable inpostgresql.conf
:huge_pages = on
And ensure kernel supports it (
vm.nr_hugepages
in sysctl).
3. Maintain Database Health
Even the best config can't fix a bloated or poorly indexed database.
Vacuum regularly: Especially
autovacuum
. Ensure it's enabled:autovacuum = on
Tune for busy tables:
autovacuum_vacuum_scale_factor = 0.05 autovacuum_analyze_scale_factor = 0.02
Index wisely: Use
EXPLAIN (ANALYZE, BUFFERS)
to find slow queries. Add indexes on frequently filtered or joined columns. But avoid over-indexing—each index slows down writes.Update statistics: Ensure
ANALYZE
runs regularly so the planner makes good decisions.Reindex occasionally: Indexes can bloat. Schedule periodic reindexing during maintenance:
REINDEX TABLE my_large_table;
Partition large tables: If you have tables over tens of millions of rows, consider partitioning by date or ID to improve query speed and maintenance.
4. Monitor and Iterate
Use tools to spot bottlenecks:
pg_stat_statements: Enable to track slow queries:
shared_preload_libraries = 'pg_stat_statements' pg_stat_statements.track = all
Then:
SELECT query, calls, total_time FROM pg_stat_statements ORDER BY total_time DESC LIMIT 10;
Logging: Turn on slow query logging:
log_min_duration_statement = 1000 # Log queries > 1s log_statement = 'none' log_temp_files = 0 # Log all temp file usage
External tools: Use
pgBadger
,Prometheus Grafana
, orpgAdmin
to visualize performance over time.
Tuning PostgreSQL is iterative. Start with configuration and system settings, then refine based on actual workload. Most gains come from fixing slow queries and ensuring proper maintenance—not just cranking up memory settings.
Basically: configure wisely, maintain consistently, and monitor constantly.
The above is the detailed content of Optimizing a PostgreSQL Database on a Linux Server. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

LXD is described as the next-generation container and virtual machine manager that offers an immersive for Linux systems running inside containers or as virtual machines. It provides images for an inordinate number of Linux distributions with support

Firefox browser is the default browser for most modern Linux distributions such as Ubuntu, Mint, and Fedora. Initially, its performance might be impressive, however, with the passage of time, you might notice that your browser is not as fast and resp

When encountering DNS problems, first check the /etc/resolv.conf file to see if the correct nameserver is configured; secondly, you can manually add public DNS such as 8.8.8.8 for testing; then use nslookup and dig commands to verify whether DNS resolution is normal. If these tools are not installed, you can first install the dnsutils or bind-utils package; then check the systemd-resolved service status and configuration file /etc/systemd/resolved.conf, and set DNS and FallbackDNS as needed and restart the service; finally check the network interface status and firewall rules, confirm that port 53 is not

If you find that the server is running slowly or the memory usage is too high, you should check the cause before operating. First, you need to check the system resource usage, use top, htop, free-h, iostat, ss-antp and other commands to check CPU, memory, disk I/O and network connections; secondly, analyze specific process problems, and track the behavior of high-occupancy processes through tools such as ps, jstack, strace; then check logs and monitoring data, view OOM records, exception requests, slow queries and other clues; finally, targeted processing is carried out based on common reasons such as memory leaks, connection pool exhaustion, cache failure storms, and timing task conflicts, optimize code logic, set up a timeout retry mechanism, add current limit fuses, and regularly pressure measurement and evaluation resources.

As a system administrator, you may find yourself (today or in the future) working in an environment where Windows and Linux coexist. It is no secret that some big companies prefer (or have to) run some of their production services in Windows boxes an

Frankly speaking, I cannot recall the last time I used a PC with a CD/DVD drive. This is thanks to the ever-evolving tech industry which has seen optical disks replaced by USB drives and other smaller and compact storage media that offer more storage

In Linux systems, 1. Use ipa or hostname-I command to view private IP; 2. Use curlifconfig.me or curlipinfo.io/ip to obtain public IP; 3. The desktop version can view private IP through system settings, and the browser can access specific websites to view public IP; 4. Common commands can be set as aliases for quick call. These methods are simple and practical, suitable for IP viewing needs in different scenarios.

Built on Chrome’s V8 engine, Node.JS is an open-source, event-driven JavaScript runtime environment crafted for building scalable applications and backend APIs. NodeJS is known for being lightweight and efficient due to its non-blocking I/O model and
