Home / Databases / PostgreSQL

DatabasesTroubleshootingIntermediate

PostgreSQL 'could not resize shared memory segment ... No space left on device': fixing /dev/shm in Docker and Kubernetes

Parallel queries fail with "could not resize shared memory segment" because /dev/shm in the container is tiny. Confirm it, unblock the query, then size /dev/shm properly.

Deepak Bhardwaj7 min read

Applies toPostgreSQL 12–18 on Linux, running in Docker, Podman or Kubernetes (self-managed images and operators)

Symptom

A report, an analytic query or a big join fails, usually only in the containerised environment and not on the VM or laptop where it was tested:

ERROR:  could not resize shared memory segment "/PostgreSQL.1489264328" to 8388608 bytes: No space left on device

The disk is not full. The "device" is /dev/shm, the tmpfs that PostgreSQL uses for dynamic shared memory (DSM). Parallel query workers exchange tuples and build shared hash tables in DSM segments. Docker gives a container a 64 MB /dev/shm by default, and a Kubernetes pod gets whatever the container runtime provides, often also 64 MB. One parallel hash join on a large table can need far more than that.

Small queries keep working, which is why the problem often appears only after data grows or after someone raises work_mem.

Note

Older minor releases could crash a backend with a bus error (SIGBUS) instead of returning this error. Current releases allocate the segment up front, so you get a clean error instead. If you see SIGBUS crashes in the log on an old build, the cause and fix are the same.

Confirm the cause

Check the size and use of /dev/shm inside the container

# Docker / Podman
docker exec -it pg df -h /dev/shm
docker exec -it pg ls -l /dev/shm

# Kubernetes
kubectl exec -it pg-0 -c postgres -- df -h /dev/shm

A Size of 64M confirms the default. While a failing query runs, you will see PostgreSQL.* files appear in /dev/shm and the Use% climb to 100%.

Check the DSM settings

SHOW dynamic_shared_memory_type;        -- normally posix on Linux
SHOW max_parallel_workers_per_gather;
SHOW work_mem;
SHOW hash_mem_multiplier;
SHOW min_dynamic_shared_memory;         -- PostgreSQL 14 and later

With dynamic_shared_memory_type = posix, every DSM segment is a file in /dev/shm. A parallel hash join can use roughly work_mem × hash_mem_multiplier × (workers + 1) of shared memory for its hash table, plus tuple queues. With work_mem = 256MB and four workers, that is well past 64 MB.

Reproduce it with the plan

Run EXPLAIN on the failing query. If you see Gather, Parallel Hash or Parallel Hash Join nodes, DSM is involved:

EXPLAIN (COSTS OFF) SELECT ... ;
Message Cause Fix
could not resize shared memory segment ... No space left on device /dev/shm too small for parallel query DSM Increase /dev/shm (below)
could not open shared memory segment "/PostgreSQL.nnn": No such file or directory On a host with systemd, RemoveIPC=yes in logind.conf deletes the postgres user's shared memory when that user's last session logs out Set RemoveIPC=no or run PostgreSQL as a system user, as the PostgreSQL docs describe
out of shared memory with a hint about max_locks_per_transaction Main lock table full, not /dev/shm Size the lock table; unrelated to this post
Pod OOMKilled after you enlarge /dev/shm tmpfs pages are charged to the container's memory limit Raise the memory limit to cover shared_buffers + /dev/shm + per-backend memory

Unblock the query now

If you can't restart the container yet, take parallelism out of the failing query. This stops it needing large DSM segments.

-- Just this session
SET max_parallel_workers_per_gather = 0;

-- Or for the reporting role only
ALTER ROLE reporting SET max_parallel_workers_per_gather = 0;

The query will run single-threaded and slower, but it will finish. Lowering work_mem for that role also reduces DSM use if you want to keep some parallelism.

Warning

Don't set max_parallel_workers_per_gather = 0 server-wide as the permanent fix. You lose parallel query for every workload to work around a container default.

Fix it: give /dev/shm a realistic size

