Skip to content

fix(metrics): stop the v1 /cluster/metrics series leak - #1281

Merged
Hamdy-khader merged 1 commit into
R26.2-PREfrom
fix/v1-metrics-series-leak
Aug 27, 2026
Merged

Hamdy-khader merged 1 commit into
R26.2-PREfrom
fix/v1-metrics-series-leak

Conversation

@wmousa

@wmousa wmousa commented Aug 26, 2026

Copy link
Copy Markdown
Contributor

The gauges were cached at module scope, so a Gauge child created for a label set lived as long as the worker process. Those label sets carry entity identity (lvol/lvol_name/pvc_name/device/...), so every volume that had ever existed kept being exported.

Measured on a customer cluster (94 live volumes, ~1.2k volume deletions/day):

  • 11,534 distinct pvc_name label sets still being exported
  • ~83 MB and ~5 s per scrape, growing ~7 MB/day
  • 15 WebAppAPI containers (5 services x 3 managers), each with its own accumulated registry, so a single Prometheus target answered by HAProxy round-robin returned a different series set every scrape -- series flapped in and out and Grafana panels rendered empty
  • ~450 MiB RSS above a comparable app service, per container

Fix: build the registry per request, and build each gauge family exactly once per request, before the entity loops. Both halves are required -- a Gauge registers its name on construction, so constructing a family inside the per-entity loops raises DuplicateTimeseries on the second node/device/pool/volume.

After the equivalent change, customer scrapes went from 310,401 lines (and 298,851 from a sibling container) to a stable 3,741 lines in 2-3 s, identical across repeated scrapes, and the dashboards recovered.

Also in this endpoint, both inseparable from the rewrite:

  • health_check is Optional[bool]; Gauge.set(None) raises TypeError and would fail the whole scrape. Report NaN, which Prometheus reads as "no sample" rather than as unhealthy.
  • The reactor walk sat inside the per-gauge-name loop, so every reactor was re-walked once per gauge name (~33x per node) while only two of those names consumed the result. It now runs once per node.
  • .labels() creates the child series and an un-set child exports as 0, so the value is resolved before .labels() is called; a metric with no source value stays absent instead of reading as a real zero.

The gauges were cached at module scope, so a Gauge child created for a
label set lived as long as the worker process. Those label sets carry
entity identity (lvol/lvol_name/pvc_name/device/...), so every volume
that had ever existed kept being exported.

Measured on a customer cluster (94 live volumes, ~1.2k volume
deletions/day):

  * 11,534 distinct pvc_name label sets still being exported
  * ~83 MB and ~5 s per scrape, growing ~7 MB/day
  * 15 WebAppAPI containers (5 services x 3 managers), each with its own
    accumulated registry, so a single Prometheus target answered by
    HAProxy round-robin returned a different series set every scrape --
    series flapped in and out and Grafana panels rendered empty
  * ~450 MiB RSS above a comparable app service, per container

Fix: build the registry per request, and build each gauge family exactly
once per request, before the entity loops. Both halves are required -- a
Gauge registers its name on construction, so constructing a family
inside the per-entity loops raises DuplicateTimeseries on the second
node/device/pool/volume.

After the equivalent change, customer scrapes went from 310,401 lines
(and 298,851 from a sibling container) to a stable 3,741 lines in 2-3 s,
identical across repeated scrapes, and the dashboards recovered.

Also in this endpoint, both inseparable from the rewrite:

  * health_check is Optional[bool]; Gauge.set(None) raises TypeError and
    would fail the whole scrape. Report NaN, which Prometheus reads as
    "no sample" rather than as unhealthy.
  * The reactor walk sat inside the per-gauge-name loop, so every reactor
    was re-walked once per gauge name (~33x per node) while only two of
    those names consumed the result. It now runs once per node.
  * .labels() creates the child series and an un-set child exports as 0,
    so the value is resolved before .labels() is called; a metric with no
    source value stays absent instead of reading as a real zero.
@wmousa
wmousa force-pushed the fix/v1-metrics-series-leak branch from a0894ff to a83e500 Compare August 27, 2026 13:54

@Hamdy-khader Hamdy-khader left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Great! Thanks Waleed

@Hamdy-khader
Hamdy-khader merged commit f33dd9d into R26.2-PRE Aug 27, 2026
11 of 17 checks passed
@Hamdy-khader
Hamdy-khader deleted the fix/v1-metrics-series-leak branch August 27, 2026 15:43
wmousa added a commit that referenced this pull request Sep 1, 2026
prometheus, thanos-sidecar and thanos-store are all `mode: global`, so a
3-manager swarm runs three of each. thanos-query was pointed at them by
bare service name:

    --store=thanos-store:10901
    --store=thanos-sidecar:10901

so it saw exactly one of each. Its own startup log shows it, printing one
line each instead of three:

    msg="adding new store with [storeEndpoints]"    address=thanos-store:10901
    msg="adding new sidecar with [storeEndpoints…]" address=thanos-sidecar:10901

Two separate prefixes are needed to fix it:

  * `dns+` makes Thanos treat the address as a DNS-discovered set and
    re-resolve it periodically, rather than as one static endpoint.
  * `tasks.` is required because these services use the default VIP
    endpoint mode, where the bare service name resolves to a single
    *virtual* IP. `dns+` alone would therefore still resolve to exactly one
    endpoint and fix nothing -- the routing mesh simply pins Thanos's
    long-lived gRPC connection to whichever task it first hit.
    `tasks.<service>` returns every task's real IP; prometheus.yml.j2
    already uses this idiom for tasks.node-exporter.

Why this caused "no data" alerts: the most recent ~2h of samples exist only
in each Prometheus's local TSDB and are served solely by *its own* sidecar;
only older blocks reach the object store. Grafana alert rules evaluate
recent data, so every evaluation depended on the single pinned sidecar.
When that sidecar was slow the query came back EMPTY rather than failing --
presenting as `noDataState: NoData` (empty result set) instead of
`execErrState: Error` -- and the alert self-cleared once it responded.

Seen on a customer cluster as recurring "no data" alerts whose underlying
Prometheus data was complete and healthy throughout
(scrape_samples_scraped a continuous 3.65k-5.15k, count(lvol_status_code)
a steady 90-140, never absent), alongside:

    "update of endpoint failed" err="getting metadata: fallback fetching
     info from thanos-sidecar:10901: rpc error: code = DeadlineExceeded"

Note this is only reproducible with 2+ manager nodes; on a single-manager
swarm there is one sidecar and the bug is invisible by construction.

Unrelated to the /cluster/metrics series leak fixed in #1281 -- a read-path
defect present since the monitoring stack was written. Same bug on main and
R26.3.
wmousa added a commit that referenced this pull request Sep 2, 2026
* fix(monitoring): thanos-query must discover all sidecars, not one

prometheus, thanos-sidecar and thanos-store are all `mode: global`, so a
3-manager swarm runs three of each. thanos-query was pointed at them by
bare service name:

    --store=thanos-store:10901
    --store=thanos-sidecar:10901

so it saw exactly one of each. Its own startup log shows it, printing one
line each instead of three:

    msg="adding new store with [storeEndpoints]"    address=thanos-store:10901
    msg="adding new sidecar with [storeEndpoints…]" address=thanos-sidecar:10901

Two separate prefixes are needed to fix it:

  * `dns+` makes Thanos treat the address as a DNS-discovered set and
    re-resolve it periodically, rather than as one static endpoint.
  * `tasks.` is required because these services use the default VIP
    endpoint mode, where the bare service name resolves to a single
    *virtual* IP. `dns+` alone would therefore still resolve to exactly one
    endpoint and fix nothing -- the routing mesh simply pins Thanos's
    long-lived gRPC connection to whichever task it first hit.
    `tasks.<service>` returns every task's real IP; prometheus.yml.j2
    already uses this idiom for tasks.node-exporter.

