Guest mode. You can read posts without signing up. Comments, ratings, job contacts and your own posts open after you sign up and accept the rules. What is Kommit →

Редакция КоммитРедакция портала
commit a5e50b0 · 15 days ago

PostgreSQL, Part 2: Tuning Memory, Disk, Autovacuum, and Connections, PgBouncer Pool

🌐 Machine-translated from Russian. Show original

In this part:

Why the default settings don't work#

postgresql.conf by default is designed so that PostgreSQL runs on any computer, even on a Raspberry Pi: 128 MB for cache, careful disk settings. On a server with 32 GB of memory, this leaves most resources unused.

Procedure: first basic calculation using the formulas below, then measurements (part 5) and spot adjustment. Do not copy other people's configs from the internet entirely.

Memory: basic calculation#

Example for a dedicated database server: 32 GB RAM, 8 cores, NVMe, up to 200 connections, mixed load (OLTP).

ParameterRuleExample
shared_buffers~25 % RAM8GB
effective_cache_size~50–75% RAM (scheduler prompt, memory does not allocate)24GB
work_memper sort/hash operation; (RAM − shared_buffers) / (max_connections × 2–4)32MB
maintenance_work_memfor VACUUM, CREATE INDEX; 1–2 GB on large1GB
huge_pagestry by default; enable huge pages in the OS for shared_buffers from 8 GBtry

⚠️ work_mem is allocated to each operation in the query, and there are many queries. A complex report can take work_mem a dozen times. A modest global value is better and a higher value is pointwise for the report role: ALTER ROLE report SET work_mem = '256MB';.

An online calculator that calculates by the same principles is pgtune.leopard.in.ua. Use it as a starting point.

Disc and WAL#

Parameterfor SSD/NVMeWhy
random_page_cost1.1default is 4 — designed for HDD, which prevents the scheduler from indexing
effective_io_concurrency200how many parallel disk requests are allowed
max_wal_size4GB``16GBless often, checkpoints — record
min_wal_size1GB
checkpoint_completion_target0.9 (default)extends the checkpoint record
wal_compressionzstdless WAL — less load on disk, backups, and replicas

PostgreSQL 18 introduced an asynchronous I/O subsystem (io_method, default worker). The default value is reasonable; the io_uring option is only available on Linux when built with liburing support — change it only if you have measured the gain.

Ready-made settings file#

sudo tee /etc/postgresql/18/main/conf.d/20-tuning.conf >/dev/null <<'EOF'
# память (32 ГБ RAM)
shared_buffers = 8GB
effective_cache_size = 24GB
work_mem = 32MB
maintenance_work_mem = 1GB

# диск (NVMe)
random_page_cost = 1.1
effective_io_concurrency = 200
max_wal_size = 8GB
min_wal_size = 1GB
wal_compression = zstd

# параллельные запросы (8 ядер)
max_worker_processes = 8
max_parallel_workers = 8
max_parallel_workers_per_gather = 2
max_parallel_maintenance_workers = 2

# журналы: медленные запросы и полезные события
log_min_duration_statement = 1000
log_checkpoints = on
log_lock_waits = on
log_temp_files = 0
log_autovacuum_min_duration = 10s
EOF
sudo systemctl restart postgresql@18-main

Check which values have been applied and which ones are waiting to be restarted:

SELECT name, setting, unit, source, pending_restart
FROM pg_settings
WHERE source NOT IN ('default', 'override')
ORDER BY name;

Autovacuum: why it shouldn't be turned off#

PostgreSQL does not overwrite rows in place: UPDATE and DELETE leave "dead" versions of rows. VACUUM frees up this space, and ANALYZE updates statistics for the scheduler. Autovacuum does this in the background.

If it is turned off or cannot keep up:

  • tables and indices "bloat," queries slow down;
  • the planner makes mistakes due to outdated statistics;
  • in the worst case — the transaction counter overflows (wraparound), and the database stops accepting the record until VACUUM is executed.

