The prometheus_client library documentation addresses this case:

Prometheus client libraries presume a threaded model, where metrics are shared across workers. This doesn't work so well for languages such as Python where it's common to have processes rather than threads to handle large workloads.

I won't copy here the explanation (which is geared toward gunicorn) use case but basically, you need to:

  • define an env variable with directory to use: since you are using Process yourself, you can set it in the code
os.environ["PROMETHEUS_MULTIPROC_DIR"] = "/path/to/writeable/tmp/"
  • each process must have its own collector, register it at start and unregister it at exit:
from prometheus_client import multiprocess

def called_from_process():
    registry = CollectorRegistry()
    multiprocess.MultiProcessCollector(CollectorRegistry())

def process_exit(process):
    if process.pid is not None:
        multiprocess.mark_process_dead(process.pid)

p = Process(target=f)
# f calls called_from_process
p.start()
p.join()
process_exit(process)

See the full documentation about how to handle gauge and any other quirk.

I expect that PROMETHEUS_MULTIPROC_DIRshould be cleaned at startup of your application to handle odd case where the application previous run was not able to do so.

Answer from Michael Doubez on Stack Overflow
🌐
client_python
prometheus.github.io › client_python › multiprocess
Multiprocess Mode | client_python
June 23, 2026 - Prometheus client libraries presume a threaded model, where metrics are shared across workers. This doesn’t work so well for languages such as Python where it’s common to have processes rather than threads to handle large workloads. To handle this the client library can be put in multiprocess mode.
Discussions

Show HN: Pytheus – Python Prometheus client built with multiprocessing in mind
The library offers the same interface between single process & multi process, the only difference is doing a function call specifying which backend to use and everything will work out of the box. It supports default labels & partial labels so that you can build your child instances incrementally. More on news.ycombinator.com
🌐 news.ycombinator.com
11
35
July 5, 2023
How to collect prometheus metrics from multiple python-flask sub-process? - Stack Overflow
I have main() function which spawns two separate sub-processes. These both sub-process shares metrics. How can I share metrics for both process and keep it updating? Here, is my snippet for more More on stackoverflow.com
🌐 stackoverflow.com
pytheus: a modern python library for collecting prometheus metrics built with multiprocessing in mind
It's a new python library for collecting metrics with prometheus with a focus on flexibility & multiprocessing. More on reddit.com
🌐 r/Python
10
22
April 17, 2023
python - Prometheus how to expose metrics in multiprocess app with start_http_server - Stack Overflow
How expose metrics in multiprocess app use start_http_server I found many examples with gunicorn in internet but i want use start_http_server what should i do with code below to make it work proper... More on stackoverflow.com
🌐 stackoverflow.com
🌐
GitHub
github.com › jonashaag › prometheus-multiprocessing-example
GitHub - jonashaag/prometheus-multiprocessing-example: Prometheus Gunicorn multiple worker processes integration example with Flask · GitHub
The integration uses a special multi-processing feature in the Prometheus client, details of which you can find here: https://prometheus.github.io/client_python/multiprocess/
Starred by 69 users
Forked by 7 users
Languages: Python
🌐
GitHub
github.com › jonashaag › prometheus-multiprocessing-example › blob › master › README.md
prometheus-multiprocessing-example/README.md at master · jonashaag/prometheus-multiprocessing-example
The integration uses a special multi-processing feature in the Prometheus client, details of which you can find here: https://prometheus.github.io/client_python/multiprocess/
Author: jonashaag
🌐
Echorand
echorand.me › posts › python-prometheus-monitoring-options
Your options for monitoring multi-process Python applications with Prometheus
The prometheus Python Client has a multi-processing mode which essentially creates a shared prometheus registry and shares it among all the processes and hence the aggregation happens at the application level.
🌐
Hacker News
news.ycombinator.com › item
Show HN: Pytheus – Python Prometheus client built with multiprocessing in mind | Hacker News
July 5, 2023 - The library offers the same interface between single process & multi process, the only difference is doing a function call specifying which backend to use and everything will work out of the box. It supports default labels & partial labels so that you can build your child instances incrementally.
Find elsewhere
Top answer
1 of 1
15

I was figuring out the same thing, and the solution was as simple as you would imagine.

Updated your example code to work:


from multiprocessing import Process
import shutil
import time, os
from prometheus_client import start_http_server, multiprocess, CollectorRegistry, Counter


COUNTER1 = Counter('counter1', 'Incremented by the first child process')
COUNTER2 = Counter('counter2', 'Incremented by the second child process')
COUNTER3 = Counter('counter3', 'Incremented by both child processes')


def f1():
    while True:
        time.sleep(1)
        print("Child process 1")
        COUNTER1.inc()
        COUNTER3.inc()
    

def f2():
    while True:
        time.sleep(1)
        print("Child process 2")
        COUNTER2.inc()
        COUNTER3.inc()


if __name__ == '__main__':
    # ensure variable exists, and ensure defined folder is clean on start
    prome_stats = os.environ["PROMETHEUS_MULTIPROC_DIR"]
    if os.path.exists(prome_stats):
        shutil.rmtree(prome_stats)
    os.mkdir(prome_stats)

    # pass the registry to server
    registry = CollectorRegistry()
    multiprocess.MultiProcessCollector(registry)
    start_http_server(8000, registry=registry)

    p = Process(target=f1, args=())
    a = p.start()
    p2 = Process(target=f2, args=())
    p2.start()

    print("collect")

    while True:
        time.sleep(1)