A reasonable starting point is 1 GB, or about a quarter of the container memory limit for analytic workloads. Measure with df -h /dev/shm during peak parallel queries and adjust. Each of these changes needs a container restart.

Docker and Podman

docker run -d --name pg --shm-size=1g \
  -e POSTGRES_PASSWORD_FILE=/run/secrets/pgpass \
  -v pgdata:/var/lib/postgresql/data \
  postgres:17

Docker Compose:

services:
  db:
    image: postgres:17
    shm_size: 1gb
    volumes:
      - pgdata:/var/lib/postgresql/data

Check after recreating the container:

docker exec -it pg df -h /dev/shm

Kubernetes (plain StatefulSet)

Kubernetes has no --shm-size flag. Mount a memory-backed emptyDir over /dev/shm:

spec:
  template:
    spec:
      containers:
        - name: postgres
          image: postgres:17
          resources:
            requests:
              memory: 6Gi
            limits:
              memory: 6Gi
          volumeMounts:
            - name: dshm
              mountPath: /dev/shm
            - name: data
              mountPath: /var/lib/postgresql/data
      volumes:
        - name: dshm
          emptyDir:
            medium: Memory
            sizeLimit: 1Gi

Apply it and confirm on the new pod:

kubectl apply -f postgres-statefulset.yaml
kubectl rollout status statefulset/pg
kubectl exec -it pg-0 -c postgres -- df -h /dev/shm

Caution

Data written to a medium: Memory volume counts against the container memory limit. If you add a 1 Gi /dev/shm without raising limits.memory, a busy parallel query can now get the whole pod OOM-killed instead of failing one query. Raise the limit at the same time, and roll the change through replicas before the primary.

Kubernetes operators

PostgreSQL operators usually manage the /dev/shm volume for you and expose a setting to enable or size it. Setting names vary by operator and version; check your operator's documentation rather than patching the generated StatefulSet, which the operator will overwrite.

Optional: reserve DSM from main shared memory

On PostgreSQL 14 and later, min_dynamic_shared_memory preallocates an area inside the main shared memory segment that parallel query uses before it creates segments in /dev/shm:

ALTER SYSTEM SET min_dynamic_shared_memory = '256MB';
-- requires a restart

This memory is taken at startup whether it is used or not, and it still counts against the container's memory limit. It helps when you can't change the container spec, but sizing /dev/shm correctly is the cleaner fix.

Tip

Avoid changing dynamic_shared_memory_type to mmap to dodge /dev/shm. It writes DSM segments to pg_dynshmem under the data directory, which adds disk I/O on your data volume. Changing to sysv is possible but it moves the limit to the kernel's SysV settings instead of removing it.

Verify the fix

  1. Re-run the original query with parallelism enabled and check the plan still shows Gather:

    RESET max_parallel_workers_per_gather;
    EXPLAIN (ANALYZE, COSTS OFF) SELECT ... ;
    
  2. Watch /dev/shm while it runs:

    kubectl exec -it pg-0 -c postgres -- sh -c 'while true; do df -h /dev/shm | tail -1; sleep 2; done'
    
  3. Remove any temporary role-level setting you added:

    ALTER ROLE reporting RESET max_parallel_workers_per_gather;
    
  4. Search the server log for further occurrences over the next few days:

    kubectl logs pg-0 -c postgres --since=24h | grep -i "could not resize shared memory"
    

Prevent it next time

  • Put --shm-size, shm_size or the /dev/shm emptyDir in your standard PostgreSQL container template, so no environment ships with the 64 MB default.
  • Size the container memory limit as shared_buffers + /dev/shm + expected backend memory (work_mem multiplied by realistic concurrency), plus headroom.
  • When someone raises work_mem, hash_mem_multiplier or max_parallel_workers_per_gather, check that /dev/shm still covers the largest parallel query.
  • Add an alert on could not resize shared memory segment in your log pipeline. It usually shows up in a scheduled report before users notice.
  • Test new images with a production-sized parallel query, not only a smoke test, before promoting them.