Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

fix(query): add retry hint to clickhouse capacity responses (#108573)

Vasco de Krijgereb1c59ca8c24
diff --git a/posthog/api/test/test_query.py b/posthog/api/test/test_query.py
index 101c540025b8..3a611e49886a 100644
--- a/posthog/api/test/test_query.py
+++ b/posthog/api/test/test_query.py
@@ -120,6 +120,7 @@ class TestQuery(ClickhouseTestMixin, APIBaseTest):
{"query": HogQLQuery(query="select 1").model_dump()},
)
self.assertEqual(response.status_code, ClickHouseQueryTimeOut.status_code)
+ self.assertNotIn("Retry-After", response)
self.assertEqual(mock_capture.called, expect_capture)
@parameterized.expand(
diff --git a/posthog/exceptions.py b/posthog/exceptions.py
index 0fe392a6d8b2..eb7aafabce89 100644
--- a/posthog/exceptions.py
+++ b/posthog/exceptions.py
@@ -1,3 +1,4 @@
+import random
from typing import Any, Optional, Protocol, TypedDict
from django.http.request import HttpRequest
@@ -83,11 +84,17 @@ class DatabaseSchemaUnavailable(APIException):
class ClickHouseAtCapacity(APIException):
+ wait: int
status_code = 503
default_detail = (
"Queries are a little too busy right now. We're working to free up resources. Please try again later."
)
+ def __init__(self, detail: Optional[str] = None, code: Optional[str] = None) -> None:
+ super().__init__(detail=detail, code=code)
+ # Spread retries across requests while keeping a minimum recovery window.
+ self.wait = random.randint(30, 60)
+
class QueryRanConcurrently(APIException):
"""Raised by a query single flight follower whose leader left nothing to serve or rebuild: the
diff --git a/posthog/session_recordings/session_recording_api.py b/posthog/session_recordings/session_recording_api.py
index 9cc4fcd5f3b4..8eb6bf4d88db 100644
--- a/posthog/session_recordings/session_recording_api.py
+++ b/posthog/session_recordings/session_recording_api.py
@@ -752,6 +752,16 @@ def get_replay_listing_throttle_error(request, view) -> str | None:
return None
+class SessionRecordingAtCapacity(Throttled):
+ wait: int
+ default_detail = "ClickHouse is at capacity. Try again later."
+
+ def __init__(self, *, wait: int) -> None:
+ # Passing wait to Throttled's constructor also changes the response body.
+ super().__init__()
+ self.wait = wait
+
+
class SharingTokenReplayThrottle(SimpleRateThrottle):
"""Per-token cap for replay endpoints reached via a sharing-token authenticator."""
@@ -927,9 +937,9 @@ class SessionRecordingViewSet(
)
return response
- except ClickHouseAtCapacity:
+ except ClickHouseAtCapacity as e:
_count_session_recording_throttled(location="clickhouse_at_capacity", auth_type=auth_type)
- raise Throttled(detail="ClickHouse is at capacity. Try again later.")
+ raise SessionRecordingAtCapacity(wait=e.wait) from e
except (ExposedHogQLError, ExposedCHQueryError) as e:
# A bad filter or query (e.g. a property referencing a field that doesn't exist on the
# event) is the caller's problem, not a server error. Surface the actual reason as a 400
@@ -1441,7 +1451,10 @@ class SessionRecordingViewSet(
status.HTTP_503_SERVICE_UNAVAILABLE if is_ch_error else status.HTTP_500_INTERNAL_SERVER_ERROR
)
- return Response({"error": message}, status=response_status)
+ response = Response({"error": message}, status=response_status)
+ if isinstance(e, ClickHouseAtCapacity):
+ response["Retry-After"] = str(e.wait)
+ return response
def _maybe_report_recording_list_filters_changed(self, request: request.Request, team: Team):
"""
diff --git a/posthog/session_recordings/test/test_session_recordings.py b/posthog/session_recordings/test/test_session_recordings.py
index 999cb84a6681..6f9aeb1828e2 100644
--- a/posthog/session_recordings/test/test_session_recordings.py
+++ b/posthog/session_recordings/test/test_session_recordings.py
@@ -1372,16 +1372,20 @@ class TestSessionRecordings(APIBaseTest, ClickhouseTestMixin, QueryMatchingTest)
"at_capacity",
ClickHouseAtCapacity(),
"ClickHouse is at capacity. Try again later.",
+ "37",
),
(
"timeout_exceeded",
ServerException("CHQueryErrorTimeoutExceeded"),
"Query timeout exceeded. Try again later.",
+ None,
),
]
)
@patch("posthog.session_recordings.queries.session_recording_list_from_query.SessionRecordingListFromQuery.run")
- def test_session_recordings_query_errors(self, _name, exception, expected_message, mock_run):
+ def test_session_recordings_query_errors(self, _name, exception, expected_message, expected_retry_after, mock_run):
+ if isinstance(exception, ClickHouseAtCapacity):
+ exception.wait = 37
mock_run.side_effect = exception
response = self.client.get(f"/api/projects/{self.team.id}/session_recordings")
assert response.status_code == status.HTTP_429_TOO_MANY_REQUESTS
@@ -1391,6 +1395,7 @@ class TestSessionRecordings(APIBaseTest, ClickhouseTestMixin, QueryMatchingTest)
"detail": expected_message,
"type": "throttled_error",
}
+ assert response.get("Retry-After") == expected_retry_after
@parameterized.expand(
[
@@ -1418,19 +1423,35 @@ class TestSessionRecordings(APIBaseTest, ClickhouseTestMixin, QueryMatchingTest)
# the real reason must reach the client, not a generic "internal server error"
assert expected_detail_substring in response.json()["detail"]
- def test_sync_execute_ch_at_capacity_retry_then_503(self):
- """Test that list_blocks throws ClickHouseAtCapacity multiple times and eventually returns 503"""
- call_count = 0
-
- def mock_list_blocks(*args, **kwargs):
- nonlocal call_count
- call_count += 1
- raise ClickHouseAtCapacity()
+ @parameterized.expand(
+ [
+ (
+ "at_capacity",
+ ClickHouseAtCapacity(),
+ 6,
+ status.HTTP_503_SERVICE_UNAVAILABLE,
+ "ClickHouse over capacity. Please retry",
+ "37",
+ ),
+ (
+ "unexpected_error",
+ RuntimeError("Unexpected failure"),
+ 1,
+ status.HTTP_500_INTERNAL_SERVER_ERROR,
+ "An unexpected error has occurred. Please try again later.",
+ None,
+ ),
+ ]
+ )
+ def test_snapshot_query_errors(self, _name, exception, expected_attempts, expected_status, message, retry_after):
+ if isinstance(exception, ClickHouseAtCapacity):
+ exception.wait = 37
- # Patch list_blocks where it's imported and used in session_recording_v2_service
- with patch(
- "posthog.session_recordings.session_recording_api.list_blocks",
- side_effect=mock_list_blocks,
+ with (
+ patch("posthog.session_recordings.session_recording_api.list_blocks", side_effect=exception) as list_blocks,
+ patch(
+ "posthog.session_recordings.session_recording_api.SessionRecordingViewSet._gather_session_recording_sources.retry.sleep"
+ ),
):
session_id = str(uuid7())
self.produce_replay_summary("user", session_id, now() - relativedelta(days=1))
@@ -1439,9 +1460,10 @@ class TestSessionRecordings(APIBaseTest, ClickhouseTestMixin, QueryMatchingTest)
f"/api/projects/{self.team.id}/session_recordings/{session_id}/snapshots?blob_v2=true"
)
- # Verify the error was called multiple times and we get 503
- assert call_count > 2, f"Expected multiple calls, got {call_count}"
- assert response.status_code == status.HTTP_503_SERVICE_UNAVAILABLE
+ assert list_blocks.call_count == expected_attempts
+ assert response.status_code == expected_status
+ assert response.json() == {"error": message}
+ assert response.get("Retry-After") == retry_after
@patch(
"posthog.session_recordings.session_recording_api.SessionRecordingViewSet._delete_via_recording_api",
diff --git a/posthog/test/test_exceptions.py b/posthog/test/test_exceptions.py
index 13d78dadde26..f0c8c2284219 100644
--- a/posthog/test/test_exceptions.py
+++ b/posthog/test/test_exceptions.py
@@ -1,3 +1,7 @@
+from random import Random
+
+from unittest.mock import patch
+
from django.http import HttpRequest
from django.test import RequestFactory, SimpleTestCase, override_settings
@@ -10,7 +14,46 @@ from rest_framework.exceptions import (
ValidationError,
)
-from posthog.exceptions import exception_handler
+from posthog.exceptions import ClickHouseAtCapacity, ClickHouseQueryTimeOut, QueryRanConcurrently, exception_handler
+
+
+class TestQueryRetryAfter(SimpleTestCase):
+ @parameterized.expand(
+ [
+ ("capacity", ClickHouseAtCapacity, 0, 503, "57"),
+ ("capacity_minimum", ClickHouseAtCapacity, 31, 503, "30"),
+ ("capacity_maximum", ClickHouseAtCapacity, 2, 503, "60"),
+ ("timeout", ClickHouseQueryTimeOut, 0, 504, None),
+ ("single_flight_follower", QueryRanConcurrently, 0, 503, None),
+ ]
+ )
+ def test_retry_after_is_only_advertised_for_capacity(
+ self,
+ _name: str,
+ exception_type: type[APIException],
+ seed: int,
+ expected_status: int,
+ expected_retry_after: str | None,
+ ) -> None:
+ with patch("random.randint", side_effect=Random(seed).randint):
+ response = exception_handler(exception_type(), {"request": RequestFactory().post("/api/projects/1/query/")})
+ assert response is not None
+ self.assertEqual(response.status_code, expected_status)
+ self.assertEqual(response.get("Retry-After"), expected_retry_after)
+
+ def test_capacity_retry_after_varies_between_errors_but_is_stable_for_each_error(self) -> None:
+ with patch("random.randint", side_effect=Random(0).randint):
+ for expected_retry_after in ("57", "42", "54"):
+ exception = ClickHouseAtCapacity(detail="Try again later.", code="busy")
+ for _ in range(2):
+ response = exception_handler(
+ exception, {"request": RequestFactory().post("/api/projects/1/query/")}
+ )
+ assert response is not None
+ self.assertEqual(response.status_code, 503)
+ self.assertEqual(response["Retry-After"], expected_retry_after)
+ self.assertEqual(response.data["detail"], "Try again later.")
+ self.assertEqual(response.data["code"], "busy")
@override_settings(SITE_URL="https://us.posthog.com")
diff --git a/products/endpoints/backend/exceptions.py b/products/endpoints/backend/exceptions.py
index de893992b23a..0dff9f9e6854 100644
--- a/products/endpoints/backend/exceptions.py
+++ b/products/endpoints/backend/exceptions.py
@@ -13,9 +13,14 @@ class EndpointQueryTooExpensive(APIException):
class EndpointAtCapacity(APIException):
"""Shared ClickHouse pool momentarily at capacity — transient; materializing gives isolated compute."""
+ wait: int
status_code = status.HTTP_503_SERVICE_UNAVAILABLE
default_code = "query_capacity"
default_detail = (
"Queries are momentarily at capacity — please retry shortly. For consistently heavy "
"endpoints, materialize to run on dedicated endpoint compute that isn't affected by shared query load."
)
+
+ def __init__(self, *, wait: int) -> None:
+ super().__init__()
+ self.wait = wait
diff --git a/products/endpoints/backend/logic/execution.py b/products/endpoints/backend/logic/execution.py
index 2d2ec61fa072..e4ea861f53a8 100644
--- a/products/endpoints/backend/logic/execution.py
+++ b/products/endpoints/backend/logic/execution.py
@@ -643,11 +643,11 @@ class EndpointExecutionService(PydanticModelMixin):
code, detail = _query_performance_code_and_detail(e)
logger.warning("Endpoint query hit a performance limit", endpoint_name=endpoint.name, reason=error_label)
raise EndpointQueryTooExpensive(detail, code=code)
- except ClickHouseAtCapacity:
+ except ClickHouseAtCapacity as e:
execution_status = "capacity"
error_label = "ClickHouseAtCapacity"
logger.warning("Endpoint query hit shared ClickHouse capacity", endpoint_name=endpoint.name)
- raise EndpointAtCapacity()
+ raise EndpointAtCapacity(wait=e.wait) from e
except Exception as e:
execution_status = "error"
error_label = type(e).__name__
diff --git a/products/endpoints/backend/tests/test_endpoint_execution.py b/products/endpoints/backend/tests/test_endpoint_execution.py
index a572ba00060c..50a2dfb26951 100644
--- a/products/endpoints/backend/tests/test_endpoint_execution.py
+++ b/products/endpoints/backend/tests/test_endpoint_execution.py
@@ -16,7 +16,7 @@ from posthog.schema import EventsNode, TrendsQuery
from posthog.hogql.errors import ExposedHogQLError
from posthog.errors import CHQueryErrorNoCommonType
-from posthog.exceptions import APIQueriesBudgetExceeded
+from posthog.exceptions import APIQueriesBudgetExceeded, ClickHouseAtCapacity
from products.data_modeling.backend.facade.models import DataModelingJob, DataWarehouseSavedQuery
from products.endpoints.backend.logic.execution import EndpointExecutionService, _emit_endpoint_failure_signal
@@ -226,6 +226,37 @@ class TestEndpointExecution(ClickhouseTestMixin, APIBaseTest):
mock_signal.assert_not_called()
mock_capture.assert_not_called()
+ def test_capacity_error_preserves_retry_after(self):
+ endpoint = create_endpoint_with_version(
+ name="at_capacity",
+ team=self.team,
+ query={"kind": "HogQLQuery", "query": "SELECT count() FROM events"},
+ created_by=self.user,
+ is_active=True,
+ )
+ error = ClickHouseAtCapacity()
+ error.wait = 37
+
+ with mock.patch("products.endpoints.backend.logic.execution.process_query_model", side_effect=error):
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/endpoints/{endpoint.name}/run/", {}, format="json"
+ )
+
+ self.assertEqual(response.status_code, status.HTTP_503_SERVICE_UNAVAILABLE)
+ self.assertEqual(
+ response.json(),
+ {
+ "type": "server_error",
+ "code": "query_capacity",
+ "detail": (
+ "Queries are momentarily at capacity — please retry shortly. For consistently heavy "
+ "endpoints, materialize to run on dedicated endpoint compute that isn't affected by shared query load."
+ ),
+ "attr": None,
+ },
+ )
+ self.assertEqual(response.get("Retry-After"), "37")
+
def test_hogql_endpoint_executes_with_variable_override(self):
endpoint = create_endpoint_with_version(
name="hogql_var_override",