{"id":7755,"library":"starlette-prometheus","title":"Starlette Prometheus Integration","description":"Starlette-prometheus is a Python library that provides seamless Prometheus integration for Starlette applications. It includes a middleware to automatically expose key metrics such as total requests, request duration, and concurrent requests. The library is currently at version 0.10.0, released on September 3, 2024, with a development cadence that includes periodic updates and feature enhancements.","status":"active","version":"0.10.0","language":"en","source_language":"en","source_url":"https://github.com/PeRDy/starlette-prometheus","tags":["starlette","prometheus","metrics","monitoring","asgi","middleware","observability"],"install":[{"cmd":"pip install starlette-prometheus uvicorn","lang":"bash","label":"Install with Uvicorn for local testing"}],"dependencies":[{"reason":"Core ASGI framework for integration.","package":"starlette","optional":false},{"reason":"Python client for Prometheus metric exposition.","package":"prometheus-client","optional":false},{"reason":"Runtime environment.","package":"python","optional":false}],"imports":[{"symbol":"PrometheusMiddleware","correct":"from starlette_prometheus import PrometheusMiddleware"},{"note":"The `metrics` endpoint handler is exposed directly from the top-level package for convenience.","wrong":"from starlette_prometheus.middleware import metrics","symbol":"metrics","correct":"from starlette_prometheus import metrics"},{"note":"Starlette application class resides in `starlette.applications`.","wrong":"from starlette import Starlette","symbol":"Starlette","correct":"from starlette.applications import Starlette"}],"quickstart":{"code":"import uvicorn\nfrom starlette.applications import Starlette\nfrom starlette.responses import PlainTextResponse\nfrom starlette_prometheus import PrometheusMiddleware, metrics\n\napp = Starlette()\napp.add_middleware(PrometheusMiddleware, app_name='my_starlette_app', prefix='starlette_app_prefix')\napp.add_route('/metrics', metrics)\n\n@app.route('/')\nasync def homepage(request):\n    return PlainTextResponse('Hello, world!')\n\n@app.route('/items/{item_id}')\nasync def read_item(request):\n    item_id = request.path_params['item_id']\n    return PlainTextResponse(f'Item: {item_id}')\n\nif __name__ == '__main__':\n    # Run with: uvicorn quickstart:app --port 8000\n    uvicorn.run(app, host='0.0.0.0', port=8000)\n","lang":"python","description":"This quickstart demonstrates how to integrate `starlette-prometheus` into a basic Starlette application. It sets up `PrometheusMiddleware` to automatically collect HTTP request metrics and exposes them at the `/metrics` endpoint. Run this file using `uvicorn quickstart:app --port 8000` and then access `http://localhost:8000/metrics` to see the collected metrics."},"warnings":[{"fix":"Initialize PrometheusMiddleware with `filter_unhandled_paths=True`. Example: `app.add_middleware(PrometheusMiddleware, filter_unhandled_paths=True)`.","message":"Failing to filter unhandled paths (e.g., 404s) can lead to unbounded memory use and high cardinality metrics, potentially overwhelming your Prometheus server.","severity":"gotcha","affected_versions":"All versions"},{"fix":"Set the `PROMETHEUS_MULTIPROC_DIR` environment variable to a shared directory. `prometheus_client` will use this directory to store metric files, which Prometheus can then scrape and aggregate. For example: `export PROMETHEUS_MULTIPROC_DIR=/tmp/prometheus_metrics`.","message":"When deploying with multiple worker processes (e.g., Gunicorn or Uvicorn with `--workers`), Prometheus metrics will not aggregate correctly by default, leading to incomplete or incorrect data.","severity":"breaking","affected_versions":"All versions"},{"fix":"Upgrade `starlette-prometheus` to version `0.9.0` or higher to resolve the `UnboundLocalError: local variable 'status_code' referenced before assignment` bug.","message":"Older versions (pre-0.9.0) of `starlette-prometheus` contained a bug (`UnboundLocalError`) when handling certain requests.","severity":"deprecated","affected_versions":"<0.9.0"}],"env_vars":null,"last_verified":"2026-04-16T00:00:00.000Z","next_check":"2026-07-15T00:00:00.000Z","problems":[{"fix":"Ensure `app.add_middleware(PrometheusMiddleware)` is called and `app.add_route('/metrics', metrics)` is set up. Make sure to send requests to your application's endpoints (e.g., `/` or `/items/123`) before checking `/metrics`.","cause":"The middleware or the metrics route handler is not correctly configured, or the application hasn't processed any requests yet.","error":"Metrics endpoint is empty or not showing expected data."},{"fix":"Upgrade your `starlette-prometheus` package to version `0.9.0` or newer: `pip install --upgrade starlette-prometheus`.","cause":"This is a known bug in `starlette-prometheus` versions prior to `0.9.0`.","error":"UnboundLocalError: local variable 'status_code' referenced before assignment"},{"fix":"Configure the middleware with `filter_unhandled_paths=True` to prevent metrics from being generated for 404 routes. If using dynamic paths, consider options provided by similar libraries (like `starlette_exporter`'s `group_paths`) if more fine-grained control is needed, but for `starlette-prometheus`, `filter_unhandled_paths` is the primary control.","cause":"By default, `starlette-prometheus` tracks every unique request path, including 404s or dynamic paths without grouping.","error":"Prometheus shows too many unique `path` labels, leading to high cardinality warnings."}]}