ValueError: Duplicated timeseries in CollectorRegistry  

means that at leat two metrics were added with same metric name.
You should add the metric to the registry only one time.

In my case, I declared the metric in the util directory. (like util/prometheus/metrics.py)
And then import it ( from util.prometheus import metrics) and set the label and values in every api.

check the below code.

# src/prometheus/metrics.py
from prometheus_client import  Gauge 


metric_name = "metrics_info"
metric_description = "metric test"
metric_labels = ["status_code","os","handler"]
metric_gauge = Gauge(
    name=metric_name,
    documentation = metric_description,
    labelnames = metric_labels
) 
# src/api/test.py
from ..prometheus import metrics

@router.get("/metrictest")
def test():
... do sth 
metrics.metric_gauge.labels(status_code="400",os="someos",handler="/api/test/metrictest").set(1)        
... do sth else

Answer from JAESANGPARK on Stack Overflow
🌐
Medium
medium.com › @hitorunajp › prometheus-on-a-fastapi-application-aa25e5223a9e
Prometheus on a FastAPI application | by Hitoruna | Medium
September 1, 2025 - Here MetricsMiddleware is a custom middleware class that intercepts every HTTP request to our app, records Prometheus metrics, then passes the request on. Its core functionality is in the dispatch function. For every HTTP request, it forwards the request so that FastAPI can process it normally, then increments the corresponding counter.
🌐
Reddit
reddit.com › r/fastapi › prometheus middleware is out!
r/FastAPI on Reddit: Prometheus Middleware is out!
October 12, 2020 -

Today is pretty unusual day - my first Middleware for #FastApi (and, obviously, #starlette) is out. It deals with integration and customization metrics for #prometheus with, I hopefully, simple and intuitive way.

Working with #FastApi is delight and I hope this middleware will make life of couple of folks even easier :)

Will be happy with criticism and suggestions :)

https://github.com/kozhushman/prometheusrock

Custom middleware in FastAPI Oct 21, 2021
r/FastAPI
4y ago
Unable to get API data metrics into Prometheus Dec 18, 2019
r/PrometheusMonitoring
6y ago
Securing Prometheus Jul 9, 2024
r/PrometheusMonitoring
2y ago
More results from reddit.com
Discussions

python - How to add middleware to the Fast API to create metrics to track time spent and requests made? - Stack Overflow
I am adding Middleware to my Fast API app to create Prometheus metrics to get the Processing Time and Number of requests per route. Can someone tell me what I am missing? ... This is my middleware. import time from fastapi import Request from prometheus_client import Summary, make_asgi_app, ... More on stackoverflow.com
🌐 stackoverflow.com
FastAPI and Prometheus endpoint
You won't be able to start 2 servers/processes listening on the same port. First one to start, wins. The other will fail to bind as the port is already in use. What you could do though is start both on different ports, say 8080 and 8081 or something, then put nginx in front of it all and proxy through to which ever backend based on the requested path. As a bonus you can terminate TLS at the nginx level using a single cert etc etc too. More on reddit.com
🌐 r/FastAPI
5
1
December 16, 2022
FastAPI Middleware: Performance issues when adding prometheus instrumentation package - increases latency of REST api - Stack Overflow
We are trying to decrease the latency of our BERT model prediction service that is deployed using FastAPI. The predictions are called through the /predict endpoint. We looked into the tracing and f... More on stackoverflow.com
🌐 stackoverflow.com
FastAPI Middleware: Why does adding prometheus instrumentation package increase latency of REST API?
We are trying to decrease the latency of our BERT model prediction service that is deployed using FastAPI. The predictions are called through the… More on reddit.com
🌐 r/FastAPI
5
10
December 5, 2021
🌐
Readthedocs
aioprometheus.readthedocs.io › en › latest › user › index.html
User Guide — aioprometheus Documentation
The easiest option for adding Prometheus metrics to a Starlette, FastAPI or Quart application is to use the ASGI Middleware provided by aioprometheus.
🌐
GitHub
github.com › kozhushman › prometheusrock
GitHub - kozhushman/prometheusrock: Prometheus middleware for Starlette and FastAPI
from prometheusrock import PrometheusMiddleware, metrics_route app = # Starlette() or FastAPI() app.add_middleware(PrometheusMiddleware) app.add_route("/metrics", metrics_route) ...
Author: kozhushman
Top answer
1 of 2
1
ValueError: Duplicated timeseries in CollectorRegistry  

