-
Notifications
You must be signed in to change notification settings - Fork 10
Rate Monitor: Per-org request rate alerting on high-cost endpoints #911
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
vprashrex
wants to merge
8
commits into
main
Choose a base branch
from
feat/threshold-monitor
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
8 commits
Select commit
Hold shift + click to select a range
6c502ea
feat: implement rate monitoring for API endpoints
vprashrex 4a77d05
feat: add threshold rates for monitoring LLM calls, collections, and …
vprashrex 4263c46
feat: update monitor_rate usage to accept dynamic category parameter
vprashrex 6b4ce6c
feat: add unit tests for rate_monitor and telemetry.record_rate_thres…
vprashrex b8d6f65
Merge branch 'main' into feat/threshold-monitor
vprashrex 5021d0d
feat: update monitor_rate to use project context instead of organization
vprashrex 9ffcc83
feat: update telemetry and rate_monitor to use project context instea…
vprashrex abd4725
feat: update rate_monitor and telemetry to use project context instea…
vprashrex 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
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
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,98 @@ | ||
| import logging | ||
| import time | ||
|
|
||
| from collections.abc import Callable | ||
| from typing import Literal | ||
|
|
||
| import redis | ||
|
|
||
| from app.api.deps import AuthContextDep | ||
| from app.core.config import settings | ||
|
|
||
| from app.core.telemetry import record_rate_threshold | ||
|
|
||
| logger = logging.getLogger(__name__) | ||
|
|
||
| # Categories of rates we want to monitor | ||
| RateCategory = Literal["llm_call", "collections", "evaluations"] | ||
|
|
||
| # THRESHOLD NUMBERS | ||
| THRESHOLDS: dict[RateCategory, int] = { | ||
| "llm_call": settings.THRESHOLD_LLM_CALL_RATE, | ||
| "collections": settings.THRESHOLD_COLLECTIONS_RATE, | ||
| "evaluations": settings.THRESHOLD_EVALUATIONS_RATE, | ||
| } | ||
|
|
||
| # Delete record after 2 minutes from redis | ||
| _EXPIRATION_SECONDS = 120 | ||
|
|
||
| _redis_client: redis.Redis = redis.from_url(settings.REDIS_URL, decode_responses=True) | ||
|
|
||
|
|
||
| # count incrementor after each request and get count | ||
| def increment_and_get_count(key: str) -> int | None: | ||
| """Increment the count for the given key and return the new count. | ||
| The count will automatically expire after _EXPIRATION_SECONDS. | ||
| """ | ||
| try: | ||
| pipe = _redis_client.pipeline() | ||
| pipe.incr(key) | ||
| pipe.expire(key, _EXPIRATION_SECONDS) | ||
| count, _ = pipe.execute() | ||
| return count | ||
| except Exception as e: | ||
| logger.error( | ||
| f"[increment_and_get_count] Error incrementing count for {key}: {e}" | ||
| ) | ||
| return None | ||
|
|
||
|
|
||
| def monitor_rate(category: RateCategory) -> Callable[[AuthContextDep], None]: | ||
| """Monitor the rate of events for the given category. If the rate exceeds the threshold, record it in telemetry. | ||
|
|
||
| Usage: | ||
| dependencies=[ | ||
| Depends(require_permission(Permission.REQUIRE_PROJECT)), | ||
| Depends(monitor_rate("{category}")), | ||
| ] | ||
| """ | ||
|
|
||
| def _checker(auth_context: AuthContextDep) -> None: | ||
| project = auth_context.project | ||
| if project is None: | ||
| return | ||
|
|
||
| threshold = THRESHOLDS.get(category, None) | ||
| if threshold is None: | ||
| logger.warning( | ||
| f"[monitor_rate] No threshold defined for category {category}" | ||
| ) | ||
| return | ||
|
|
||
| minute_bucket = int(time.time() // 60) | ||
| redis_key = f"rate_monitor:{category}:{project.id}:{minute_bucket}" | ||
|
|
||
| try: | ||
| count = increment_and_get_count(redis_key) | ||
| if count is not None and count == threshold + 1: | ||
| logger.warning( | ||
| f"[monitor_rate] Rate threshold exceeded for {category} in project {project.id}: count={count}" | ||
| ) | ||
| record_rate_threshold( | ||
| project_id=project.id, | ||
| project_name=project.name, | ||
| category=category, | ||
|
coderabbitai[bot] marked this conversation as resolved.
|
||
| request_count=count, | ||
| threshold=threshold, | ||
| ) | ||
|
|
||
| except redis.RedisError as e: | ||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
|
||
| logger.error( | ||
| "[monitor_rate] Redis unavailable, skipping rate check " | ||
| "(project_id=%s category=%s)", | ||
| project.id, | ||
| category, | ||
| exc_info=e, | ||
| ) | ||
|
|
||
| return _checker | ||
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.
increment and expire are not atomic; what if increment executes, system crashes, expire does not execute -- key will remain in redis forever