Skip to content

[surfacers.prometheus] Expire stale non-timestamped metrics after 4h - #1445

Merged
manugarg merged 2 commits into
mainfrom
prom-stale-metrics-expiration
Aug 30, 2026
Merged

manugarg merged 2 commits into
mainfrom
prom-stale-metrics-expiration

Conversation

@manugarg

@manugarg manugarg commented Aug 30, 2026 •

Copy link
Copy Markdown
Contributor

Problem

Metrics expiration in the Prometheus surfacer was derived from include_timestamp. Metrics we export without a timestamp were never expired, on the reasoning that the 10m deadline exists only to avoid Prometheus's warning about samples with timestamps older than 10 minutes — no timestamp, nothing to expire.

That conflated two different problems:

  1. This sample's timestamp is too old for Prometheus. — handled.
  2. This series belongs to a probe or target that no longer exists. — not handled at all.

The second has nothing to do with timestamps. A counter for a target that has gone away stayed in the /metrics output, and in memory, for the life of the process.

Change

Split the two concerns. A new per-type helper expirationAge() decides how long a metric is kept after its last update:

  • Timestamped metrics → 10m, unchanged (Prometheus's constraint).
  • Everything else → new stale_metrics_expiration_sec, defaulting to 4h.
  • stale_metrics_expiration_sec: 0 restores the old never-expire behavior; disable_metrics_expiration: true still turns off both deadlines. Negative values are rejected at startup rather than silently meaning "never".

isTimestamped() mirrors the dataWriter switch in New(), so the two can't drift apart.

Why 4h

Counter expiration was originally disabled because of long interval probes, so the default is deliberately generous. The two failure directions are not symmetric:

  • Expiring too early is a correctness failure. A series deleted in between two probe runs shows up as a gap and a counter reset on a probe that is working fine.
  • Expiring too late is a tidiness failure. A dead series lingers a few extra hours. A frozen counter yields rate() == 0 rather than garbage, so the real cost is just cloudprober's memory — which 4h still bounds.

4h leaves an hourly probe 4x of headroom. I didn't go higher because bounding memory under target churn is the point: a workload cycling pods would accumulate a full day of dead series at 24h.

Behavior changes

config before after
default: counters never 4h
default: histograms 10m 4h
default: gauges 10m 10m
include_timestamp: false nothing expires 4h for all
include_timestamp: true all at 10m all at 10m
disable_metrics_expiration: true nothing expires unchanged
disable_metrics_expiration: false, non-timestamped 10m 4h

Rows worth calling out:

  • Distributions are typed "histogram", not "counter", so they were already being expired at 10m despite carrying no timestamp. They now follow the same staleness deadline as counters.
  • include_timestamp: false is the only row that isn't strictly "collect garbage that was never collected" — those deployments go from nothing ever expires to everything expires at 4h.
  • disable_metrics_expiration: false now means what it says (expiration is not disabled) and composes with the new field, rather than pinning everything to 10m and silently ignoring stale_metrics_expiration_sec.

The last two both move in the keep-data-longer direction, and both escape hatches above cover anyone who disagrees.

Performance

deleteExpiredMetrics used to remove keys from pm.dataKeys one at a time, rescanning the slice per key. That was fine when only gauges expired; now counters do, and those are the families with one data key per target. Removing a probe with many targets would make a single sweep quadratic on the goroutine that also serves /metrics and drains emChan — stalling scrapes and dropping EventMetrics. Expired keys are now collected into a set and filtered out in one pass.

Notes

  • The sweep interval is derived from the shortest deadline in effect, so a stale_metrics_expiration_sec under 10m isn't silently rounded up. It's computed before the sweep goroutine starts, so the goroutine doesn't read surfacer fields it doesn't own.
  • Each sweep that deletes anything logs the count, so the one case that can surprise someone — a probe whose interval exceeds the staleness deadline — leaves a trail.
  • The 4h default lives only in the config proto and is read through the generated getter, so there's no second copy to drift.
  • config.pb.go was regenerated with the same toolchain the file was built with (protoc v6.33.5 / protoc-gen-go v1.36.11).

Testing

TestExpirationAge replaces TestDisableMetricsExpiration and covers the gauge/counter split across every include_timestamp and disable_metrics_expiration combination. TestStaleMetricsExpiration drives the new deadline end to end through the config; TestDeleteExpiredMetricsKeepsKeyOrder pins the single-pass filter's ordering and data/dataKeys consistency across a partial expiry; TestNegativeStaleMetricsExpiration covers the validation. Full surfacer suite passes under -race; vet and gofmt clean.

Metrics expiration was derived from include_timestamp: metrics we export
without a timestamp were never expired, because the 10m deadline exists
only to avoid Prometheus's warning about samples with old timestamps.

That conflated two different problems. "This sample's timestamp is too
old for Prometheus" is not the same as "this series belongs to a probe
or target that no longer exists", and nothing handled the second one. A
counter for a target that has gone away stayed in the /metrics output,
and in memory, for the life of the process.

Split the two. Timestamped metrics keep the 10m deadline. Everything
else is now dropped after stale_metrics_expiration_sec, new and
defaulting to 4h; 0 restores the old never-expire behavior, and an
explicit disable_metrics_expiration:true still turns off both.

Counter expiration was originally disabled because of long interval
probes, so the default is deliberately generous. The two failure
directions aren't symmetric: expiring a series that a slow probe is
still updating shows up as a gap and a counter reset on a probe that is
working fine, while expiring late only means a dead series lingers a few
extra hours. 4h leaves an hourly probe 4x of headroom while still
bounding memory under target churn.

Note that distributions are typed "histogram", not "counter", so they
were already being expired at 10m despite carrying no timestamp. They
now follow the same staleness deadline as counters.
Five follow-ups from review of the previous commit:

- deleteExpiredMetrics deleted keys from pm.dataKeys one at a time, and
  each delete rescanned the slice. That was tolerable when only gauges
  expired, but counters now expire too, and those are the families with
  one data key per target. Removing a probe with many targets would make
  a single sweep quadratic on the goroutine that also serves /metrics and
  drains emChan, so scrapes would stall and EventMetrics would be
  dropped. Collect the expired keys in a set and filter in one pass.

- disable_metrics_expiration:false pinned every metric to the 10m
  deadline, so setting it alongside stale_metrics_expiration_sec silently
  ignored the latter. It now means what it says -- expiration is not
  disabled -- and composes with the new field. This drops the last
  special case from expirationAge. Non-timestamped metrics under an
  explicit false go from 10m to the staleness deadline, which is the
  same keep-data-longer direction as the rest of the change.

- The sweep ticker was pinned to metricExpirationTime, silently rounding
  any stale_metrics_expiration_sec below 10m up to 10m. Derive it from
  the shortest deadline we actually have to honor. It's computed before
  the goroutine starts rather than inside it, so the goroutine doesn't
  read surfacer fields it doesn't own.

- Negative stale_metrics_expiration_sec was indistinguishable from the
  documented 0 ("keep forever"), so a typo silently disabled the feature
  being configured. Reject it in New().

- deleteExpiredMetrics was silent, leaving no trail for the one case
  where this series of changes can surprise someone: a probe whose
  interval exceeds the staleness deadline. Log the count per sweep.

Adds coverage for key order across a partial expiry, for the negative
and zero config values, and reworks TestStaleMetricsExpiration to drive
everything through the config instead of mutating a live surfacer, which
raced with the sweep goroutine under -race.
@manugarg manugarg changed the title [surfacers/prometheus] Expire stale non-timestamped metrics after 4h [surfacers.prometheus] Expire stale non-timestamped metrics after 4h Aug 30, 2026
@manugarg
manugarg merged commit bedf327 into main Aug 30, 2026
12 of 13 checks passed
@manugarg
manugarg deleted the prom-stale-metrics-expiration branch August 30, 2026 09:29
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.

1 participant