Why this caused "no data" alerts: the most recent ~2h of samples exist only
in each Prometheus's local TSDB and are served solely by *its own* sidecar;
only older blocks reach the object store. Grafana alert rules evaluate
recent data, so every evaluation depended on the single pinned sidecar.
When that sidecar was slow the query came back EMPTY rather than failing --
presenting as `noDataState: NoData` (empty result set) instead of
`execErrState: Error` -- and the alert self-cleared once it responded.

Seen on a customer cluster as recurring "no data" alerts whose underlying
Prometheus data was complete and healthy throughout
(scrape_samples_scraped a continuous 3.65k-5.15k, count(lvol_status_code)
a steady 90-140, never absent), alongside:

    "update of endpoint failed" err="getting metadata: fallback fetching
     info from thanos-sidecar:10901: rpc error: code = DeadlineExceeded"

Note this is only reproducible with 2+ manager nodes; on a single-manager
swarm there is one sidecar and the bug is invisible by construction.

Unrelated to the /cluster/metrics series leak fixed in #1281 -- a read-path
defect present since the monitoring stack was written. Same bug on main and
R26.3.

* fix(monitoring): give each Prometheus a replica label so Thanos can dedup

All three Prometheus replicas shared one hardcoded external label set:

    external_labels:
      monitor: 'codelab-monitor'

so every replica emitted series with byte-identical identity
({job, instance, monitor}). Two consequences:

  * thanos-query had nothing to deduplicate on, so a query merged three
    independent series claiming the same identity whose samples were taken
    at different seconds (observed: one replica scraping at :02, another at
    :56). The result is one interleaved, non-monotonic stream rather than a
    clean series -- unstable between evaluations for an alert rule using a
    `last` reducer over a short window.
  * all three sidecars uploaded blocks carrying identical external labels
    into the same bucket. Thanos treats those as overlapping and the
    compactor halts by default, consistent with a compactor that had done
    essentially nothing (18 MiB RSS, 0% CPU, 200 kB total network).

Thanos identifies HA replicas by a label that differs per replica and drops
it when deduplicating, so:

  * prometheus.yml.j2 gains `replica: '${REPLICA}'`;
  * prometheus gains --enable-feature=expand-external-labels, which expands
    ${REPLICA} from the environment. The indirection is required because
    prometheus.yml is bind-mounted -- every replica reads identical bytes and
    cannot self-identify from file content;
  * the compose sets REPLICA per task from the swarm node-hostname template;
  * thanos-query gains --query.replica-label=replica;
  * thanos-compactor gains --deduplication.replica-label=replica so it
    vertically compacts the overlap instead of halting on it.

Note for anyone editing prometheus.yml.j2: it is Jinja-rendered before
deployment, so a swarm template written literally with double braces in that
file is evaluated as a Jinja expression and breaks rendering. The swarm
template therefore lives in the compose file and the placeholder here is the
shell-style ${REPLICA}.

Verified: the template renders under Jinja with ${REPLICA} intact and
basic_auth substitution unaffected, and the compose parses with the expected
flags on all four services.

* fix(monitoring): run a single thanos-compactor, not one per manager

thanos-compactor was `mode: global`, so a 3-manager swarm ran three
compactors against the same object-storage bucket. Thanos requires exactly
one compactor per bucket; concurrent compactors rewriting the same blocks is
a documented data-corruption risk, and with halt-on-overlap the three also
contend for the same work.

More pressing after the previous commit: with
--deduplication.replica-label set the compactor performs vertical compaction
of the replicas' overlapping blocks, so three racing on the same blocks is
precisely the case Thanos warns about.

thanos-store and thanos-query stay `mode: global` -- both read-only and safe
to scale; only the compactor must be a singleton.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants