Skip to content

Recommend a memory-backed directory for multiprocess mode - #1269

Open
kevinmingtarja wants to merge 1 commit into
prometheus:masterfrom
kevinmingtarja:docs-multiprocess-memory-backed-dir
Open

kevinmingtarja wants to merge 1 commit into
prometheus:masterfrom
kevinmingtarja:docs-multiprocess-memory-backed-dir

Conversation

@kevinmingtarja

Copy link
Copy Markdown

Add a paragraph to the multiprocess mode page that recommends a memory-backed filesystem for PROMETHEUS_MULTIPROC_DIR, and says why.

Why

In multiprocess mode every metric update is a write into a memory-mapped file. The first write to a page after the kernel has written it back takes a page fault. On ext4 that fault updates the file's modification time, which needs a journal handle. If the journal is full, for example while another process deletes a large directory on the same filesystem, the fault waits.

Python cannot see the wait. The write is a slice assignment into the mmap object, and CPython copies the bytes with the GIL held. So one blocked metric update stops every thread of the process, an asyncio event loop included.

We hit this in a multi-threaded asyncio server on Kubernetes. Its /tmp is on the node's disk, as it is for containers by default. Each time a pod holding several hundred thousand small files was removed from the same node, the server's event loop stalled for more than a second inside Histogram.observe().

Reproduction

promtest.py (below) starts 16 single-threaded processes. Each one updates a counter, a histogram and a gauge every 5 ms and times the three updates together. Eight of them have PROMETHEUS_MULTIPROC_DIR on the node's disk and eight on a memory-backed volume. While they run, a directory holding 600,000 empty files and 20,000 files of 350 KiB is deleted from the same disk.

Linux 6.12, ext4 on a 95 GB cloud disk, Python 3.13, prometheus_client 0.26.0:

Directory on Timed updates Slowest Updates of 1 s or more
ext4 on the node's disk 510,862 1,880 ms 8: one in each process, all during the delete
tmpfs 513,776 14 ms 0

Outside the delete, neither group had an update of 20 ms or more.

In the server we traced the same wait with bpftrace. A write fault on one of the .db files normally takes about 10 microseconds. During the delete the faults took up to 1.8 s, with this kernel stack:

asm_exc_page_fault > exc_page_fault > do_user_addr_fault > handle_mm_fault > do_wp_page
  > ext4_page_mkwrite > file_update_time > __mark_inode_dirty > ext4_dirty_inode
  > __ext4_journal_start_sb > jbd2__journal_start > start_this_handle
  > __jbd2_log_wait_for_space

Prior art

promtest.py

In our run /prom-disk and /prom-mem were two volumes of one Kubernetes pod, an emptyDir and an emptyDir with medium: Memory. The deleted directory was the emptyDir of a second pod on the same node, removed when that pod was deleted.

"""Standalone check: how long does a metric update take in prometheus_client's multiprocess mode while a large
directory on the same filesystem is deleted? One arm keeps PROMETHEUS_MULTIPROC_DIR on the node's disk, the
other on a memory-backed volume. Run as: promtest_worker.py parent DURATION, which starts 8 workers per arm."""
import os, subprocess, sys, time

def worker(arm, duration):
    import prometheus_client  # imported after PROMETHEUS_MULTIPROC_DIR is set by the parent
    c = prometheus_client.Counter("promtest_updates_total", "x")
    h = prometheus_client.Histogram("promtest_seconds", "x")
    g = prometheus_client.Gauge("promtest_gauge", "x", multiprocess_mode="liveall")
    end = time.time() + duration
    n = over20 = over100 = over1000 = 0
    worst = 0.0
    while time.time() < end:
        t0 = time.perf_counter()
        c.inc(); h.observe(0.01); g.set(n)
        dt = time.perf_counter() - t0
        n += 1
        worst = max(worst, dt)
        if dt >= 0.02:
            over20 += 1; over100 += dt >= 0.1; over1000 += dt >= 1.0
            print(f"SLOW arm={arm} pid={os.getpid()} t={time.time():.3f} ms={dt * 1000:.0f}", flush=True)
        time.sleep(0.005)
    print(f"SUMMARY arm={arm} pid={os.getpid()} n={n} max_ms={worst * 1000:.1f} over20={over20} over100={over100} over1000={over1000}", flush=True)

if sys.argv[1] == "worker":
    worker(sys.argv[2], float(sys.argv[3]))
else:
    duration = float(sys.argv[2])
    procs = []
    for arm, d in (("disk", "/prom-disk"), ("memory", "/prom-mem")):
        for _ in range(8):
            procs.append(subprocess.Popen([sys.executable, "-u", __file__, "worker", arm, str(duration)], env={**os.environ, "PROMETHEUS_MULTIPROC_DIR": d}))
    print(f"START t={time.time():.3f} workers={len(procs)} prometheus_client={__import__('importlib.metadata').metadata.version('prometheus_client')}", flush=True)
    end = time.time() + duration
    while time.time() < end:
        full = open("/proc/pressure/io").read().splitlines()[1].split("total=")[1]
        print(f"PSI t={time.time():.3f} full_total_us={full}", flush=True)
        time.sleep(1)
    for p in procs: p.wait()
    print("DONE", flush=True)

AI disclosure: I used an AI coding assistant (Claude Code) to help reproduce the stall, trace it, and draft this change and description. I reviewed it.

Every metric update in multiprocess mode writes into a memory-mapped
file under PROMETHEUS_MULTIPROC_DIR. On a disk-backed filesystem that
write can wait in a page fault while the disk is busy, and the thread
holds the GIL while it waits, so every thread of the process stops.

Say so on the multiprocess page and recommend tmpfs, /dev/shm or a
memory-backed emptyDir volume.

Signed-off-by: Kevin Mingtarja <kevin.mingtarja@gmail.com>

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant