Sub topic 14
Operating system settings: overcommit and swap
This chapter covers the Linux kernel settings that decide what happens when PostgreSQL asks for more memory than the machine can give. It assumes you have read the earlier chapters on work_mem, shared_buffers, and memory budgeting across connections. It also assumes you can use a Linux shell with sudo and sysctl. Other operating systems have different knobs, so the commands below are Linux-specific.
Why the operating system matters
PostgreSQL settings only control how much memory the server asks for. The kernel decides whether the request succeeds, and what to do when physical memory runs out. Two mechanisms dominate:
- Overcommit controls whether the kernel promises more virtual memory than it can back with RAM and swap.
- Swap is disk space the kernel uses to hold memory pages that are not currently needed in RAM.
If these are left at defaults on a busy server, the usual failure is the OOM killer. This is a kernel routine that picks a process and sends it SIGKILL when memory is exhausted. In the PostgreSQL log it looks like this:
LOG: server process (PID 12345) was terminated by signal 9: Killed
LOG: terminating any other active server processesWhen any backend dies from a signal, the postmaster assumes shared memory may be corrupt. It disconnects every session and runs crash recovery. One OOM kill therefore becomes a full restart for all clients.
How overcommit works
By default, Linux uses heuristic overcommit. malloc() usually succeeds even when the request is large, because pages are only assigned when a process first touches them. Memory can then run out later, at the moment of use, and the OOM killer is the only way out.
The setting vm.overcommit_memory has three values:
| Value | Name | Behavior |
|---|---|---|
| 0 | Heuristic (default) | Refuses only obviously absurd single requests. Total commitments can far exceed RAM plus swap. |
| 1 | Always | Never refuses. Not suitable for a database server. |
| 2 | Strict | Refuses allocations once total committed memory would exceed `CommitLimit`. |
The PostgreSQL documentation recommends mode 2 for dedicated database servers. With strict mode, an over-large request makes malloc() return an error. PostgreSQL reports that as an ordinary query error, and only that one query fails:
ERROR: out of memory
DETAIL: Failed on request of size 268435456.The other sessions keep running. A failed query is much better than a restarted server.
Computing the limit
In mode 2 the limit is:
CommitLimit = (RAM - reserved huge pages) * overcommit_ratio / 100 + swapThe default vm.overcommit_ratio is 50. On a 64 GB machine with 8 GB of swap, that gives 32 + 8 = 40 GB. PostgreSQL would be refused memory long before the machine is full, which is why you must raise the ratio when you switch to mode 2. With a ratio of 80, the same machine has 51.2 + 8 = 59.2 GB.
You can set vm.overcommit_kbytes instead of the ratio to give an absolute number. If one is set, the other is ignored.
flowchart TD
A[Process requests memory] --> B{overcommit_memory}
B -->|0 heuristic| C[Granted unless absurdly large]
B -->|1 always| D[Always granted]
B -->|2 strict| E{Committed_AS + request > CommitLimit?}
E -->|Yes| F[malloc fails: ERROR out of memory]
E -->|No| G[Granted]
C --> H{RAM exhausted when pages are touched?}
D --> H
G --> H
H -->|Yes, modes 0 and 1| I[OOM killer sends SIGKILL]
H -->|Rarely, mode 2| J[Memory is already accounted for]caption: How the three overcommit modes handle a memory request and where each one fails alt: Flowchart showing that modes 0 and 1 grant requests and may later trigger the OOM killer, while mode 2 checks the commit limit and fails the allocation with a normal error.
Checking and setting the values
Read the current state first:
sysctl vm.overcommit_memory vm.overcommit_ratio vm.swappiness
grep -E 'CommitLimit|Committed_AS|MemTotal|SwapTotal' /proc/meminfoCommitted_AS is how much memory the kernel has promised in total. In mode 2, if it sits close to CommitLimit under normal load, you have no headroom and queries will start failing. Check it at your busiest time, not at idle.
To persist the settings across reboots, write a file in /etc/sysctl.d/ and load it:
# /etc/sysctl.d/30-postgresql.conf
vm.overcommit_memory = 2
vm.overcommit_ratio = 80
vm.swappiness = 10sudo sysctl --systemProtecting the postmaster from the OOM killer
If you keep mode 0, or cannot use strict mode (for example because the host is shared), protect the main process instead. The kernel picks its victim by oom_score, which you can bias per process with oom_score_adj. The range is -1000 (never kill) to 1000.
The recommended pattern is to protect the postmaster only. The backends it forks should keep a normal score so the kernel kills a single backend rather than the parent. PostgreSQL supports this through two environment variables. On a systemd host, add a drop-in with sudo systemctl edit postgresql:
[Service]
OOMScoreAdjust=-1000
Environment=PG_OOM_ADJUST_FILE=/proc/self/oom_score_adj
Environment=PG_OOM_ADJUST_VALUE=0OOMScoreAdjust sets the value for the postmaster. At each fork, PostgreSQL writes PG_OOM_ADJUST_VALUE into PG_OOM_ADJUST_FILE, so every child process returns to 0. Restart the service, then verify:
PM=$(head -1 "$(psql -Atc 'SHOW data_directory')/postmaster.pid")
cat /proc/$PM/oom_score_adjRun that as a user that can read the data directory. The output should be -1000. A backend's PID, from pg_stat_activity, should show 0.
Containers
Inside a container, the kernel enforces the cgroup memory limit, not the host's RAM. A container with a 4 GB limit gets OOM-killed at 4 GB even if the host has 128 GB free. Size shared_buffers, work_mem, and max_connections against the container limit. Do not use the host's total memory. The /proc/meminfo inside a container often shows the host's values, so do not size from it.
Swap
Swap lets the kernel move rarely used pages to disk. For a database server it has two sides:
- A small amount of swap gives the kernel somewhere to put idle pages, such as memory of long-idle backends, which leaves more RAM for the page cache.
- Heavy swapping is a disaster. A backend whose pages were swapped out stalls on disk reads while holding locks. Latency rises by orders of magnitude, and other sessions queue behind it.
vm.swappiness (0 to 100, default 60) sets how eagerly the kernel swaps anonymous memory instead of dropping page cache. For a dedicated PostgreSQL host, a low value such as 1 to 10 is common. This makes the kernel drop file cache first. It does not disable swap, so the safety net remains.
Avoid disabling swap completely on hosts that use heuristic overcommit. Without swap, the first real shortage goes straight to the OOM killer, with no slow period to warn you. In strict mode, swap is part of CommitLimit, so removing it also lowers that limit.
Detecting swap trouble
Watch the swap-in and swap-out columns:
vmstat 5Sustained non-zero si and so values mean the machine is actively swapping. A steady, small amount of used swap with si and so at zero is harmless. Those pages are idle and are not hurting you.
Putting it together with the memory budget
The budget from the earlier chapter predicts how much memory PostgreSQL may use:
SELECT pg_size_pretty(
(8::bigint * 1024 * 1024 * 1024) -- shared_buffers
+ (200::bigint * 64 * 1024 * 1024 * 2) -- connections * work_mem * 2 nodes
+ (4::bigint * 1024 * 1024 * 1024) -- maintenance and autovacuum workers
) AS worst_case;This returns about 37 GB. Compare that figure to CommitLimit under strict mode, or to physical RAM minus page-cache headroom under heuristic mode. If the worst case is larger, lower max_connections or work_mem, or add RAM. Do not rely on the kernel to absorb the gap.
Recommended starting points
| Situation | overcommit_memory | swappiness | Extra protection |
|---|---|---|---|
| Dedicated server | 2, with a ratio checked against `Committed_AS` | 1 to 10 | Not needed |
| Shared host | 0 | 10 | Postmaster `oom_score_adj` of -1000 |
| Container | Host setting applies | Host setting applies | Size all settings to the cgroup limit |
Troubleshooting
- Backends vanish with signal 9. Check
dmesg -T | grep -i 'killed process'for the OOM killer. If it is there, reduce memory use or switch to strict overcommit. out of memoryerrors in strict mode whilefreeshows RAM available. CompareCommitted_AStoCommitLimit. The commit limit, not free RAM, is what is being enforced. Raise the ratio or add swap.- Latency spikes with
soabove zero invmstat. Lowerswappinessand reduce memory demand.
Exercise
A server has 32 GB of RAM and 4 GB of swap, and you set vm.overcommitmemory = 2 with the default vm.overcommitratio of 50. What is CommitLimit (ignoring huge pages), and why might PostgreSQL start reporting "out of memory" errors even when most RAM is free?
Show answer
CommitLimit = 32 GB * 50 / 100 + 4 GB = 20 GB. In strict mode the kernel refuses allocations once CommittedAS would exceed that limit, regardless of how much RAM is physically free. Since sharedbuffers, per-backend memory, and other processes all count toward the commitment, PostgreSQL can hit the 20 GB limit while many gigabytes of RAM are unused. The fix is to raise vm.overcommitratio (for example to 80, giving 29.6 GB) after checking CommittedAS under peak load.
Exercise
Why is it recommended to set PGOOMADJUSTVALUE=0 when the postmaster runs with oomscore_adj of -1000?
Show answer
Child processes inherit the postmaster's score. If they kept -1000, the OOM killer could never choose a backend and would kill something else. Resetting backends to 0 keeps the postmaster protected while letting the kernel kill one runaway backend, which is far less disruptive than losing the postmaster.