localhost:8000/metrics
# HELP counter1_total Incremented by the first child process
# TYPE counter1_total counter
counter1_total 9.0
# HELP counter2_total Incremented by the second child process
# TYPE counter2_total counter
counter2_total 9.0
# HELP counter3_total Incremented by both child processes
# TYPE counter3_total counter
counter3_total 18.0
🌐
Artur's Blog
shiriev.ru › posts › prometheus-multiprocessing
Monitoring multi-process Python apps with Prometheus | Artur Shiriev
April 26, 2021 - Each worker then responds with a value for a metric that it knows of. Official Prometheus Python client has multiprocess mode. In FastAPI we are using package prometheus-fastapi-instrumentator built on top of official client. Here is the part of the source code of instrumentator:
🌐
GitHub
github.com › prometheus › client_python › issues › 367
Multiprocess mode is slow · Issue #367 · prometheus/client_python
January 21, 2019 - import os import time os.environ['prometheus_multiproc_dir'] = '/Users/akx/Desktop/roi_prometheus_multiproc' import prometheus_client from prometheus_client import multiprocess t0 = time.time() registry = prometheus_client.CollectorRegistry() multiprocess.MultiProcessCollector(registry) metrics_page = prometheus_client.generate_latest(registry) print(len(metrics_page)) print(time.time() - t0)
Author: prometheus
🌐
Medium
medium.com › @MetricFire › how-to-monitor-python-applications-with-prometheus-5144b1cffb80
How to monitor Python Applications with Prometheus | by MetricFire | Medium
August 10, 2023 - This method is our favorite here at MetricFire. We actually use this method to monitor our own application with Prometheus. This method entails using the Prometheus Python Client, which handles multi-process apps on gunicorn application server.
🌐
Python Forum
python-forum.io › thread-23766.html
prometheus in multiprocess code
Battling with Prometheus, in the below code, my prometheus counters are not incrementing. tracked it down to the working being in a multiprocess pool... Neither FILE_GESTER_TIME nor FILE_GESTER_LINE_C
🌐
Reddit
reddit.com › r/prometheusmonitoring › mpmetrics: multiprocess-safe python metrics
r/PrometheusMonitoring on Reddit: mpmetrics: Multiprocess-safe Python metrics
November 27, 2023 - I also wrote up a more in-depth post outlining my motivations for this library. The second and third bullets under the prometheus section could both cause corruption, and are both addressed in this library. ... Author here. I wrote this library after becoming annoyed with the multiprocess-mode restrictions in prometheus_client.
🌐
GitHub
github.com › prometheus › client_python › issues › 886
Support multiprocess mode without setting an environment variable · Issue #886 · prometheus/client_python
January 31, 2023 - The main problem for my use case is that it's impossible to separate multiple instances of collectors, even though it has a path field misleading you into thinking that you can https://github.com/prometheus/client_python/blob/master/prometheus_client/multiprocess.py#L22
Author: prometheus
🌐
MetricFire
metricfire.com › blog › how-to-monitor-python-applications-with-prometheus
How to monitor Python Applications with Prometheus | MetricFire
September 15, 2023 - Prometheus is becoming a popular tool for monitoring Python applications despite the fact that it was originally designed for single-process multi-threaded applications, rather than multi-process.
🌐
GitHub
github.com › prometheus › client_python › discussions › 943
Custom collectors and multiprocess mode · prometheus/client_python · Discussion #943
September 11, 2023 - As the application is served using Gunicorn with multiple worker processes, I’ve followed the multiprocess instructions from the docs. This all works perfectly fine! I’d also like to expose some metrics based on database records (e.g. number of users) or queue lengths (e.g. number of queued tasks). In order to do that, I have implemented a few custom collectors that fetch data from data stores and return Prometheus metrics.
Author: prometheus
🌐
Google Groups
groups.google.com › g › prometheus-users › c › 1c3-8oiotzk
generate_latest() for MultiProcessing writes both the MultiProcess Metrics and per Process Metrics
I guess the title says it all but using Gunicorn multiprocessing environment and creating a CollectorRegistry() that is passed into MultiProcessorCollector()... then doing generate_latest() on that registry, I get both keys for MultiProcess metrics and per Process Metrics. However, I would like to only see the MultiProcess Metrics and ignore the per Process Metrics. Is there a way to do that? ... from prometheus_client import generate_latest, CollectorRegistry, Counter, Histogram, CONTENT_TYPE_LATEST
🌐
Stack Overflow
stackoverflow.com › questions › 61729601 › right-way-to-implement-prometheus-client-multiprocess-multiprocesscollector-dja
prometheus - Right way to implement prometheus_client.multiprocess.MultiProcessCollector (Django + Celery) - Stack Overflow
registry = CollectorRegistry() multiprocess.MultiProcessCollector(registry, path='/home/aleksandrovalbert/Work/blackbox_exporter/exporter/multiproc-tmp') ... from project.settings import registry def export(request): metrics_page = prometheus_client.generate_latest(registry) return HttpResponse(metrics_page, content_type=prometheus_client.CONTENT_TYPE_LATEST)