Sub topic 11
Tuning memory and storage
This chapter assumes you can install and run PostgreSQL or MySQL, edit their configuration files, and restart the service with systemctl. It also assumes you know what RAM, swap and a filesystem are. The goal is to size the main memory settings for the host and place storage sensibly. You will not need to tune every parameter.
The working model
A database server uses memory in three ways:
- A shared cache holds table and index pages so reads avoid the disk.
- Per-connection or per-operation memory handles sorts, joins and hashes.
- The operating system's page cache holds file data that the database reads and writes.
Tuning means giving the shared cache enough space without starving the other two. If the total demand exceeds physical RAM, the host swaps or the kernel's out-of-memory (OOM) killer ends the database process. Both are worse than a slightly small cache.
Sizing PostgreSQL memory
PostgreSQL relies on both its own cache and the OS page cache. The main settings are in postgresql.conf.
| Setting | What it controls | Starting point |
|---|---|---|
| `shared_buffers` | Shared page cache, allocated at start | About 25% of RAM |
| `effective_cache_size` | Planner's estimate of total cache available, not an allocation | 50% to 75% of RAM |
| `work_mem` | Memory per sort or hash operation, per query node | 4 MB to 64 MB |
| `maintenance_work_mem` | Memory for VACUUM, CREATE INDEX and similar | 256 MB to 1 GB |
For a dedicated host with 16 GB of RAM, a reasonable starting configuration is:
# postgresql.conf
shared_buffers = 4GB
effective_cache_size = 12GB
work_mem = 16MB
maintenance_work_mem = 512MBshared_buffers needs a restart. The other three can be reloaded.
work_mem is the setting that most often causes trouble. It applies to each sort or hash operation, not to each connection. A single complex query can use several multiples of it, and many connections can run such queries at once. A rough worst case is work_mem times the number of operations times the number of active connections. With 200 connections and 64 MB, a burst of heavy queries can consume far more memory than the host has. Keep the global value modest. Raise it for one session or one role when a specific job needs it:
-- Raise work_mem for one reporting role only
ALTER ROLE report_user SET work_mem = '128MB';
-- Or for the current session
SET work_mem = '256MB';Sizing MySQL memory
MySQL with the InnoDB storage engine keeps most of its caching in one place, the buffer pool. InnoDB reads files in a way that can also fill the OS page cache, so the pool is usually sized larger than PostgreSQL's cache.
| Setting | What it controls | Starting point |
|---|---|---|
| `innodb_buffer_pool_size` | Cache for data and index pages | 50% to 70% of RAM on a dedicated host |
| `innodb_log_file_size` or `innodb_redo_log_capacity` | Size of the redo log | Large enough for roughly an hour of writes |
| `sort_buffer_size`, `join_buffer_size` | Per-connection buffers | Leave at defaults unless measured |
| `max_connections` | Upper bound on client sessions | Match your pooling plan |
# MySQL configuration file, [mysqld] section
[mysqld]
innodb_buffer_pool_size = 10G
innodb_redo_log_capacity = 4Ginnodb_redo_log_capacity exists in MySQL 8.0.30 and later. Older versions use innodb_log_file_size. In MySQL 5.7 and early 8.0 the log size needed a restart. In recent 8.0 versions both the buffer pool and the redo log capacity can be changed at runtime with SET GLOBAL.
Do not set the per-connection buffers to large values globally. Like work_mem, they are multiplied by the number of connections.
Checking that the cache is effective
Measure before and after changing anything. A cache hit ratio near 99% on a steady workload suggests the cache is large enough for the hot data.
-- PostgreSQL: buffer cache hit ratio per database
SELECT datname,
round(100.0 * blks_hit / nullif(blks_hit + blks_read, 0), 2) AS hit_pct
FROM pg_stat_database
WHERE datname = 'appdb';-- MySQL: how often InnoDB had to read from disk
SHOW GLOBAL STATUS LIKE 'Innodb_buffer_pool_read%';In MySQL, compare Innodb_buffer_pool_reads (reads that went to disk) with Innodb_buffer_pool_read_requests (all logical reads). A ratio that stays small means the pool is working.
A low hit ratio does not always mean the cache is too small. A one-time scan of a large table also lowers it. Look at the ratio during normal load, not right after a restart, because the cache starts empty and warms up over time.
Swap, the OOM killer and huge pages
Database hosts should avoid swapping hot cache pages. Set a low swappiness value, but keep some swap so the kernel has a safety valve:
sudo sysctl vm.swappiness=10
echo 'vm.swappiness = 10' | sudo tee /etc/sysctl.d/90-database.confOn PostgreSQL hosts, also consider vm.overcommit_memory = 2 with an appropriate vm.overcommit_ratio. This makes the kernel refuse allocations that it cannot back, so a failed allocation produces a clean database error rather than an OOM kill. Test this setting carefully, because a wrong ratio can cause allocation failures at normal load.
Huge pages reduce the memory-management overhead for large caches. PostgreSQL uses them when huge_pages = try (the default) and the kernel has enough reserved. This matters mostly when shared_buffers is many gigabytes.
Storage basics
Storage affects database speed as much as memory does. Keep these points in view:
- Use SSD or NVMe storage for the data directory when you can. Random reads and writes dominate database workloads.
- Put the data on a dedicated filesystem such as
/var/lib/postgresqlor/var/lib/mysql. A full root filesystem then does not stop the database, and a full data volume does not stop the whole host. - Use ext4 or XFS. Both are well supported. Avoid network filesystems for the data directory unless the vendor documents them.
- Mount with
noatimeto skip access-time writes on every read. - Put the write-ahead log (WAL) in PostgreSQL, or the redo log in MySQL, on fast storage. These logs take synchronous writes, so latency here limits commit speed.
An example /etc/fstab line for a dedicated data volume:
# /etc/fstab
UUID=3f8a1c2e-0000-4d2b-9a11-5b7e2c9d1a10 /var/lib/postgresql xfs defaults,noatime 0 2Check disk space and I/O regularly:
df -h /var/lib/postgresql
iostat -x 5 3In iostat, sustained high %util together with high await indicates the disk is the bottleneck. More memory or faster storage then helps more than any setting.
Durability settings you should not trade away
Both engines can run faster if you relax durability. In PostgreSQL, fsync = off or synchronous_commit = off and in MySQL innodb_flush_log_at_trx_commit = 0 or 2 and sync_binlog = 0 reduce the flush work per commit. They also risk losing recent transactions, or corrupting the data in the case of fsync = off, after a crash or power failure. Keep the defaults for data you cannot recreate. Use relaxed settings only for disposable data, such as a test copy that you reload from a dump.
Applying and verifying changes
- Back up the current configuration file.
- Change one group of settings at a time.
- Reload or restart as required. Check the log for errors on startup.
- Confirm the running value, then watch the hit ratio and memory use under real load.
sudo systemctl restart postgresql
sudo -u postgres psql -c 'SHOW shared_buffers;'
free -hFor MySQL, use mysql -e "SHOW VARIABLES LIKE 'innodb_buffer_pool_size'". MySQL reports the value in bytes.
Common errors
- The server fails to start after raising
shared_buffers. The request exceeds the kernel's shared memory limits or available RAM. Check the log withjournalctl -u postgresqland lower the value. - MySQL is killed by the OOM killer. The buffer pool plus per-connection buffers times
max_connectionsexceeded RAM. Lower the pool or the connection count, and use connection pooling. - Queries are slow after a restart. The cache is empty. Wait for it to warm, or use the warm-up features each engine provides.
- Setting
effective_cache_sizetoo high and expecting more memory use. It allocates nothing. It only changes the planner's cost estimates. - Changing a setting in the file but seeing the old value. The setting needs a restart, or the file you edited is not the one the server reads. Confirm with
SHOW config_file;in PostgreSQL.
Exercise
A PostgreSQL host has 32 GB of RAM and allows 300 connections. The administrator sets work_mem to 256MB globally to speed up a nightly report, and the server begins to hit the OOM killer during busy periods. Explain why this happens and give a better configuration.
Show answer
workmem applies to each sort or hash operation inside each query, so one query can use several multiples of it, and many connections can do this at once. With 300 connections, the potential demand is far above 32 GB. A better configuration keeps the global workmem modest (for example 16MB), sets sharedbuffers to about 8GB, and raises workmem only for the reporting role with ALTER ROLE reportuser SET workmem = '256MB'. Reducing max_connections and adding connection pooling also lowers the worst-case total.
Exercise
You have a dedicated MySQL host with 24 GB of RAM. Which value would you choose for innodbbufferpool_size as a starting point, and how would you check whether it is large enough?
Show answer
Start at about 50% to 70% of RAM, for example 14G to 16G. Under normal load, compare Innodbbufferpoolreads with Innodbbufferpoolread_requests from SHOW GLOBAL STATUS. If disk reads stay a very small fraction of logical read requests, the pool is large enough. If the ratio is poor and the host still has free memory, raise the pool.