# Prometheus FastAPI Instrumentator for FastAPI Metrics

> Prometheus FastAPI Instrumentator is a Python package that adds configurable Prometheus metrics to FastAPI applications. It suits teams that want framework-specific request metrics without building generic Prometheus instrumentation themselves.

**trallnag/prometheus-fastapi-instrumentator** — Instrument your FastAPI with Prometheus metrics.

- Repository: https://github.com/trallnag/prometheus-fastapi-instrumentator
- Stars: 1,490 · Forks: 120
- Language: Python
- License: ISC
- Published: 2026-10-16 · Updated: 2026-10-16 · Language: en
- Canonical page: https://hysenlabs.com/projects/trallnag-prometheus-fastapi-instrumentator

## Why prometheus-fastapi-instrumentator exists for FastAPI services

This package solves the narrow problem of observing HTTP request activity inside a FastAPI application. The README describes it as a configurable and modular Prometheus instrumentator for FastAPI, not as a general-purpose Python instrumentation layer. That boundary matters because the package uses the Prometheus client library and adds middleware and instrumentation logic around FastAPI requests. The intended users are FastAPI developers and service teams that expose an application to Prometheus and want request counts, request and response sizes, and latency data without writing the complete integration themselves.

The default configuration is designed to keep metric cardinality relatively low. It records the total number of requests in the `http_requests_total` counter, with `handler`, `status`, and `method` labels. The status label is grouped into categories such as `2xx`, `3xx`, and other status groups. Requests that do not match a FastAPI route template are grouped under the handler label `none`. This grouping is a practical compromise: it avoids creating a separate label value for every individual status code in the default request counter while preserving status-group information.

The package also records request size, response size, request duration, and a higher-resolution duration histogram. These defaults are useful when a service team needs a basic scrape surface immediately. Teams that need different labels, bucket boundaries, names, or additional measurements can start from the packaged metric closures or provide their own instrumentation function. The README also warns that generic middleware and instrumentation code carries a performance cost that can become noticeable, so adoption should be considered for FastAPI services where framework-specific metrics justify that overhead.

## How Instrumentator connects FastAPI requests to Prometheus

The core entry point is the `Instrumentator` class from `prometheus_fastapi_instrumentator`. Calling `.instrument(app)` attaches the instrumentation behavior to a FastAPI application. Calling `.expose(app)` adds the metrics endpoint that Prometheus can scrape. The normal first setup is therefore two chained calls, with the README describing the resulting metrics as ready to be scraped.

The instrumentation functions are stored as closures in the package's `metrics` module. Each closure receives request and response information when FastAPI handles a request. The `add()` method stores a metric function in a list, and the instrumentator calls the functions in that list during request handling. If no `add()` call is made, the default metric is added in the background. This explains why the fast-track example does not need to list the default metrics explicitly.

The metric model is built around a small set of Prometheus types. Counts use a counter, request and response sizes use summaries, and duration measurements use histograms. The default duration histogram uses a few buckets to keep cardinality low. A second histogram, `http_request_duration_highr_seconds`, has more than 20 buckets and no labels. The README gives this as a separate default metric, so users should inspect the generated metric set before assuming that all latency information shares one histogram.

The package also offers behavior switches for ignored routes, untemplated routes, environment-variable control, latency rounding, metric and label renaming, gzip compression for the metrics endpoint, and an in-progress request metric. Static custom labels and namespace or subsystem settings are also documented. These controls operate at configuration or metric-construction time, rather than making every observation available through one fixed endpoint contract.

## Installing prometheus-fastapi-instrumentator and exposing the first metrics

The README directs users to install `prometheus-fastapi-instrumentator` from PyPI. The package metadata states that the project requires Python 3.10 or later and depends on `starlette (>=1.0.0,<2.0.0)` and `prometheus-client (>=0.8.0,<1.0.0)`.

After installing the package from PyPI, import `Instrumentator`:

```python
from prometheus_fastapi_instrumentator import Instrumentator
```

The import makes the package class available in the application module. The README then gives the shortest configuration, which instruments the app and exposes the metrics route:

```python
Instrumentator().instrument(app).expose(app)
```

In a FastAPI application, this line should be placed where the `app` object is available. After the application starts, the package exposes metrics that a Prometheus server can scrape. The README does not specify a metrics path, response body, or startup log output, so those details should be checked against the deployed application and Prometheus configuration.

For code organized around a startup event, the documented alternative is:

```python
instrumentator = Instrumentator().instrument(app)

@app.on_event("startup")
async def _startup():
    instrumentator.expose(app)
```

This separates instrumentation from exposition. The README says that one form may be needed depending on the application code. It does not say that either form changes the default metric definitions.

## Configuring request filtering and adding metric closures

A more explicit setup can control whether metrics are enabled and which handlers are excluded. The README shows an `Instrumentator` configured with status grouping disabled, untemplated routes ignored, environment-variable control enabled, and an in-progress request metric enabled. It also excludes handlers matching `.*admin.*` and `/metrics`:

```python
from prometheus_fastapi_instrumentator import Instrumentator, metrics

instrumentator = Instrumentator(
    should_group_status_codes=False,
    should_ignore_untemplated=True,
    should_respect_env_var=True,
    should_instrument_requests_inprogress=True,
    excluded_handlers=[".*admin.*", "/metrics"],
    env_var_name="ENABLE_METRICS",
    inprogress_name="inprogress",
    inprogress_labels=True
)
```

The documentation states that instrumentation and exposition happen only when the `ENABLE_METRICS` environment variable is `true` at run time. This can help a shared FastAPI base application behave differently across deployments. The exact truthiness and process-level configuration behavior beyond that statement are not documented in the README.

Metric closures can be added independently. The latency closure accepts bucket values, and the request and response size closures accept switches for labels and naming. For example:

```python
instrumentator.add(metrics.latency(buckets=(1, 2, 3,)))

instrumentator.add(
    metrics.request_size(
        should_include_handler=True,
        should_include_method=False,
        should_include_status=True,
        metric_namespace="a",
        metric_subsystem="b",
        custom_labels={"service": "example-label"}
    )
).add(
    metrics.response_size(
        should_include_handler=True,
        should_include_method=False,
        should_include_status=True,
        metric_namespace="namespace",
        metric_subsystem="subsystem",
        custom_labels={"service": "example-label"}
    )
)
```

The first call configures the latency histogram with three documented buckets. The next calls add request and response size metrics with different namespaces, subsystems, and static service labels. The README states that users may add as many metrics as they like, but it also warns about instrumentation overhead. Adding metrics therefore increases both configuration complexity and observation work.

## Trade-offs against generic Prometheus client instrumentation

The README distinguishes this package from generic Prometheus instrumentation in Python. Its alternative is the Prometheus client library, which the package also uses. The difference is scope. This package supplies FastAPI-specific request integration, default HTTP metrics, route-handler grouping, untemplated-route handling, and an endpoint exposure pattern. A generic client library requires the application or surrounding framework integration to define the HTTP metrics and lifecycle behavior itself.

That convenience has a cost. The README says that all generic middleware and instrumentation code comes with a performance cost that can become noticeable. It does not provide a benchmark or quantify the overhead, so teams cannot use the repository information to predict a particular production impact. They would need to evaluate the overhead against their request volume and metrics design.

The package is also not a complete observability system. It exposes Prometheus metrics, but the repository does not say that it configures a Prometheus server, stores metric history, creates alerts, or provides dashboards. Those parts remain outside the documented scope. It is a better fit when the application needs a FastAPI-oriented metrics adapter and already has a Prometheus deployment that will scrape the application.

## Compatibility, licensing, and upgrade considerations

The package metadata identifies `prometheus-fastapi-instrumentator` as version 8.1.0, requires Python `>=3.10`, and uses `poetry-core>=2.0` as its build backend. The documented runtime dependencies are `starlette (>=1.0.0,<2.0.0)` and `prometheus-client (>=0.8.0,<1.0.0)`. The dependency bounds are relevant when integrating the package with an existing FastAPI or Starlette stack, because an application environment must satisfy those constraints.

The repository uses the ISC license. The license should be reviewed as part of normal dependency acceptance, especially for organizations that require a consistent inventory of open source licenses. This article does not provide legal interpretation or claim that the license imposes a particular operational obligation.

The repository is not archived, and its last push was on 2026-09-18. The listed releases include v8.1.0 on 2026-07-26, v8.0.2 on 2026-06-23, and v8.0.1 on 2026-06-22. The repository layout includes `CHANGELOG.md`, `RELEASE.md`, `poetry.lock`, `pyproject.toml`, tests, and development configuration. Those files indicate a release and development workflow, but the repository does not state a support policy, compatibility matrix, migration procedure, or rollback procedure. Upgrade review should therefore focus on the version changes recorded in the repository and the dependency bounds above.

## Conclusion

Adopt this package when a FastAPI service needs request metrics with low-cardinality defaults, configurable presets, or a custom metrics function. Do not use it for generic Python Prometheus instrumentation, and verify first that its middleware cost, metric names, labels, environment-variable behavior, and `/metrics` exposure match the service requirements.

## FAQ

### How do I install prometheus-fastapi-instrumentator?

The README directs users to install `prometheus-fastapi-instrumentator` from PyPI. The package metadata specifies Python `>=3.10` and the runtime dependencies `starlette (>=1.0.0,<2.0.0)` and `prometheus-client (>=0.8.0,<1.0.0)`. The README does not provide a shell installation command.

### What metrics does prometheus-fastapi-instrumentator collect by default?

The defaults include `http_requests_total`, `http_request_size_bytes`, `http_response_size_bytes`, `http_request_duration_seconds`, and `http_request_duration_highr_seconds`. The first counter uses `handler`, `status`, and `method`, while the default behavior groups status codes and untemplated requests.

### Can I expose FastAPI metrics with prometheus-fastapi-instrumentator?

Yes. The documented setup calls `Instrumentator().instrument(app).expose(app)`, which instruments the FastAPI application and exposes metrics for scraping. The README also documents a startup-event alternative that calls `instrumentator.expose(app)` during startup.

## Sources

- [Issues](https://github.com/trallnag/prometheus-fastapi-instrumentator/issues)
- [License: ISC](https://github.com/trallnag/prometheus-fastapi-instrumentator/blob/master/LICENSE)
- [README](https://github.com/trallnag/prometheus-fastapi-instrumentator/blob/master/README.md)
- [Releases](https://github.com/trallnag/prometheus-fastapi-instrumentator/releases)
- [trallnag/prometheus-fastapi-instrumentator on GitHub](https://github.com/trallnag/prometheus-fastapi-instrumentator)

---

Hysen Labs editorial analysis, written from the project's own repository and release notes. Cite the canonical page: https://hysenlabs.com/projects/trallnag-prometheus-fastapi-instrumentator
