-
Notifications
You must be signed in to change notification settings - Fork 71
feat(exception-capture): add client-side token bucket rate limiting #662
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. Weβll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
hpouillot
wants to merge
4
commits into
main
Choose a base branch
from
feat/exception-bucketed-rate-limiter
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
7d14f38
feat(exception-capture): add client-side token bucket rate limiting
hpouillot 38a5953
feat(exception-capture): make rate limiting configurable
hpouillot 3ffa1eb
feat(exception-capture): raise default rate limits for server workloads
hpouillot c540a53
feat(exception-capture): make rate limiting opt-in
hpouillot File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,5 @@ | ||
| --- | ||
| pypi/posthog: minor | ||
| --- | ||
|
|
||
| Add opt-in client-side rate limiting for exception autocapture, using the same token bucket algorithm as the posthog-js and posthog-node SDKs: a bucket per exception type allows a burst of captures, then refills over time. Rate-limited exceptions are skipped before they reach the ingestion queue. Disabled by default; enable with the new `enable_exception_autocapture_rate_limiting` client option and tune via `exception_autocapture_bucket_size` (default 50), `exception_autocapture_refill_rate` (default 10), and `exception_autocapture_refill_interval_seconds` (default 10). |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,119 @@ | ||
| # Python port of the posthog-js BucketedRateLimiter: | ||
| # https://github.com/PostHog/posthog-js/blob/main/packages/core/src/utils/bucketed-rate-limiter.ts | ||
| # Kept behaviorally identical so rate limiting is consistent across SDKs. | ||
|
|
||
| import logging | ||
| import threading | ||
| import time | ||
| from typing import Callable, Dict, Hashable, Optional, Union | ||
|
|
||
| ONE_DAY_IN_SECONDS = 86400.0 | ||
|
|
||
| log = logging.getLogger("posthog") | ||
|
|
||
| Number = Union[int, float] | ||
|
|
||
|
|
||
| def _clamp_to_range(value, min_value: Number, max_value: Number, label: str) -> Number: | ||
| if isinstance(value, bool) or not isinstance(value, (int, float)): | ||
| log.warning(f"{label} must be a number. Using max value {max_value}.") | ||
| return max_value | ||
| if value > max_value: | ||
| log.warning(f"{label} cannot be greater than {max_value}. Using {max_value}.") | ||
| return max_value | ||
| if value < min_value: | ||
| log.warning(f"{label} cannot be less than {min_value}. Using {min_value}.") | ||
| return min_value | ||
| return value | ||
|
|
||
|
|
||
| class _Bucket: | ||
| __slots__ = ("tokens", "last_access") | ||
|
|
||
| def __init__(self, tokens: Number, last_access: float): | ||
| self.tokens = tokens | ||
| self.last_access = last_access | ||
|
|
||
|
|
||
| class BucketedRateLimiter: | ||
| """Token bucket rate limiter that tracks a separate bucket per key. | ||
|
|
||
| Each key starts with a full bucket of ``bucket_size`` tokens and every | ||
| call to :meth:`consume_rate_limit` consumes one token. ``refill_rate`` | ||
| tokens are restored per elapsed ``refill_interval_seconds`` (whole | ||
| intervals only, fractional elapsed time is carried over), capped at | ||
| ``bucket_size``. | ||
|
|
||
| The call that empties a bucket is itself reported as rate limited β a | ||
| burst over a fresh bucket lets ``bucket_size - 1`` events through before | ||
| limiting kicks in β and ``on_bucket_rate_limited`` fires once each time a | ||
| bucket is drained. | ||
|
|
||
| Thread-safe. ``clock`` must return seconds and is injectable for tests. | ||
| """ | ||
|
|
||
| def __init__( | ||
| self, | ||
| bucket_size: Number, | ||
| refill_rate: Number, | ||
| refill_interval_seconds: Number, | ||
| on_bucket_rate_limited: Optional[Callable[[Hashable], None]] = None, | ||
| clock: Callable[[], float] = time.monotonic, | ||
| ): | ||
| self._bucket_size = _clamp_to_range(bucket_size, 0, 100, "bucket_size") | ||
| self._refill_rate = _clamp_to_range( | ||
| refill_rate, 0, self._bucket_size, "refill_rate" | ||
| ) | ||
| self._refill_interval = _clamp_to_range( | ||
| refill_interval_seconds, 0, ONE_DAY_IN_SECONDS, "refill_interval_seconds" | ||
| ) | ||
| self._on_bucket_rate_limited = on_bucket_rate_limited | ||
| self._clock = clock | ||
| self._buckets: Dict[Hashable, _Bucket] = {} | ||
| self._lock = threading.Lock() | ||
|
|
||
| def _apply_refill(self, bucket: _Bucket, now: float) -> None: | ||
| if self._refill_interval <= 0: | ||
| bucket.tokens = self._bucket_size | ||
| bucket.last_access = now | ||
| return | ||
|
|
||
| elapsed = now - bucket.last_access | ||
| refill_intervals = int(elapsed // self._refill_interval) | ||
|
|
||
| if refill_intervals > 0: | ||
| tokens_to_add = refill_intervals * self._refill_rate | ||
| bucket.tokens = min(bucket.tokens + tokens_to_add, self._bucket_size) | ||
| # advance by whole intervals so fractional elapsed time still | ||
| # counts towards the next refill | ||
| bucket.last_access += refill_intervals * self._refill_interval | ||
|
|
||
| def consume_rate_limit(self, key: Hashable) -> bool: | ||
| """Consume one token for ``key``. Returns True if rate limited.""" | ||
| callback = None | ||
|
|
||
| with self._lock: | ||
| now = self._clock() | ||
| bucket = self._buckets.get(key) | ||
|
|
||
| if bucket is None: | ||
| bucket = _Bucket(tokens=self._bucket_size, last_access=now) | ||
| self._buckets[key] = bucket | ||
| else: | ||
| self._apply_refill(bucket, now) | ||
|
|
||
| if bucket.tokens <= 0: | ||
| return True | ||
|
|
||
| bucket.tokens -= 1 | ||
| rate_limited = bucket.tokens <= 0 | ||
| if rate_limited: | ||
| callback = self._on_bucket_rate_limited | ||
|
|
||
| if callback is not None: | ||
| callback(key) | ||
| return rate_limited | ||
|
|
||
| def stop(self) -> None: | ||
| with self._lock: | ||
| self._buckets.clear() |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
is this the correct order with chained exceptions? I think that might consume the top-level one instead, i.e.
RuntimeError from ZeroDivisionErrorconsumes RuntimeError instead of ZeroDivisionErrorI think this fails, but we'd want it to pass?