Skip to content
Latchkey

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.

python
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

  1. Keep metric definitions at import scope so they register exactly once.
  2. In tests that need isolation, create a new CollectorRegistry() and pass it explicitly.
  3. Avoid importlib.reload on modules that define metrics.
test_metrics.py
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.

conftest.py
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.

Frequently asked questions

What causes ""Duplicated timeseries in CollectorRegistry""?
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.
How do I fix "Duplicated timeseries in CollectorRegistry"?
Define metrics once, or use a fresh registry per test

Related guides

References

Latchkey auto-heals failures like this one - detected, fixed, and retried without you. Start free → 30-day trial · No credit card