Skip to content

Multiprocessing with Gunicorn + FastAPI #810

Closed
@IWillPull

Description

@IWillPull

I've been trying to make multiprocessing work with FastAPI, but it just doesn't seem to happen.

This part is what I've been struggling the most:

def app(environ, start_response):
    registry = CollectorRegistry()
    multiprocess.MultiProcessCollector(registry)
    data = generate_latest(registry)
    status = '200 OK'
    response_headers = [
        ('Content-type', CONTENT_TYPE_LATEST),
        ('Content-Length', str(len(data)))
    ]
    start_response(status, response_headers)
    return iter([data])

Had no idea where to put this, but after some experimentation it turns out, the simplest solution of creating a metrics app looks like this (including other parts from the documentation):

app = FastAPI(debug=False)

# Preparing gunicorn multiprocessing HACKS
def make_metrics_app():
    registry = CollectorRegistry()
    multiprocess.MultiProcessCollector(registry)
    return prometheus_client.make_asgi_app(registry=registry)


metrics_app = make_metrics_app()
app.mount("/metrics", metrics_app))

Just posting this to help others save hours of researching and debugging.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions