Skip to content

feat(metrics): Add experimental window sampling for trace metrics - #8320

Open
k-fish wants to merge 1 commit into
masterfrom
feat/metrics/add-window-sample
Open

k-fish wants to merge 1 commit into
masterfrom
feat/metrics/add-window-sample

Conversation

@k-fish

@k-fish k-fish commented Nov 18, 2026

Copy link
Copy Markdown
Member

Summary

We want to try introducing sampling for metrics to help with high volume cases. More details about why and why this specific approach here, but we'll likely be using window sampling.

tldr for window sampling; Each process's SDK keeps at most a fixed number of metrics per metric name per time window, it will pick which ones to keep at random (preferring ones attached to sampled spans to preserve trace-connectedness),and then marks each kept metric with its sample rate so we can scale counts back up.

I'm going to experiment with this for our Sentry SaaS python project since it has a.) a high number of processes to check that as a constraint b.) a rate-limit exceeding metric we can also test this design against, c.) nothing critical is using metrics, and finally d.) we should dogfood our own changes.

Sampling notes:

  • Window sampling re-using our existing buffer (for now, might tbd) to avoid too much extra code. Should not interfere with the existing code path when the experiment is off.
  • Each metric sets client_sample_rate = kept / seen per window (within the metric name) which is already accepted by relay.
  • We can possibly do an early sample call w/ should_capture to skip
  • Metric names can affect each other if either sample_rate is set very high per name or we have a large number of metric names per window (see more in doc), for most use cases (and certainly for ours) it shouldn't be a problem.

Other:

  • No public api change, putting per_name in experimental options for this reason, despite it being clunky.
  • Memory remains largely unchanged, we are keeping a few extra details per metric name but MAX_DROP means metric memory is bounded still.
  • A rate below 0.2/s are treated as 0.2/s for now until we allow for stretching windows across flushes (5s buffer window * 0.2/s works out to the minimum unit of 1 event). This also means only multiples of 0.2 work to change the reservoir size. Will probably change this later.
  • Using two reservoirs so that we can prefer having trace-connected metrics, simply doing sample_rand introduces bias towards particular traces.
  • It's an experiment right now, if this works well I'll write up a develop doc.

Behind an _experimental flag, we will add window sampling to allow for
better handling of high volume metric event data.
@k-fish
k-fish requested a review from a team as a code owner November 18, 2026 01:17
@github-actions

Copy link
Copy Markdown
Contributor

Coverage Results 📊

✅ 59522 passed | ⏭️ 3035 skipped | Total: 62557 | Pass Rate: 95.15% | Execution Time: 227m 19s

📊 Comparison with Base Branch

Metric Change
Total Tests 📉 -84545
Passed Tests 📉 -79723
Failed Tests —
Skipped Tests 📉 -4822

All tests are passing successfully.

✅ Patch coverage is 97.14% (102 of 105 changed executable lines covered; target 80%).
Project statement coverage is 90.15% (down 0.10 percentage points from base (1df5669) to head (c27cfa5)).

Changed files with executable lines (2)
File Patch coverage Changed executable lines
sentry_sdk/_metrics_batcher.py 96.91% 94/97 covered; missed: 54, 55, 92; partial branches: 91
sentry_sdk/_batcher.py 100.00% 8/8 covered
Coverage diff
@@            Coverage Diff             @@
##        master     #8320       +/-##
==========================================
- Coverage    90.25%    90.15%    -0.10%
==========================================
  Files          203       200        -3
  Tracked lines     27330     22181     -5149
  Branches     10242      7776     -2466
==========================================
- Hits         24665     19997     -4668
+ Misses        2665      2184      -481
+ Partials      1555      1274      -281

Generated by Coverage Action

@cursor cursor Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Cursor Bugbot has reviewed your changes and found 2 potential issues.

Fix All in Cursor

❌ Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, enable autofix in the Cursor dashboard.

Reviewed by Cursor Bugbot for commit c27cfa5. Configure here.

# Replacing a slot in a full reservoir doesn't need more memory, only
# a new slot does
if len(self._buffer) + self._held >= self.MAX_BEFORE_DROP:
return False

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Window close drops incoming metrics

Medium Severity

Closing a full window copies every reserved metric into _buffer up to MAX_BEFORE_DROP, then the same add still capacity-checks that buffer. The metric that closed the window, and any that arrive before the flusher drains, are discarded as queue_overflow even though that capacity is about to be freed. MAX_BEFORE_FLUSH is meant to leave headroom for this gap, but a window close can fill the buffer to the hard cap in one shot and wipe that headroom out.

Additional Locations (1)
Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit c27cfa5. Configure here.

# Replacing a slot in a full reservoir doesn't need more memory, only
# a new slot does
if len(self._buffer) + self._held >= self.MAX_BEFORE_DROP:
return False

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Empty reservoirs bypass memory bound

Medium Severity

A new metric name is inserted into _reservoirs before the MAX_BEFORE_DROP check. When that check fails, the empty list stays in the map and _held never counts it, so unique names arriving while at capacity can grow _reservoirs without bound until the window closes. That breaks the claim that metric memory stays bounded by MAX_BEFORE_DROP.

Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit c27cfa5. Configure here.

@alexander-alderman-webb alexander-alderman-webb 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.

The basis we inherited is not good, I'll write the same thing without all these locks that keep causing problems and update relevant conventions for you.

attributes = item["attributes"]
client_rate = attributes.get("sentry.client_sample_rate")
if isinstance(client_rate, (int, float)) and 0 < client_rate <= 1:
attributes["sentry.client_sample_rate"] = rate * client_rate

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.

Needs a conventions update, sentry.client_sample_rate is defined at the sample rate for a span.

@k-fish

k-fish commented Nov 18, 2026

Copy link
Copy Markdown
Member Author

The basis we inherited is not good, I'll write the same thing without all these locks that keep causing problems and update relevant conventions for you.

Appreciate it 👍 . Didn't know about our issues w/ locks. Let me know if you'd like me to take it on too, just give me an outline of the problem and I can chip away at it if you're busy.

Base automatically changed from major/3.0 to master November 23, 2026 08:56

This branch has not been deployed

No deployments
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