means that at leat two metrics were added with same metric name.
You should add the metric to the registry only one time.

In my case, I declared the metric in the util directory. (like util/prometheus/metrics.py)
And then import it ( from util.prometheus import metrics) and set the label and values in every api.

check the below code.

# src/prometheus/metrics.py
from prometheus_client import  Gauge 


metric_name = "metrics_info"
metric_description = "metric test"
metric_labels = ["status_code","os","handler"]
metric_gauge = Gauge(
    name=metric_name,
    documentation = metric_description,
    labelnames = metric_labels
) 
# src/api/test.py
from ..prometheus import metrics

@router.get("/metrictest")
def test():
... do sth 
metrics.metric_gauge.labels(status_code="400",os="someos",handler="/api/test/metrictest").set(1)        
... do sth else

2 of 2
-2

Instead of setting up your own monitoring stack with Prometheus, which can be a bit fiddly, you could use a tool like Apitally to track API metrics, such as number of requests, error rates, response times etc.

Apitally comes with a middleware for FastAPI, which captures request and response metadata, and provides a simple dashboard with insights for the whole API and individual endpoints/routes.

There is a specific setup guide for FastAPI that you can follow. The basic steps are:

  1. Create an app in the Apitally dashboard to get a client ID.
  2. Install the client library as a dependency in your project:
pip install "apitally[fastapi]"
  1. Add the middleware to your FastAPI app:
from fastapi import FastAPI
from apitally.fastapi import ApitallyMiddleware

app = FastAPI()
app.add_middleware(
    ApitallyMiddleware,
    client_id="your-client-id",
    env="dev",  # or "prod" etc.
)

Disclaimer: I'm the author of Apitally.

🌐
PyPI
pypi.org › project › prometheus-fastapi-instrumentator
prometheus-fastapi-instrumentator · PyPI
Don't use this package at all and just use the source code as inspiration on how to instrument your FastAPI. ... Not made for generic Prometheus instrumentation in Python. Use the Prometheus client library for that. This packages uses it as well. All the generic middleware and instrumentation ...
🌐
GitHub
github.com › trallnag › prometheus-fastapi-instrumentator › releases
Releases · trallnag/prometheus-fastapi-instrumentator
This is possible because every FastAPI app is also a Starlette app (but not the other way around). Or to be more specific: FastAPI uses Starlette for things like routing and middleware this package relies on. The change is backwards compatible, even type checkers like mypy should continue working.
Author: trallnag
Find elsewhere
🌐
PyPI
pypi.org › project › fastapi-prometheus-exporter
fastapi-prometheus-exporter · PyPI
December 3, 2023 - from fastapi import FastAPI from fastapi_prometheus_exporter import PrometheusExporterMiddleware app = FastAPI() PrometheusExporterMiddleware.setup( app=app, metrics_path="/metrics", # ignore_paths=["/healthz", "/metrics"], )
🌐
Hashnode
carlosmv.hashnode.dev › adding-prometheus-to-a-fastapi-app-python
Adding Prometheus to a FastAPI app | Python
April 15, 2025 - Now, we can create a middleware, to count every request made to the server. from fastapi import FastAPI, Request from prometheus_client import make_asgi_app, Counter app = FastAPI() all_requests = Counter('all_requests', 'A counter of the all ...
🌐
client_python
prometheus.github.io › client_python › exporting › http › fastapi-gunicorn
FastAPI + Gunicorn | client_python
April 15, 2024 - To use Prometheus with FastAPI and Gunicorn we need to serve metrics through a Prometheus ASGI application. Save the snippet below in a myapp.py file from fastapi import FastAPI from prometheus_client import make_asgi_app # Create app app = FastAPI(debug=False) # Add prometheus asgi middleware ...
🌐
GitHub
github.com › trallnag › prometheus-fastapi-instrumentator
GitHub - trallnag/prometheus-fastapi-instrumentator: Instrument your FastAPI with Prometheus metrics. · GitHub
Don't use this package at all and just use the source code as inspiration on how to instrument your FastAPI. ... Not made for generic Prometheus instrumentation in Python. Use the Prometheus client library for that. This packages uses it as well. All the generic middleware and instrumentation ...
Author: trallnag
🌐
Medium
dimasyotama.medium.com › building-a-powerful-observability-stack-for-fastapi-with-prometheus-grafana-loki-426822422fd6
Building a Powerful Observability Stack for FastAPI with Prometheus, Grafana & Loki | by Dimas Yoga Pratama | Medium
August 21, 2025 - Note the FastAPI service is named the-app and runs on port 5060. version: "3.8" services: prometheus-app: image: prom/prometheus:latest restart: unless-stopped container_name: prometheus-observer ports: - 9090:9090 volumes: - ./prometheus/prometheus.yml:/etc/prometheus/prometheus.yml networks: - monitoring grafana: image: grafana/grafana container_name: grafana-observer restart: unless-stopped depends_on: - prometheus-app - loki-app ports: - 3000:3000 volumes: - ./grafana/provisioning:/etc/grafana/provisioning environment: - GF_SECURITY_ADMIN_USER=admin - GF_SECURITY_ADMIN_PASSWORD=admin netwo
🌐
Reddit
reddit.com › r/fastapi › fastapi and prometheus endpoint
r/FastAPI on Reddit: FastAPI and Prometheus endpoint
December 16, 2022 -

Hi all,

I have a fastapi app which generates some custom prometheus metrics with the prometheus client library.

I can start a separate server with start_http_server method from the prometheus client, but i would like to have the /metrics endpoint be served on the same port as my fastapi app.

I cant seem to find an easy way to do this, i see a prometheus offers integration with ASGI but i cant figure out how to piece everything together. AAnyone here done this before?

🌐
Stack Overflow
stackoverflow.com › questions › 70222752 › fastapi-middleware-performance-issues-when-adding-prometheus-instrumentation-pa
FastAPI Middleware: Performance issues when adding prometheus instrumentation package - increases latency of REST api - Stack Overflow
We are trying to decrease the latency of our BERT model prediction service that is deployed using FastAPI. The predictions are called through the /predict endpoint. We looked into the tracing and found one of the bottlenecks is the prometheus-fastapi-instrumentator.
🌐
GitHub
github.com › stephenhillier › starlette_exporter
GitHub - stephenhillier/starlette_exporter: Prometheus exporter for Starlette and FastAPI · GitHub
from starlette.applications import Starlette from starlette_exporter import PrometheusMiddleware, handle_metrics app = Starlette() app.add_middleware(PrometheusMiddleware) app.add_route("/metrics", handle_metrics) ... from fastapi import FastAPI from starlette_exporter import PrometheusMiddleware, handle_metrics app = FastAPI() app.add_middleware(PrometheusMiddleware) app.add_route("/metrics", handle_metrics) ...
Author: stephenhillier
🌐
Pythe
pythe.us › fastapi
FastAPI - pytheus
from fastapi import FastAPI from pytheus.middleware import PytheusMiddlewareASGI app = FastAPI() app.add_middleware(PytheusMiddlewareASGI)
🌐
Medium
medium.com › @natalia.oypmd.mnk › integrating-fastapi-with-prometheus-ea68aa8e5089
Integrating FastAPI with Prometheus | by Lidia Manik | Medium
November 17, 2025 - # Build the Docker Image docker build -t fastapi-prometheus . # Run the Container docker run -d -p 8000:8000 fastapi-prometheus · Access it at http://localhost:8000. ... Instrumentator() creates a Prometheus collector. .instrument(app) attaches metrics tracking middleware to FastAPI.
🌐
Reddit
reddit.com › r/fastapi › fastapi middleware: why does adding prometheus instrumentation package increase latency of rest api?
r/FastAPI on Reddit: FastAPI Middleware: Why does adding prometheus instrumentation package increase latency of REST API?
December 5, 2021 - We are trying to decrease the latency of our BERT model prediction service that is deployed using FastAPI. The predictions are called through the /predict endpoint. We looked into the tracing and found one of the bottlenecks is the prometheus-fastapi-instrumentator.
🌐
DEV Community
dev.to › ken_mwaura1 › getting-started-monitoring-a-fastapi-app-with-grafana-and-prometheus-a-step-by-step-guide-3fbn
Getting Started: Monitoring a FastAPI App with Grafana and Prometheus - A Step-by-Step Guide - DEV Community
January 30, 2025 - Create a folder prometheus_data, inside it create a configuration file named: prometheus.yml to define Prometheus settings and targets. Example configuration: global: scrape_interval: 15s scrape_configs: - job_name: 'fastapi-app' static_configs: - targets: ['web:8000']