Settings for the loaded base:

sudo tee /etc/postgresql/18/main/conf.d/30-autovacuum.conf >/dev/null <<'EOF'
autovacuum_max_workers = 5
autovacuum_naptime = 30s
autovacuum_vacuum_scale_factor = 0.05     # по умолчанию 0.2 — для больших таблиц слишком редко
autovacuum_analyze_scale_factor = 0.02
autovacuum_vacuum_cost_limit = 2000       # на SSD можно чистить быстрее
EOF

For a separate huge table — its own values:

ALTER TABLE events SET (autovacuum_vacuum_scale_factor = 0.01, autovacuum_vacuum_threshold = 10000);

In PostgreSQL 18, the number of autovacuum workers can be changed without restarting (within autovacuum_worker_slots), and the autovacuum_vacuum_max_threshold parameter limits the threshold for very large tables.

Connections: why 1000 is a bad idea#

Each connection in PostgreSQL is a separate process with its own memory. Hundreds of idle connections eat up memory and slow down performance. Guideline: about 2–4 active queries per kernel at the same time. If applications need more connections — set up a pool.

PgBouncer: A Pool of Connections#

PgBouncer is a lightweight pooler: applications open as many connections as you want, and it maintains a small pool of connections to PostgreSQL. The current version as of November 2026 is 1.26.1, available in the PGDG repository.

sudo apt install -y pgbouncer

/etc/pgbouncer/pgbouncer.ini:

[databases]
appdb = host=127.0.0.1 port=5432 dbname=appdb

[pgbouncer]
listen_addr = 192.168.1.21
listen_port = 6432
auth_type = scram-sha-256
auth_file = /etc/pgbouncer/userlist.txt
pool_mode = transaction
max_client_conn = 2000
default_pool_size = 20
admin_users = dba

The userlist.txt file contains the password role and hash (not the password itself). Get the hash:

sudo -u postgres psql -At -c "SELECT '\"' || rolname || '\" \"' || rolpassword || '\"' FROM pg_authid WHERE rolname IN ('app','dba');" \
  | sudo tee /etc/pgbouncer/userlist.txt >/dev/null
sudo chown postgres:postgres /etc/pgbouncer/userlist.txt && sudo chmod 640 /etc/pgbouncer/userlist.txt
sudo systemctl restart pgbouncer

The application now connects to port 6432. Don't forget the string in pg_hba.conf for 127.0.0.1 (it's from part 1) and the ufw rule for port 6432.

| Mode pool_mode | When a Connection Returns to the Pool | | Restrictions
| --- | --- | --- |
| session | when disconnecting the client | safe for everyone, but the savings are less |
| transaction | after each transaction | best savings; be careful with session items: SET, timetables, advisory locks, |
| statement | after each request | multi-operator transactions are prohibited |

Pool statistics:

psql -h 192.168.1.21 -p 6432 -U dba pgbouncer -c "SHOW POOLS;"

💡 For 1C, PgBouncer is usually not needed: the 1C server automatically maintains the pool of connections to the DBMS, and the transaction mode conflicts with temporary tables actively used by the platform. Specific postgresql.conf settings for 1C are in the PostgreSQL step in the "1C Server on Windows and Linux" series.

Linux kernel#

sudo tee /etc/sysctl.d/90-postgresql.conf >/dev/null <<'EOF'
vm.swappiness = 1
vm.overcommit_memory = 2
vm.overcommit_ratio = 90
EOF
sudo sysctl --system

overcommit_memory = 2 protects against a situation where the OOM killer kills the PostgreSQL process. Enable it consciously and check that there are no other programs on the server that need an "optimistic" overcommit.

Server configured — now the most important: PostgreSQL, part 3: backup — pg_dump, pg_basebackup, pgBackRest, and point-in-time recovery.

Comments 00 участников · 0 гостей🔒 Rate and discuss after signing up

Comments · 0

No comments yet.Sign in to comment, rate and see all comments.