From a9a5ba5928afdf34ce940c4511e4ca3a2e204838 Mon Sep 17 00:00:00 2001 From: Vjeran Grozdanic Date: Wed, 20 May 2026 13:52:07 +0200 Subject: [PATCH] perf(sdk): Use Django URL resolution for view-based trace sampling Add SAMPLED_VIEWS dict keyed by Django URL name, replacing the regex pattern approach with resolve()-based lookups. This avoids duplicating URL regexes and gives O(1) dict lookup instead of linear regex scans. Samples AI Conversations endpoints at 100% for rollout monitoring. --- src/sentry/utils/sdk.py | 21 +++++++++++++++++++-- 1 file changed, 19 insertions(+), 2 deletions(-) diff --git a/src/sentry/utils/sdk.py b/src/sentry/utils/sdk.py index b278c4d2c7fad5..977aab7aa98778 100644 --- a/src/sentry/utils/sdk.py +++ b/src/sentry/utils/sdk.py @@ -92,6 +92,13 @@ "/api/0/auth/validate/": 0.0, } +# Sample rates keyed by Django URL name (from urls.py `name=` kwarg). +# Uses resolve() so there's no need to duplicate URL regexes. +SAMPLED_VIEWS: dict[str, float] = { + "sentry-api-0-organization-ai-conversations": 1.0, + "sentry-api-0-organization-ai-conversation-details": 1.0, +} + if settings.ADDITIONAL_SAMPLED_TASKS: SAMPLED_TASKS.update(settings.ADDITIONAL_SAMPLED_TASKS) @@ -182,8 +189,18 @@ def get_project_key(): def traces_sampler(sampling_context): wsgi_path = sampling_context.get("wsgi_environ", {}).get("PATH_INFO") - if wsgi_path and wsgi_path in SAMPLED_ROUTES: - return SAMPLED_ROUTES[wsgi_path] + if wsgi_path: + if wsgi_path in SAMPLED_ROUTES: + return SAMPLED_ROUTES[wsgi_path] + if SAMPLED_VIEWS: + try: + from django.urls import resolve + + match = resolve(wsgi_path) + if match.url_name in SAMPLED_VIEWS: + return SAMPLED_VIEWS[match.url_name] + except Exception: + pass # Apply sample_rate from custom_sampling_context custom_sample_rate = sampling_context.get("sample_rate")