Skip to content

Saleor Core: the high performance, composable, headless commerce API.

feat(graphql): mark slow spans as errored (#19056)

Mikail471e4be44452
diff --git a/saleor/graphql/core/tests/test_view.py b/saleor/graphql/core/tests/test_view.py
index 448e2baeca..e5e2d0bd11 100644
--- a/saleor/graphql/core/tests/test_view.py
+++ b/saleor/graphql/core/tests/test_view.py
@@ -7,11 +7,13 @@ import graphene
import pytest
from django.shortcuts import render
from django.test import override_settings
+from freezegun import freeze_time
from graphql.execution.base import ExecutionResult
+from opentelemetry.trace import StatusCode
from .... import __version__ as saleor_version
from ....core.telemetry import Scope, Unit
-from ....tests.utils import get_metric_data
+from ....tests.utils import get_metric_data, get_span_by_name
from ...api import backend, schema
from ...metrics import METRIC_GRAPHQL_BATCH_SIZE
from ...tests.fixtures import API_PATH
@@ -538,3 +540,39 @@ def test_playground_is_rendered_with_proper_api_url_if_public_url_is_set(
"plugins_url": f"{expected_url_base}/plugins/",
},
)
+
+
+def test_marks_slow_queries(rf, get_test_spans):
+ request = rf.post(
+ path="/graphql/",
+ data={"query": "{__typename}"},
+ content_type="application/json",
+ )
+ view = GraphQLView(backend=backend, schema=schema)
+
+ with freeze_time("2025-10-13 12:00:00") as frozen_time:
+ original_handle_query = view._handle_query
+
+ def _inner_handle_query(*args, **kwargs):
+ """Artificially increases the current time by 31 seconds.
+
+ Executes once the GraphQL query is executed so that it
+ is incremented in the middle of the HTTP request (rather than
+ too soon or too late as otherwise it will not measure the duration properly).
+ """
+ frozen_time.tick(delta=31.0)
+ return original_handle_query(*args, **kwargs)
+
+ with patch.object(
+ view, "_handle_query", wraps=_inner_handle_query
+ ) as mocked_handle_query:
+ view.handle_query(request)
+
+ # Sanity check: should have ticked the time
+ mocked_handle_query.assert_called_once()
+ span = get_span_by_name(get_test_spans(), "/graphql/")
+
+ assert span.status.status_code == StatusCode.ERROR
+ assert (
+ span.status.description == "Slow request. Exceeded time limit of 30.0 seconds."
+ )
diff --git a/saleor/graphql/views.py b/saleor/graphql/views.py
index 3fd25309db..7d55bb55fb 100644
--- a/saleor/graphql/views.py
+++ b/saleor/graphql/views.py
@@ -1,6 +1,7 @@
import decimal
import hashlib
import importlib
+import time
from inspect import isclass
from typing import Any, cast
from urllib.parse import urljoin
@@ -206,6 +207,7 @@ class GraphQLView(View):
return JsonResponse(data=result, status=status_code, safe=False)
def handle_query(self, request: HttpRequest) -> JsonResponse:
+ request_start_time = time.monotonic()
with (
tracer.extract_context(request.headers) as context,
tracer.start_as_current_span(
@@ -255,6 +257,18 @@ class GraphQLView(View):
with observability.report_api_call(request) as api_call:
api_call.response = response
api_call.report()
+
+ request_duration = time.monotonic() - request_start_time
+
+ if request_duration > settings.GRAPHQL_SPANS_MARK_SLOW_AFTER:
+ error_description = f"Slow request. Exceeded time limit of {settings.GRAPHQL_SPANS_MARK_SLOW_AFTER} seconds."
+ error = RuntimeError(error_description)
+ # We want to mark this span as an error to indicate that the user may
+ # have received an HTTP 504 or a poor experience. This increases the
+ # chance of the trace being retained as it is less likely to be dropped
+ # by sampling.
+ span.set_status(status=StatusCode.ERROR, description=error_description)
+ span.record_exception(error)
return response
def get_response(
diff --git a/saleor/settings.py b/saleor/settings.py
index c059c19e98..5b8bb189c0 100644
--- a/saleor/settings.py
+++ b/saleor/settings.py
@@ -869,6 +869,10 @@ def SENTRY_INIT(dsn: str, sentry_opts: dict):
ignore_logger("graphql.execution.executor")
+# Number of seconds after which GraphQL requests will marked
+# as slow (error status)
+GRAPHQL_SPANS_MARK_SLOW_AFTER: float = 30.0
+
GRAPHQL_PAGINATION_LIMIT = 100
GRAPHQL_MIDDLEWARE: list[str] = []
GRAPHQL_BATCH_MAX_COUNT: int = int(os.environ.get("GRAPHQL_BATCH_MAX_COUNT", 1))