prometheus_client Python "Duplicated timeseries in CollectorRegistry" in CI
The Python prometheus_client default registry rejects a second metric with the same name. When test files import a module that defines module-level Counter/Gauge objects more than once, registration collides and raises ValueError.
What this error means
A test collection or import fails with "ValueError: Duplicated timeseries in CollectorRegistry: {'my_metric_total'}", often only when running the whole suite, not a single file.
ValueError: Duplicated timeseries in CollectorRegistry:
{'requests_total', 'requests_created'}Common causes
Module-level metrics registered on re-import
A Counter("requests_total", ...) at module scope registers into the default registry. When the module is reloaded or imported by a second path, the same name is registered again.
Tests reload the app module repeatedly
Fixtures that importlib.reload the app, or apps imported under two names, trigger a second registration of the same metric.
How to fix it
Define metrics once, or use a fresh registry per test
- Keep metric definitions at import scope so they register exactly once.
- In tests that need isolation, create a new
CollectorRegistry()and pass it explicitly. - Avoid
importlib.reloadon modules that define metrics.
from prometheus_client import Counter, CollectorRegistry
registry = CollectorRegistry()
c = Counter("requests_total", "desc", registry=registry)Unregister before re-registering if a reload is unavoidable
Clear the collector from the default registry before the second definition.
from prometheus_client import REGISTRY
REGISTRY.unregister(my_counter)How to prevent it
- Register each metric once at module import scope.
- Use a per-test CollectorRegistry for isolation.
- Do not importlib.reload modules that define metrics.