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): friendly concurrency-limit error + per-product block signal (#67985)

Lucas Ricoy2e469100add8
diff --git a/posthog/api/query.py b/posthog/api/query.py
index 2f8487ab6c2c..9f4b69f70fc8 100644
--- a/posthog/api/query.py
+++ b/posthog/api/query.py
@@ -1,5 +1,6 @@
import re
from time import perf_counter
+from typing import NoReturn
from django.core.cache import cache
from django.http import JsonResponse, StreamingHttpResponse
@@ -74,6 +75,11 @@ logger = structlog.get_logger(__name__)
tracer = trace.get_tracer(__name__)
+# Shown to the user when the org's concurrent-query limiter rejects a request. The raw limiter
+# exception embeds an internal Redis key + task id, so we log that for debugging and surface this
+# friendly message instead of leaking implementation details into the UI.
+CONCURRENCY_LIMIT_USER_MESSAGE = "Too many queries are running right now — please try again in a moment."
+
QUERY_VALIDATION_ERROR_TOTAL = Counter(
"posthog_query_validation_error_total",
"Query validation failures returned from the query API.",
@@ -162,6 +168,11 @@ class QueryViewSet(QueryCoalescingMixin, TeamAndOrgViewSetMixin, PydanticModelMi
return new_val
return False
+ def _raise_concurrency_throttled(self, exc: ConcurrencyLimitExceeded) -> NoReturn:
+ # Log the raw detail (Redis key + task id) for Loki, but surface a clean message to the user.
+ logger.warning("query_concurrency_limit_exceeded", detail=str(exc))
+ raise Throttled(detail=CONCURRENCY_LIMIT_USER_MESSAGE)
+
@extend_schema(
request=QueryRequest,
responses={
@@ -282,7 +293,7 @@ class QueryViewSet(QueryCoalescingMixin, TeamAndOrgViewSetMixin, PydanticModelMi
).inc()
raise
except ConcurrencyLimitExceeded as c:
- raise Throttled(detail=str(c))
+ self._raise_concurrency_throttled(c)
except Exception as e:
capture_exception(e)
raise
@@ -384,7 +395,7 @@ class QueryViewSet(QueryCoalescingMixin, TeamAndOrgViewSetMixin, PydanticModelMi
result = hogql_runner.calculate()
return Response(result.model_dump(), status=200)
except ConcurrencyLimitExceeded as c:
- raise Throttled(detail=str(c))
+ self._raise_concurrency_throttled(c)
except Exception as e:
capture_exception(e)
raise
diff --git a/posthog/api/test/test_query.py b/posthog/api/test/test_query.py
index ff221b0abb88..62092bfa060a 100644
--- a/posthog/api/test/test_query.py
+++ b/posthog/api/test/test_query.py
@@ -33,8 +33,10 @@ from posthog.schema import (
from posthog.hogql.constants import LimitContext
+from posthog.api.query import CONCURRENCY_LIMIT_USER_MESSAGE
from posthog.api.services.query import process_query_dict, process_query_model
from posthog.clickhouse.client import sync_execute
+from posthog.clickhouse.client.limit import ConcurrencyLimitExceeded
from posthog.clickhouse.query_tagging import Product, QueryTags
from posthog.models.utils import UUIDT
@@ -45,6 +47,20 @@ from products.product_analytics.backend.models.insight_variable import InsightVa
class TestQuery(ClickhouseTestMixin, APIBaseTest):
ENDPOINT = "query"
+ def test_concurrency_limit_returns_friendly_message_without_internal_key(self):
+ # A concurrency block must surface as a 429 with a user-facing message — not str(exc),
+ # which embeds the limiter's internal Redis key + task id and used to leak into the UI.
+ raw = "Exceeded maximum concurrency limit: 30 for key: app:query:per-org:abc and task: def"
+ with patch("posthog.api.query.process_query_model", side_effect=ConcurrencyLimitExceeded(raw)):
+ response = self.client.post(
+ f"/api/environments/{self.team.id}/query/",
+ {"query": HogQLQuery(query="select 1").model_dump()},
+ )
+ self.assertEqual(response.status_code, status.HTTP_429_TOO_MANY_REQUESTS)
+ detail = response.json()["detail"]
+ self.assertEqual(detail, CONCURRENCY_LIMIT_USER_MESSAGE)
+ self.assertNotIn("app:query:per-org", detail)
+
@snapshot_clickhouse_queries
def test_select_hogql_expressions(self):
with freeze_time("2020-01-10 12:00:00"):
diff --git a/posthog/clickhouse/client/limit.py b/posthog/clickhouse/client/limit.py
index 4cd67986335f..b8a4141ddde5 100644
--- a/posthog/clickhouse/client/limit.py
+++ b/posthog/clickhouse/client/limit.py
@@ -12,8 +12,9 @@ from prometheus_client import Counter
from posthog import redis, settings
from posthog.clickhouse.cluster import ExponentialBackoff
-from posthog.clickhouse.query_tagging import tag_queries
+from posthog.clickhouse.query_tagging import Product, add_fallback_query_tags, get_query_tags, tag_queries
from posthog.constants import AvailableFeature
+from posthog.schema_enums import ProductKey
from posthog.settings import TEST
from posthog.utils import generate_short_id
@@ -24,9 +25,14 @@ DEFAULT_APP_DASHBOARD_CONCURRENT_QUERIES = 6
CONCURRENT_QUERY_LIMIT_EXCEEDED_COUNTER = Counter(
"posthog_clickhouse_query_concurrency_limit_exceeded",
"Number of times a team tried to exceed concurrency limit.",
- ["task_name", "team_id", "limit", "limit_name", "result"],
+ ["task_name", "team_id", "limit", "limit_name", "result", "product"],
)
+# The `product` label is derived from query tags that originate in a client-supplied productKey.
+# Restricting it to known product values keeps the Prometheus series count bounded — an arbitrary
+# tag can never mint a new series.
+_KNOWN_PRODUCT_LABELS: frozenset[str] = frozenset(p.value for p in Product) | frozenset(p.value for p in ProductKey)
+
CONCURRENT_TASKS_LIMIT_EXCEEDED_COUNTER = Counter(
"posthog_celery_task_concurrency_limit_exceeded",
"Number of times a Celery task exceeded the concurrency limit",
@@ -102,6 +108,16 @@ class RateLimit:
running_tasks_key = self.get_task_key(*args, **kwargs) if self.get_task_key else task_name
task_id = self.get_task_id(*args, **kwargs)
team_id: Optional[int] = kwargs.get("team_id", None)
+ # Attribute blocks to the originating product surface (web_analytics, product_analytics, …)
+ # so we can track which product a saturated org's rejections come from. The limiter runs
+ # before sync_execute's add_fallback_query_tags, so ad-hoc queries that only tag scene/kind
+ # (no explicit productKey) would otherwise label as "unknown" — apply the same fallback here.
+ # StrEnum → its value.
+ tags = get_query_tags()
+ if tags.product is None:
+ add_fallback_query_tags(tags)
+ product_value = str(tags.product) if tags.product else None
+ product_label = product_value if product_value in _KNOWN_PRODUCT_LABELS else "unknown"
max_concurrency: int = self.max_concurrency
@@ -145,6 +161,7 @@ class RateLimit:
limit=max_concurrency,
limit_name=self.limit_name,
result=result,
+ product=product_label,
).inc()
return None, None
@@ -155,6 +172,7 @@ class RateLimit:
limit=max_concurrency,
limit_name=self.limit_name,
result="retry",
+ product=product_label,
).inc()
wait_sec = backoff(count)
self.sleep(wait_sec)
@@ -169,6 +187,7 @@ class RateLimit:
limit=max_concurrency,
limit_name=self.limit_name,
result="block",
+ product=product_label,
).inc()
raise ConcurrencyLimitExceeded(
diff --git a/posthog/clickhouse/client/test/test_limit.py b/posthog/clickhouse/client/test/test_limit.py
index 8077ffdfc955..cb185f73b098 100644
--- a/posthog/clickhouse/client/test/test_limit.py
+++ b/posthog/clickhouse/client/test/test_limit.py
@@ -5,7 +5,10 @@ from collections.abc import Callable
from posthog.test.base import BaseTest
from unittest.mock import Mock, patch
+from parameterized import parameterized
+
from posthog.clickhouse.client.limit import ConcurrencyLimitExceeded, RateLimit
+from posthog.clickhouse.query_tagging import Product, QueryTags, query_tags, reset_query_tags, tag_queries
from posthog.constants import AvailableFeature
@@ -37,6 +40,40 @@ class TestRateLimit(BaseTest):
with self.assertRaises(ConcurrencyLimitExceeded):
self.cancels.append(self.limit.use(True, 8, 18))
+ @parameterized.expand(
+ [
+ # Scene-only queries carry no explicit productKey; the block counter must still attribute
+ # them via the same fallback sync_execute applies later, not record "unknown".
+ ("scene_fallback", {"scene": "SQLEditor"}, "warehouse"),
+ # An explicit product wins over the scene fallback.
+ ("explicit_product_wins", {"scene": "SQLEditor", "product": Product.WEB_ANALYTICS}, "web_analytics"),
+ # Nothing to attribute falls back to "unknown".
+ ("no_tags", {}, "unknown"),
+ ]
+ )
+ def test_block_counter_attributes_product_via_fallback(self, _name, query_tags, expected_product):
+ reset_query_tags()
+ if query_tags:
+ tag_queries(**query_tags)
+ self.cancels.append(self.limit.use(is_api=True, team_id=9, task_id=1))
+ with patch("posthog.clickhouse.client.limit.CONCURRENT_QUERY_LIMIT_EXCEEDED_COUNTER") as mock_counter:
+ with self.assertRaises(ConcurrencyLimitExceeded):
+ self.limit.use(is_api=True, team_id=9, task_id=2)
+ labeled_products = {call.kwargs.get("product") for call in mock_counter.labels.call_args_list}
+ self.assertIn(expected_product, labeled_products)
+
+ def test_block_counter_buckets_unknown_product(self):
+ # A product value outside the known set (e.g. a client-forged tag that slipped past validation)
+ # must collapse to "unknown" so it can't mint an unbounded Prometheus series.
+ query_tags.set(QueryTags.model_construct(product="totally-made-up-product")) # type: ignore[arg-type]
+ self.cancels.append(self.limit.use(is_api=True, team_id=9, task_id=1))
+ with patch("posthog.clickhouse.client.limit.CONCURRENT_QUERY_LIMIT_EXCEEDED_COUNTER") as mock_counter:
+ with self.assertRaises(ConcurrencyLimitExceeded):
+ self.limit.use(is_api=True, team_id=9, task_id=2)
+ labeled_products = {call.kwargs.get("product") for call in mock_counter.labels.call_args_list}
+ self.assertIn("unknown", labeled_products)
+ self.assertNotIn("totally-made-up-product", labeled_products)
+
def test_rate_limits_no_inference(self):
"""
User limits do not interfere even with same task ids.