Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
37 commits
Select commit Hold shift + click to select a range
0cb3e73
feat: Add sliding window to lock free metrics batcher
alexander-alderman-webb Nov 18, 2026
c800bc7
merge
alexander-alderman-webb Nov 18, 2026
84db651
merge and simplify tests
alexander-alderman-webb Nov 18, 2026
21fd75e
per thread state
alexander-alderman-webb Nov 18, 2026
343bef6
simplify more
alexander-alderman-webb Nov 18, 2026
ff10f51
Merge branch 'webb/sliding-window-metrics-batcher' into webb/sliding-…
alexander-alderman-webb Nov 18, 2026
7e49836
only use class if option set
alexander-alderman-webb Nov 18, 2026
14893a6
simplify
alexander-alderman-webb Nov 18, 2026
183d1a1
simplify again
alexander-alderman-webb Nov 18, 2026
5181903
remove some tests
alexander-alderman-webb Nov 18, 2026
c626961
remove indirection and tests
alexander-alderman-webb Nov 18, 2026
33aa0d7
.
alexander-alderman-webb Nov 18, 2026
4afc3ba
simplify
alexander-alderman-webb Nov 18, 2026
3f07315
merge
alexander-alderman-webb Nov 18, 2026
4fdf682
fix typo
alexander-alderman-webb Nov 18, 2026
7ed73d5
iteration clean up
alexander-alderman-webb Nov 18, 2026
c7cc2dd
remove indirection
alexander-alderman-webb Nov 18, 2026
3119a60
fix
alexander-alderman-webb Nov 18, 2026
44d2d61
iterate on tests
alexander-alderman-webb Nov 19, 2026
eb22208
make test intersting
alexander-alderman-webb Nov 19, 2026
eaf3ab6
fix client options
alexander-alderman-webb Nov 19, 2026
3f45ee5
.
alexander-alderman-webb Nov 19, 2026
cb36693
simplify test
alexander-alderman-webb Nov 19, 2026
4ce601c
merge
alexander-alderman-webb Nov 19, 2026
ffc6b96
Merge branch 'webb/sliding-window-metrics-batcher' into webb/sliding-…
alexander-alderman-webb Nov 19, 2026
c89e37d
inline _merge()
alexander-alderman-webb Nov 19, 2026
7967d7f
use list.copy() for consistency
alexander-alderman-webb Nov 19, 2026
f38f3a9
remove comment in consts.py
alexander-alderman-webb Nov 20, 2026
5e08286
add 0.05 second delay before harvesting
alexander-alderman-webb Nov 20, 2026
525cb85
do not share limit between sampled and unsampled metrics
alexander-alderman-webb Nov 20, 2026
e5ae8c9
simplify iteration over retired windows
alexander-alderman-webb Nov 20, 2026
008f662
store counter on window instead of thread state
alexander-alderman-webb Nov 20, 2026
cbcd999
remove unnecessary early returns
alexander-alderman-webb Nov 20, 2026
7442556
always emit client report for sample_rate
alexander-alderman-webb Nov 20, 2026
b617d12
merge
alexander-alderman-webb Nov 20, 2026
c304ece
remove misleading comment
alexander-alderman-webb Nov 20, 2026
2caf187
clamp options in client instead of batcher
alexander-alderman-webb Nov 20, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 0 additions & 2 deletions sentry_sdk/_batcher.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,6 @@


class Batcher(Generic[T]):
MAX_BEFORE_FLUSH = 100
MAX_BEFORE_DROP = 1_000
FLUSH_WAIT_TIME = 5.0

TYPE = ""
Expand Down
169 changes: 159 additions & 10 deletions sentry_sdk/_lock_free_metrics_batcher.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
import bisect
import itertools
import os
import random
import threading
from collections import deque
import time
from collections import defaultdict, deque
from datetime import datetime, timezone
from typing import TYPE_CHECKING

Expand All @@ -17,9 +21,42 @@
from sentry_sdk._types import Metric


class _Reservoir:
__slots__ = ("kept", "seen")

def __init__(self) -> None:
self.kept: "list[Metric]" = []
self.seen = 0


class _ThreadState:
"""The metrics collected by one thread in a given window."""

__slots__ = ("reservoirs",)

def __init__(self) -> None:
self.reservoirs: "defaultdict[str, _Reservoir]" = defaultdict(_Reservoir)


class _Window:
"""
One time window in which multiple threads concurrently capture metrics.
Only the thread with the given identifier should change its local state.
"""

__slots__ = ("start", "threads", "retire_claims", "number_kept")

def __init__(self) -> None:
self.start = time.monotonic()
self.threads: "defaultdict[int, _ThreadState]" = defaultdict(_ThreadState)
self.retire_claims: "list[object]" = []
self.number_kept = 0


class LockFreeMetricsBatcher(Batcher["Metric"]):
MAX_BEFORE_FLUSH = 1000
MAX_BEFORE_DROP = 10_000
MAX_UNSAMPLED_BEFORE_FLUSH = 1000
MAX_UNSAMPLED_BEFORE_DROP = 10_000
MAX_KEPT_PER_WINDOW = 10_000
FLUSH_WAIT_TIME = 5.0

TYPE = "trace_metric"
Expand All @@ -30,15 +67,26 @@ def __init__(
self,
capture_func: "Callable[[Envelope], None]",
record_lost_func: "Callable[..., None]",
window_sampling: "dict[str, float]",
) -> None:
super().__init__(capture_func, record_lost_func)

self._limits = {
name: int(rate * self.FLUSH_WAIT_TIME)
for name, rate in window_sampling.items()
}

self._queue: "deque[Metric]" = deque()
self._window = _Window()
self._retired: "deque[_Window]" = deque()
# Holds the claim of the one thread that gets to start the flusher.
self._flusher_claim: "dict[str, object]" = {}

def _reset_thread_state(self) -> None:
super()._reset_thread_state()
self._queue = deque()
self._window = _Window()
self._retired = deque()
self._flusher_claim = {}

def _ensure_thread(self) -> bool:
Expand Down Expand Up @@ -75,16 +123,59 @@ def add(self, item: "Metric") -> None:
if not self._ensure_thread():
return None

queue = self._queue
if len(queue) >= self.MAX_BEFORE_DROP:
self._record_lost(item)
return None
window = self._window
if time.monotonic() - window.start >= self.FLUSH_WAIT_TIME:
self._retire_window(window)
window = self._window

queue.append(item)
if len(queue) < self.MAX_BEFORE_FLUSH or self._flush_event.is_set():
limit = self._limits.get(item["name"])
if limit is None:
if len(self._queue) >= self.MAX_UNSAMPLED_BEFORE_DROP:
self._record_lost(item)
return None

self._queue.append(item)
if (
len(self._queue) < self.MAX_UNSAMPLED_BEFORE_FLUSH
or self._flush_event.is_set()
):
return

self._flush_event.set()
return

self._flush_event.set()
self._add_to_window(item, window, limit)
Comment thread
cursor[bot] marked this conversation as resolved.
Resolved

def _add_to_window(self, item: "Metric", window: "_Window", limit: int) -> None:
state = window.threads[threading.get_ident()]
reservoir = state.reservoirs[item["name"]]
reservoir.seen += 1
if (
len(reservoir.kept) < limit
and window.number_kept < self.MAX_KEPT_PER_WINDOW
):
window.number_kept += 1
Comment thread
alexander-alderman-webb marked this conversation as resolved.
Resolved
reservoir.kept.append(item)
return

index = random.randrange(reservoir.seen)
if index >= len(reservoir.kept):
return

reservoir.kept[index] = item
Comment thread
cursor[bot] marked this conversation as resolved.
Resolved

def _retire_window(self, window: "_Window") -> None:
claim = object()
window.retire_claims.append(claim)
if window.retire_claims[0] is not claim:
return

self._window = _Window()
self._retired.append(window)

def flush(self) -> None:
self._retire_window(self._window)
super().flush()

def _flush(self) -> "Optional[Envelope]":
queue = self._queue
Expand All @@ -96,6 +187,32 @@ def _flush(self) -> "Optional[Envelope]":
except IndexError:
break

sampled_out = 0

now = time.monotonic()
window = self._window
if now - window.start >= self.FLUSH_WAIT_TIME:
self._retire_window(window)

for window in self._retired.copy():
if (
threading.current_thread() is self._flusher
and now - window.start < self.FLUSH_WAIT_TIME + 0.05
):
break
try:
window = self._retired.popleft()
except IndexError:
break
sampled_out += self._harvest(window, items)

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.

Wondering if we should decouple the harvesting from the flush somehow, or at least introduce some small delay in between. A recently retired window might probably still have a thread writing to it, if the write was initiated before it was retired, so we might be losing some metrics there.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

I've added another 0.05 seconds delay so there's at least a guaranteed buffer since I couldn't come up with a good synchronization mechanism to strictly not lose any metrics.
See 5e08286


if sampled_out:
self._record_lost_func(
reason="sample_rate",
data_category=self.CLIENT_REPORT_TYPE,
quantity=sampled_out,
)

if not items:
return None

Expand All @@ -106,6 +223,38 @@ def _flush(self) -> "Optional[Envelope]":
self._capture_func(envelope)
return envelope

def _harvest(self, window: "_Window", items: "list[Metric]") -> int:
by_name: "dict[str, list[_Reservoir]]" = {}
for state in window.threads.copy().values():
for name, reservoir in state.reservoirs.copy().items():
by_name.setdefault(name, []).append(reservoir)

sampled_out = 0
for name, reservoirs in by_name.items():
limit = self._limits[name]
bounds = list(
itertools.accumulate(reservoir.seen for reservoir in reservoirs)
)
slots = [0] * len(reservoirs)
for position in random.sample(range(bounds[-1]), min(limit, bounds[-1])):
slots[bisect.bisect_right(bounds, position)] += 1

kept: "list[Metric]" = []
for reservoir, count in zip(reservoirs, slots):
thread_kept = reservoir.kept.copy()
kept.extend(random.sample(thread_kept, min(count, len(thread_kept))))
if not kept:
sampled_out += bounds[-1]
continue

items.extend(kept)
rate = len(kept) / bounds[-1]
for item in kept:
item["attributes"]["sentry.client_sample_rate"] = rate
sampled_out += bounds[-1] - len(kept)

return sampled_out

@staticmethod
def _to_transport_format(item: "Metric") -> "Any":
res = {
Expand Down
57 changes: 53 additions & 4 deletions sentry_sdk/client.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import math
import os
import random
import socket
Expand All @@ -9,6 +10,7 @@
from typing import TYPE_CHECKING, Dict, cast, overload

from sentry_sdk._compat import check_uwsgi_thread_support
from sentry_sdk._lock_free_metrics_batcher import LockFreeMetricsBatcher
from sentry_sdk._log_batcher import LogBatcher
from sentry_sdk._metrics_batcher import MetricsBatcher
from sentry_sdk._span_batcher import SpanBatcher
Expand Down Expand Up @@ -128,6 +130,43 @@ def _get_options(*args: "Optional[str]", **kwargs: "Any") -> "Dict[str, Any]":

rv["data_collection"] = _resolve_data_collection(rv)

window_sampling = rv["_experiments"].get("metrics_window_sampling")
if window_sampling is not None:
valid_rates = {}
if isinstance(window_sampling, dict):
for name, rate in window_sampling.items():
if (
isinstance(rate, bool)
or not isinstance(rate, (int, float))
or not math.isfinite(rate)
or rate <= 0
):
logger.warning(
"[Metrics] Given window sampling rate for %s is invalid. It must be a positive number. Got %s, not sampling it.",
name,
rate,
)
continue

clamped = min(max(rate, 0.2), 2000)
if clamped != rate:
logger.warning(
"[Metrics] Window sampling rate for %s must be between 0.2 and 2000 metrics per second. Got %s, using %s.",
name,
rate,
clamped,
)
valid_rates[name] = clamped
else:
logger.warning(
"[Metrics] metrics_window_sampling must map metric names to rates. Got %s, not sampling.",
window_sampling,
)
rv["_experiments"] = {
**rv["_experiments"],
"metrics_window_sampling": valid_rates,
}

if rv["socket_options"] and not isinstance(rv["socket_options"], list):
logger.warning(
"Ignoring socket_options because of unexpected format. See urllib3.HTTPConnection.socket_options for the expected format."
Expand Down Expand Up @@ -160,7 +199,7 @@ def __init__(self, options: "Optional[Dict[str, Any]]" = None) -> None:
self.transport: "Optional[Transport]" = None
self.monitor: "Optional[Monitor]" = None
self.log_batcher: "Optional[LogBatcher]" = None
self.metrics_batcher: "Optional[MetricsBatcher]" = None
self.metrics_batcher: "Optional[Union[MetricsBatcher, LockFreeMetricsBatcher]]" = None
self.span_batcher: "Optional[SpanBatcher]" = None
self.integrations: "dict[str, Integration]" = {}

Expand Down Expand Up @@ -379,10 +418,20 @@ def _record_lost_event(
record_lost_func=_record_lost_event,
)

self.metrics_batcher = MetricsBatcher(
capture_func=_capture_envelope,
record_lost_func=_record_lost_event,
window_sampling = self.options["_experiments"].get(
"metrics_window_sampling"
)
if window_sampling:
self.metrics_batcher = LockFreeMetricsBatcher(
capture_func=_capture_envelope,
record_lost_func=_record_lost_event,
window_sampling=window_sampling,
)
else:
self.metrics_batcher = MetricsBatcher(
capture_func=_capture_envelope,
record_lost_func=_record_lost_event,
)

self.span_batcher = SpanBatcher(
capture_func=_capture_envelope,
Expand Down
1 change: 1 addition & 0 deletions sentry_sdk/consts.py
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,7 @@ class CompressionAlgo(Enum):
"transport_num_pools": Optional[int],
"transport_http2": Optional[bool],
"transport_async": Optional[bool],
"metrics_window_sampling": Optional[Dict[str, float]],
},
total=False,
)
Expand Down
Loading
Loading