The symptom and the explanations#
The example is fictional. At 03:12 UTC the nightly report-worker container started failing. The Python workers logged RuntimeError: can't start new thread, and the shell script that launches them printed bash: fork: retry: Resource temporarily unavailable. The container had run the same job for months; the night before, its image had moved to a new base, the cluster's node pool had been replaced, and the job's input had doubled. Three explanations fit:
- The cgroup's PID limit was reached. The container runs in a cgroup with
pids.maxset, by Docker's--pids-limit, the kubelet's per-pod PID limit or a systemd unit'sTasksMax=. docker run · Kubernetes PID limiting · systemd TasksMax= The limit counts threads as well as processes, because the controller counts the kernel's task IDs. cgroup v2 PID controller - The user's process limit was reached. The new base image runs the job as an unprivileged user, and
RLIMIT_NPROClimits the processes and threads of a real user ID. It is not enforced for root, so a job that ran as root never met it. getrlimit(2) - Memory for thread stacks ran out. Each thread needs a stack, 8 MiB by default when
ulimit -sis 8192, and with twice the input the workers start twice the threads. pthread_create(3)
fork(2) lists RLIMIT_NPROC, the system-wide threads-max and pid_max, and the cgroup's pids.max as limits that return EAGAIN, and pthread_create(3) adds "insufficient resources to create another thread". fork(2) The message is the same text for every one of them. Choose the observation where explanations disagree
What each explanation predicts#
| Observation | cgroup pids.max | RLIMIT_NPROC | Memory for stacks |
|---|---|---|---|
| Error text | EAGAIN | EAGAIN | EAGAIN from pthread_create |
pids.events max | goes up | unchanged | unchanged |
pids.current against pids.max | equal | below, or no limit | below, or no limit |
Threads of the user against ulimit -u | below | equal | below |
| Fails when run as root | yes | no | yes |
A small fork while threads are stuck | fails | fails | can succeed |
The second row is the cleanest. The kernel counts each refusal by pids.max in pids.events, and the counter only rises, so it still shows the refusals after the burst of threads has ended and pids.current has fallen back. cgroup v2 PID controller The thread count graph, if there is one, rises before the failures in every column.
The lab: three limits, one error#
The script starts threads that wait, until a thread fails to start. Then it prints the process's Threads count, its RLIMIT_NPROC, the cgroup's PID files, and whether one fork() still works. It reads cgroup v2 paths, and falls back to v1, where the PID files sit under pids/. Save it as spawn.py.
import os, resource, threading
# cgroup v2 puts the pids files at the root of /sys/fs/cgroup; v1 under pids/
CG = "/sys/fs/cgroup" if os.path.exists("/sys/fs/cgroup/pids.max") else "/sys/fs/cgroup/pids"
def cg(name):
with open(f"{CG}/{name}") as f:
return f.read().split()
def threads_in_status():
with open("/proc/self/status") as f:
return next(l.split()[1] for l in f if l.startswith("Threads:"))
stop = threading.Event()
started = []
try:
while True:
t = threading.Thread(target=stop.wait, daemon=True)
t.start()
started.append(t)
except RuntimeError as e:
print(f"thread {len(started) + 1} failed: {e}")
print(f"Threads in this process: {threads_in_status()}")
print(f"RLIMIT_NPROC soft limit: {resource.getrlimit(resource.RLIMIT_NPROC)[0]}")
print(f"pids.current={cg('pids.current')[0]} pids.max={cg('pids.max')[0]} pids.events={' '.join(cg('pids.events'))}")
try:
pid = os.fork()
if pid == 0:
os._exit(0)
os.waitpid(pid, 0)
print("fork succeeded")
except OSError as e:
print(f"fork failed: errno {e.errno} ({e.strerror})")
print(f"pids.events after fork: {' '.join(cg('pids.events'))}")
stop.set()
Run it under each limit with Docker. The first run sets the cgroup limit, the second runs as the unprivileged user 65534 with RLIMIT_NPROC at 40, and the third caps the address space with ulimit -v as a stand-in for memory that cannot fit more stacks:
docker run --rm --pids-limit 50 -v "$PWD":/lab:ro python:3.12-slim python3 -W ignore /lab/spawn.py
docker run --rm --user 65534 --ulimit nproc=40 -v "$PWD":/lab:ro python:3.12-slim python3 -W ignore /lab/spawn.py
docker run --rm -v "$PWD":/lab:ro python:3.12-slim sh -c 'ulimit -v 300000; python3 -W ignore /lab/spawn.py'
Write your prediction before you run them: only the first run moves pids.events, the first two stop at their limits of 50 and 40 tasks, and only the third lets the fork() through. Python 3.12.16 printed, on a Docker host with cgroup v1:
thread 50 failed: can't start new thread
Threads in this process: 50
RLIMIT_NPROC soft limit: 64272
pids.current=50 pids.max=50 pids.events=max 1
fork failed: errno 11 (Resource temporarily unavailable)
pids.events after fork: max 2
thread 40 failed: can't start new thread
Threads in this process: 40
RLIMIT_NPROC soft limit: 40
pids.current=40 pids.max=max pids.events=max 0
fork failed: errno 11 (Resource temporarily unavailable)
pids.events after fork: max 0
thread 11 failed: can't start new thread
Threads in this process: 11
RLIMIT_NPROC soft limit: 64272
pids.current=12 pids.max=max pids.events=max 0
fork succeeded
pids.events after fork: max 0
Python gave the same message in all three runs, and fork() returned EAGAIN (errno 11) in the first two. The pids.events counter rose once for the refused thread and once for the refused fork, and stayed at zero under RLIMIT_NPROC with the same process at the same kind of limit. Under the address-space cap the process ran out at 11 threads, far below either count, and a fork() still worked. The prediction would have failed if pids.events had moved in the second or third run, or stayed at zero in the first. Change --pids-limit 50 or nproc=40 and the failing thread number follows; add ulimit -s 1024; before ulimit -v in the third run and smaller stacks fit more threads in the same address space, 20 instead of 11 when we ran it.
The -W ignore silences Python's warning about forking a process that has threads; the fork() here exists only to test the limit. systemd warns that LimitAS=, the same limit as ulimit -v, limits address space rather than memory use, which is why the third run is a stand-in and not a reproduction of a memory shortage. systemd.exec
Read it on a real system#
These commands read only. Inside the container, on cgroup v2:
cat /sys/fs/cgroup/pids.max /sys/fs/cgroup/pids.current /sys/fs/cgroup/pids.peak
cat /sys/fs/cgroup/pids.events
From the host, /proc/PID/cgroup gives the process's cgroup path, and the same files sit under /sys/fs/cgroup/ plus that path. pids.peak is the highest count the cgroup has reached, which survives a burst that has ended. cgroup v2 PID controller
For the user's limit, compare the process's Max processes with the number of threads that user runs. ps -L lists one line per thread. proc_pid_limits(5)
grep 'Max processes' /proc/PID/limits
ps -L -u USER --no-headers | wc -l
grep Threads /proc/PID/status
cat /proc/sys/kernel/threads-max /proc/sys/kernel/pid_max
Threads in /proc/PID/status is the thread count of one process. proc_pid_status(5) Prometheus client libraries export the same figure as process_threads; graph it per instance to see which process grew. Client library process metrics
Where the check misleads#
On cgroup v2, pids.events in a cgroup counts refusals anywhere in its subtree unless the hierarchy is mounted with pids_localevents; pids.events.local counts only the cgroup's own. cgroup v2 PID controller A limit can also sit on a parent, such as the pod's cgroup, while the container's own pids.max reads max, since a child can only consume what its ancestors allow. cgroup v2 limits Walk up the path from /proc/PID/cgroup and read pids.max and pids.events at each level.
RLIMIT_NPROC counts every process and thread of the real user ID, not of one container. If other workloads run under the same numeric user ID, their threads count toward the same limit. Count that user's threads from the host.
The system-wide limits, threads-max and pid_max, return the same EAGAIN and move no cgroup counter. A host that runs out of them fails for every service at once, which is itself the distinguishing observation.
A stack shortage depends on how memory is accounted, and the lab's address-space cap is only one way to produce it. When Threads is far below every count limit and pids.events is still, look at the process's memory and thread stack size before raising PID limits. Memory keeps growing, and the heap profile stays flat
Questions#
What is the default PID limit for a Docker container?
In the lab, a container started without --pids-limit had pids.max set to max, no limit; the flag sets one, and -1 means unlimited. Orchestrators can set one for you: the kubelet applies a per-pod PID limit from --pod-max-pids or PodPidsLimit. docker run · Kubernetes PID limiting
Do threads count toward the PID limit?
Yes. The PID controller counts kernel task IDs, which include every thread, and RLIMIT_NPROC counts threads too. A process with 400 threads uses 400 of either limit.
Why does the error say temporarily?
"Resource temporarily unavailable" is the text of EAGAIN, and fork() returns it when a limit on processes or threads is reached at that moment. errno(3) It is temporary only in that a task exiting frees a slot; under a leak of threads, it stays.