A primary restarts at 3:12 a.m. The Postgres log shows crash recovery and nothing that looks like a cause. kubectl describe pod shows the container’s last state: OOMKilled, exit code 137. Nobody deployed anything.

This is a follow-up to PostgreSQL in Kubernetes?!?!? are you serious?. If you run Postgres in a pod, this is the failure you should rule out first, because it is almost always a sizing problem and you can find it before it pages you.

Postgres does not read the limit

Postgres has no idea what the pod’s memory limit is, and it sizes nothing from it. shared_buffers is a fixed number you set, allocated at startup. work_mem is an allowance for each sort or hash operation. Neither adapts to the container around it.

The limit is enforced by the kernel through the container’s cgroup. When the container goes over and the kernel cannot reclaim enough memory, it kills something. Postgres finds out afterwards. So the limit and the settings are two separate numbers that you have to keep consistent yourself, and nothing checks them against each other.

Do the budget before the incident

Memory in a Postgres container comes from several places:

  • shared_buffers. Fixed at startup. The CloudNativePG documentation suggests about 25% of the pod’s memory as a starting point.
  • work_mem. Per sort or hash operation, not per query and not per connection. Hash operations can use work_mem multiplied by hash_mem_multiplier (default 2.0), and each parallel worker gets its own allowance. I covered the multiplication in why your sort spilled to disk.
  • maintenance_work_mem. Each autovacuum worker can use it, and autovacuum_max_workers defaults to 3. A manual index build takes its own.
  • Per-connection baseline. Every backend costs memory before it runs a query. The cost grows with catalog size and prepared statements.
  • Everything else in the container. The operator’s instance manager, plus file cache the container is charged for.

This query puts the three biggest terms next to each other. It assumes one work_mem allocation per connection, which is the optimistic case:

SELECT pg_size_pretty(pg_size_bytes(current_setting('shared_buffers'))) AS shared_buffers,
pg_size_pretty(current_setting('max_connections')::bigint
* pg_size_bytes(current_setting('work_mem'))) AS one_work_mem_per_connection,
pg_size_pretty(current_setting('autovacuum_max_workers')::bigint
* pg_size_bytes(current_setting('maintenance_work_mem'))) AS autovacuum_workers,
current_setting('hash_mem_multiplier') AS hash_mem_multiplier;

Take a pod with a 4Gi limit, shared_buffers at 1GB, work_mem at 16MB, maintenance_work_mem at 256MB and 100 connections. That is 1GB for buffers, 1.6GB if every connection runs one sort at once, and 768MB if all three autovacuum workers are busy. The total is about 3.4GB against a 4GB limit, leaving roughly 700MB for backend baselines, the instance manager, and everything else. It fits, but not by much. A second sort in a few queries, or one parallel query, and it does not.

That is a worst case, not a forecast. It is also exactly the state a database is in when an incident starts: a reporting job, an autovacuum run on a large table and a connection spike, all at once. If the number does not fit, the answer is usually fewer connections through a pooler, not a larger work_mem. See why raising max_connections made everything slower.

Requests, limits and Guaranteed QoS

Kubernetes assigns each pod a quality of service (QoS) class from its requests and limits. A pod is Guaranteed when every container has CPU and memory requests equal to its limits. The CloudNativePG documentation recommends Guaranteed for Postgres. Guaranteed pods get an oom_score_adj of -997, so when a node is under memory pressure, the kernel prefers other victims.

apiVersion: postgresql.cnpg.io/v1
kind: Cluster
metadata:
name: pg-main
spec:
instances: 3
postgresql:
parameters:
shared_buffers: "1GB"
work_mem: "16MB"
maintenance_work_mem: "256MB"
max_connections: "100"
resources:
requests:
memory: "4Gi"
cpu: "2"
limits:
memory: "4Gi"
cpu: "2"

Two details that catch people. Raising the memory limit does not change shared_buffers, and changing shared_buffers needs a restart, so resize them together. And Guaranteed means the CPU limit equals the request too. CPU over the limit is throttled, not killed, so a limit that is too low shows up as latency rather than restarts. Size it from observed usage.

What happens at the limit

Two behaviors are possible, and which one you get depends on your nodes.

One process is killed. The kernel picks a victim, usually a large backend. Postgres logs that a server process was terminated by signal 9, terminates all other connections, and recovers automatically when restart_after_crash is on, which is the default. Every client is disconnected and the instance stays up.

The whole container is killed. Since Kubernetes 1.28, on cgroup v2 nodes the kubelet sets memory.oom.group for each container by default, so an OOM event kills every process in the container together. Kubernetes 1.32 added a kubelet option, singleProcessOOMKill, to bring back the per-process behavior. With the group kill, the postmaster’s low score does not help, because everything in the cgroup goes at once. The container exits with 137, restarts, and Postgres runs crash recovery on startup. On a primary, that is an outage. cgroup v1 is deprecated and the kubelet refuses to start on it by default from 1.35, so most current clusters are on this second behavior unless someone turned it off.

To see what happened to a pod, and what your nodes do:

# Why did the container last stop?
kubectl get pod pg-main-1 -o jsonpath='{.status.containerStatuses[?(@.name=="postgres")].lastState.terminated}'
# Is per-process OOM kill enabled on a node? null means the default (false).
kubectl get --raw "/api/v1/nodes/<node>/proxy/configz" | jq '.kubeletconfig.singleProcessOOMKill'

The short version

  1. Set memory requests equal to limits so the pod is Guaranteed.
  2. Compute the worst case from pg_settings and keep it under the limit with real headroom.
  3. Cap connections with a pooler instead of raising work_mem to compensate.
  4. Resize the limit and shared_buffers together, and plan for the restart.
  5. Alert on working set against the limit, on OOMKilled, and on OOM events, because a partial kill leaves the container running.

Two scripts from pgtools help here. activity.sql shows what sessions are running right now, which is the first place to look when memory climbs. cache-hit.sql shows whether the shared_buffers you gave up part of the limit for is earning its share.

Leave a Reply