: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(messaging): cap offline clickhouse query concurrency to avoid 202s (#72594)
Gustavo H. Strassburgerb1bf3c114ecc
diff --git a/posthog/settings/temporal.py b/posthog/settings/temporal.pyindex 6fdaa8776611..619decc95f76 100644--- a/posthog/settings/temporal.py+++ b/posthog/settings/temporal.py@@ -171,6 +171,22 @@ TEST_TASK_QUEUE = _set_temporal_task_queue("test-task-queue")BILLING_TASK_QUEUE = _set_temporal_task_queue("billing-task-queue")VIDEO_EXPORT_TASK_QUEUE = _set_temporal_task_queue("video-export-task-queue")MESSAGING_TASK_QUEUE = _set_temporal_task_queue("messaging-task-queue")+# Per-worker cap on concurrent offline-cluster ClickHouse queries issued by the messaging+# workflow family (reconcile-precalculated-data + realtime-cohort-calculation + the precalculated+# backfills). They share one worker/event loop and the offline `default` user+# (max_concurrent_queries=30), so an unbounded fan-out across tiers can trip+# TOO_MANY_SIMULTANEOUS_QUERIES. Kept safely below 30, leaving headroom for other offline+# consumers. Note this is per worker process, so the aggregate is this value times the number of+# messaging worker replicas — size it accordingly.+#+# This is also the effective ceiling on reconcile parallelism: a reconcile activity holds one slot+# for its whole streaming context, so raising RECONCILE_PRECALCULATED_DATA_TEAM_CONCURRENCY above+# this value only queues the extra teams on the semaphore instead of running more queries at once.+# Keep this at least as large as that concurrency, or a burst of reconcile teams can occupy every+# slot and stall realtime-cohort activities (60-min start_to_close_timeout) while they wait.+MESSAGING_CLICKHOUSE_MAX_CONCURRENT_QUERIES: int = get_from_env(+ "MESSAGING_CLICKHOUSE_MAX_CONCURRENT_QUERIES", 10, type_cast=int+)ANALYTICS_PLATFORM_TASK_QUEUE = _set_temporal_task_queue("analytics-platform-task-queue")SESSION_REPLAY_TASK_QUEUE = _set_temporal_task_queue("session-replay-task-queue")REPLAY_VISION_TASK_QUEUE = _set_temporal_task_queue("replay-vision-task-queue")diff --git a/posthog/temporal/messaging/backfill_precalculated_events_coordinator_workflow.py b/posthog/temporal/messaging/backfill_precalculated_events_coordinator_workflow.pyindex 5bb7da80ea81..ba6aee63b2ef 100644--- a/posthog/temporal/messaging/backfill_precalculated_events_coordinator_workflow.py+++ b/posthog/temporal/messaging/backfill_precalculated_events_coordinator_workflow.py@@ -11,8 +11,8 @@ import temporalio.workflowimport temporalio.exceptionsfrom posthog.temporal.common.base import PostHogWorkflow-from posthog.temporal.common.clickhouse import get_clientfrom posthog.temporal.messaging.backfill_precalculated_events_workflow import BackfillPrecalculatedEventsInputs+from posthog.temporal.messaging.clickhouse_concurrency import get_messaging_clientfrom posthog.temporal.messaging.constants import BACKFILL_EVENT_SOURCE_PREFIX@@ -68,7 +68,7 @@ async def check_day_already_backfilled_activity(inputs: EventDateCheckInputs) ->product=Product.MESSAGING,query_type="event_backfill_day_check",):- async with get_client(team_id=inputs.team_id) as client:+ async with get_messaging_client(team_id=inputs.team_id) as client:result = await client.read_query(query, query_params)condition_count = int(result.strip()) if result.strip() else 0diff --git a/posthog/temporal/messaging/backfill_precalculated_events_workflow.py b/posthog/temporal/messaging/backfill_precalculated_events_workflow.pyindex 98ad4e2ba12f..57f41329b120 100644--- a/posthog/temporal/messaging/backfill_precalculated_events_workflow.py+++ b/posthog/temporal/messaging/backfill_precalculated_events_workflow.py@@ -18,9 +18,9 @@ from posthog.kafka_client.client import _KafkaProducerfrom posthog.kafka_client.routing import get_producerfrom posthog.kafka_client.topics import KAFKA_CDP_CLICKHOUSE_PREFILTERED_EVENTSfrom posthog.temporal.common.base import PostHogWorkflow-from posthog.temporal.common.clickhouse import get_clientfrom posthog.temporal.common.heartbeat import Heartbeaterfrom posthog.temporal.common.logger import get_logger+from posthog.temporal.messaging.clickhouse_concurrency import get_messaging_clientfrom posthog.temporal.messaging.constants import BACKFILL_EVENT_SOURCE_PREFIXfrom posthog.temporal.messaging.filter_storage import get_event_filtersfrom posthog.temporal.messaging.types import BehavioralEventFilter@@ -303,7 +303,7 @@ async def backfill_precalculated_events_activity(query_start_time = time.monotonic()first_row = True- async with get_client(team_id=inputs.team_id) as client:+ async with get_messaging_client(team_id=inputs.team_id) as client:async for row in client.stream_query_as_jsonl(events_query, query_parameters=query_params):if first_row:time_to_first = time.monotonic() - query_start_timediff --git a/posthog/temporal/messaging/backfill_precalculated_person_properties_coordinator_workflow.py b/posthog/temporal/messaging/backfill_precalculated_person_properties_coordinator_workflow.pyindex e410e7dcecfb..d25adee1e097 100644--- a/posthog/temporal/messaging/backfill_precalculated_person_properties_coordinator_workflow.py+++ b/posthog/temporal/messaging/backfill_precalculated_person_properties_coordinator_workflow.py@@ -13,10 +13,10 @@ import temporalio.exceptionsfrom posthog.hogql import astfrom posthog.temporal.common.base import PostHogWorkflow-from posthog.temporal.common.clickhouse import get_clientfrom posthog.temporal.messaging.backfill_precalculated_person_properties_workflow import (BackfillPrecalculatedPersonPropertiesInputs,)+from posthog.temporal.messaging.clickhouse_concurrency import get_messaging_clientfrom posthog.temporal.messaging.hogql_compile import compile_hogql_for_streaming@@ -112,7 +112,7 @@ async def get_person_id_ranges_page_activity(inputs: PersonIdRangesPageInputs) -product=Product.MESSAGING,query_type="person_id_ranges_page",):- async with get_client(team_id=inputs.team_id) as client:+ async with get_messaging_client(team_id=inputs.team_id) as client:async for row in client.stream_query_as_jsonl(query, query_parameters=query_params):person_id = str(row["person_id"])diff --git a/posthog/temporal/messaging/backfill_precalculated_person_properties_workflow.py b/posthog/temporal/messaging/backfill_precalculated_person_properties_workflow.pyindex b0388dc8a50d..6581d094a55c 100644--- a/posthog/temporal/messaging/backfill_precalculated_person_properties_workflow.py+++ b/posthog/temporal/messaging/backfill_precalculated_person_properties_workflow.py@@ -22,9 +22,9 @@ from posthog.kafka_client.client import _KafkaProducerfrom posthog.kafka_client.routing import get_producerfrom posthog.kafka_client.topics import KAFKA_CDP_CLICKHOUSE_PRECALCULATED_PERSON_PROPERTIESfrom posthog.temporal.common.base import PostHogWorkflow-from posthog.temporal.common.clickhouse import get_clientfrom posthog.temporal.common.heartbeat import Heartbeaterfrom posthog.temporal.common.logger import get_logger+from posthog.temporal.messaging.clickhouse_concurrency import get_messaging_clientfrom posthog.temporal.messaging.filter_storage import get_filters_and_propertiesfrom posthog.temporal.messaging.hogql_compile import compile_hogql_for_streamingfrom posthog.temporal.messaging.types import PersonPropertyFilter@@ -584,7 +584,7 @@ async def backfill_precalculated_person_properties_activity(query_type="person_properties_backfill",):logger.info("Acquiring ClickHouse client connection", team_id=inputs.team_id)- async with get_client(team_id=inputs.team_id) as client:+ async with get_messaging_client(team_id=inputs.team_id) as client:logger.info("ClickHouse client connection established, starting query execution",team_id=inputs.team_id,diff --git a/posthog/temporal/messaging/clickhouse_concurrency.py b/posthog/temporal/messaging/clickhouse_concurrency.pynew file mode 100644index 000000000000..d03c126c9a1d--- /dev/null+++ b/posthog/temporal/messaging/clickhouse_concurrency.py@@ -0,0 +1,35 @@+import asyncio+from collections.abc import AsyncIterator+from contextlib import asynccontextmanager++from django.conf import settings++from posthog.temporal.common.clickhouse import ClickHouseClient, get_client++# Limits concurrent offline-cluster ClickHouse queries across the messaging workflow family+# (reconcile-precalculated-data, realtime-cohort-calculation, and the precalculated backfills).+# They all run on one worker process with a single event loop, so this module-level semaphore+# gates every messaging activity on the same worker. Acquiring a slot before opening+# `get_client()` turns an over-cap situation into in-process backpressure (waiting) instead of a+# ClickHouse TOO_MANY_SIMULTANEOUS_QUERIES rejection. The cap is per worker process; aggregate =+# this value times messaging worker replicas.+#+# This does not coordinate with other offline consumers: data_modeling runs its own independent+# semaphore against the same offline `default` user, on a separate task queue / worker / event+# loop (see data_modeling/activities/materialize_view.py). The real cluster-wide budget is the+# sum across all such families, so keep this value low enough to leave them headroom under 30.+#+# Floored at 1: a size of 0 (misconfigured env) would deadlock every gated activity forever, since+# no permit is ever released.+messaging_clickhouse_query_semaphore = asyncio.Semaphore(max(1, settings.MESSAGING_CLICKHOUSE_MAX_CONCURRENT_QUERIES))+++@asynccontextmanager+async def get_messaging_client(team_id: int) -> AsyncIterator[ClickHouseClient]:+ """Open a ClickHouse client while holding a messaging query slot.++ Every messaging offline-cluster query must go through here so the per-worker concurrency cap+ can't be defeated by a call site that forgets to acquire the semaphore first.+ """+ async with messaging_clickhouse_query_semaphore, get_client(team_id=team_id) as client:+ yield clientdiff --git a/posthog/temporal/messaging/realtime_cohort_calculation_workflow.py b/posthog/temporal/messaging/realtime_cohort_calculation_workflow.pyindex c638c9a607ca..3daf6cc855a2 100644--- a/posthog/temporal/messaging/realtime_cohort_calculation_workflow.py+++ b/posthog/temporal/messaging/realtime_cohort_calculation_workflow.py@@ -22,9 +22,9 @@ from posthog.kafka_client.routing import get_producerfrom posthog.kafka_client.topics import KAFKA_COHORT_MEMBERSHIP_CHANGEDfrom posthog.sync import database_sync_to_asyncfrom posthog.temporal.common.base import PostHogWorkflow-from posthog.temporal.common.clickhouse import get_clientfrom posthog.temporal.common.heartbeat import Heartbeaterfrom posthog.temporal.common.logger import get_logger+from posthog.temporal.messaging.clickhouse_concurrency import get_messaging_clientfrom posthog.temporal.messaging.constants import get_percentile_bucket_labelfrom products.cohorts.backend.models.cohort import Cohort, CohortType@@ -434,7 +434,7 @@ async def process_realtime_cohort_calculation_activity(inputs: RealtimeCohortCalrow_processing_start_time = Nonerows_processed = 0- async with get_client(team_id=cohort.team_id) as client:+ async with get_messaging_client(team_id=cohort.team_id) as client:try:async for row in client.stream_query_as_jsonl(final_query,diff --git a/posthog/temporal/messaging/reconcile_precalculated_data_workflow.py b/posthog/temporal/messaging/reconcile_precalculated_data_workflow.pyindex 6d7c6a7559ca..98dc00dbf0dc 100644--- a/posthog/temporal/messaging/reconcile_precalculated_data_workflow.py+++ b/posthog/temporal/messaging/reconcile_precalculated_data_workflow.py@@ -19,7 +19,6 @@ from posthog.kafka_client.topics import ()from posthog.sync import database_sync_to_asyncfrom posthog.temporal.common.base import PostHogWorkflow-from posthog.temporal.common.clickhouse import get_clientfrom posthog.temporal.common.heartbeat import Heartbeaterfrom posthog.temporal.common.logger import get_loggerfrom posthog.temporal.messaging.backfill_precalculated_events_workflow import flush_kafka_batch_async@@ -27,6 +26,7 @@ from posthog.temporal.messaging.backfill_precalculated_person_properties_workfloevaluate_combined_filters_with_fallback_sync,parse_person_properties,)+from posthog.temporal.messaging.clickhouse_concurrency import get_messaging_clientfrom posthog.temporal.messaging.filter_storage import combine_filter_bytecodes, extract_person_property_filtersfrom posthog.temporal.messaging.types import PersonPropertyFilter@@ -362,7 +362,10 @@ async def reconcile_team_precalculated_person_properties_activity(product=Product.MESSAGING,query_type="precalculated_person_properties_reconciliation",):- async with get_client(team_id=inputs.team_id) as client:+ # Hold a messaging-wide query slot for the whole streaming context (several batched+ # queries with Kafka produce / eval between them). Coarse, but only team_concurrency+ # (default 5) of these run at once, and waiting on the slot is backpressure, not a 202.+ async with get_messaging_client(team_id=inputs.team_id) as client:kafka_producer = get_producer(topic=KAFKA_CDP_CLICKHOUSE_PRECALCULATED_PERSON_PROPERTIES)kafka_results: list = []verdicts_checked = 0@@ -537,7 +540,8 @@ async def reconcile_team_precalculated_events_activity(inputs: ReconcileTeamInpuproduct=Product.MESSAGING,query_type="precalculated_events_reconciliation",):- async with get_client(team_id=inputs.team_id) as client:+ # See the person-properties activity above: one slot held for the streaming context.+ async with get_messaging_client(team_id=inputs.team_id) as client:kafka_producer = get_producer(topic=KAFKA_CDP_CLICKHOUSE_PREFILTERED_EVENTS)kafka_results: list = []rows_checked = 0diff --git a/posthog/temporal/messaging/test/test_backfill_precalculated_events_coordinator_workflow.py b/posthog/temporal/messaging/test/test_backfill_precalculated_events_coordinator_workflow.pyindex 07aab7232fd5..69ba86a3e8be 100644--- a/posthog/temporal/messaging/test/test_backfill_precalculated_events_coordinator_workflow.py+++ b/posthog/temporal/messaging/test/test_backfill_precalculated_events_coordinator_workflow.py@@ -109,7 +109,7 @@ class TestCheckDayAlreadyBackfilledActivity:mock_client.__aexit__ = AsyncMock(return_value=False)with patch(- "posthog.temporal.messaging.backfill_precalculated_events_coordinator_workflow.get_client",+ "posthog.temporal.messaging.clickhouse_concurrency.get_client",return_value=mock_client,):result = await check_day_already_backfilled_activity(inputs)@@ -131,7 +131,7 @@ class TestCheckDayAlreadyBackfilledActivity:mock_client.__aexit__ = AsyncMock(return_value=False)with patch(- "posthog.temporal.messaging.backfill_precalculated_events_coordinator_workflow.get_client",+ "posthog.temporal.messaging.clickhouse_concurrency.get_client",return_value=mock_client,):await check_day_already_backfilled_activity(inputs)diff --git a/posthog/temporal/messaging/test/test_backfill_precalculated_person_properties_coordinator_workflow.py b/posthog/temporal/messaging/test/test_backfill_precalculated_person_properties_coordinator_workflow.pyindex a23e9b5ca779..de584935a8f9 100644--- a/posthog/temporal/messaging/test/test_backfill_precalculated_person_properties_coordinator_workflow.py+++ b/posthog/temporal/messaging/test/test_backfill_precalculated_person_properties_coordinator_workflow.py@@ -272,7 +272,7 @@ class TestGetPersonIdRangesPageActivity:side_effect=fake_compile,),patch(- "posthog.temporal.messaging.backfill_precalculated_person_properties_coordinator_workflow.get_client",+ "posthog.temporal.messaging.clickhouse_concurrency.get_client",return_value=_AsyncClientContextManager(mock_client),),patch("temporalio.activity.heartbeat"),@@ -310,7 +310,7 @@ class TestGetPersonIdRangesPageActivity:side_effect=fake_compile,),patch(- "posthog.temporal.messaging.backfill_precalculated_person_properties_coordinator_workflow.get_client",+ "posthog.temporal.messaging.clickhouse_concurrency.get_client",return_value=_AsyncClientContextManager(mock_client),),patch("temporalio.activity.heartbeat"),@@ -342,7 +342,7 @@ class TestGetPersonIdRangesPageActivity:side_effect=fake_compile,),patch(- "posthog.temporal.messaging.backfill_precalculated_person_properties_coordinator_workflow.get_client",+ "posthog.temporal.messaging.clickhouse_concurrency.get_client",return_value=_AsyncClientContextManager(mock_client),),patch("temporalio.activity.heartbeat"),@@ -378,7 +378,10 @@ class TestPageActivityRowConsumption:module = "posthog.temporal.messaging.backfill_precalculated_person_properties_coordinator_workflow"with (patch(f"{module}.compile_hogql_for_streaming", side_effect=lambda node, *, team_id: ("SELECT 1", {})),- patch(f"{module}.get_client", return_value=_AsyncClientContextManager(mock_client)),+ patch(+ "posthog.temporal.messaging.clickhouse_concurrency.get_client",+ return_value=_AsyncClientContextManager(mock_client),+ ),patch("temporalio.activity.heartbeat"),):result = await get_person_id_ranges_page_activity(@@ -396,7 +399,10 @@ class TestPageActivityRowConsumption:module = "posthog.temporal.messaging.backfill_precalculated_person_properties_coordinator_workflow"with (patch(f"{module}.compile_hogql_for_streaming", side_effect=lambda node, *, team_id: ("SELECT 1", {})),- patch(f"{module}.get_client", return_value=_AsyncClientContextManager(mock_client)),+ patch(+ "posthog.temporal.messaging.clickhouse_concurrency.get_client",+ return_value=_AsyncClientContextManager(mock_client),+ ),patch("temporalio.activity.heartbeat"),):result = await get_person_id_ranges_page_activity(diff --git a/posthog/temporal/messaging/test/test_backfill_precalculated_person_properties_workflow.py b/posthog/temporal/messaging/test/test_backfill_precalculated_person_properties_workflow.pyindex 14e2966bd0e0..6cc947145fd3 100644--- a/posthog/temporal/messaging/test/test_backfill_precalculated_person_properties_workflow.py+++ b/posthog/temporal/messaging/test/test_backfill_precalculated_person_properties_workflow.py@@ -318,7 +318,7 @@ class TestBackfillPrecalculatedPersonPropertiesActivity:return_value=(filters, [malicious_property], combine_filter_bytecodes(filters)),),patch(- "posthog.temporal.messaging.backfill_precalculated_person_properties_workflow.get_client",+ "posthog.temporal.messaging.clickhouse_concurrency.get_client",return_value=_AsyncClientContextManager(mock_client),),patch(@@ -415,7 +415,7 @@ class TestBackfillPrecalculatedPersonPropertiesActivity:return_value=(filters, [percent_property], combine_filter_bytecodes(filters)),),patch(- "posthog.temporal.messaging.backfill_precalculated_person_properties_workflow.get_client",+ "posthog.temporal.messaging.clickhouse_concurrency.get_client",return_value=_AsyncClientContextManager(mock_client),),patch(@@ -515,7 +515,10 @@ class TestActivityRowConsumption:return_value=(filters, list(person_properties), combine_filter_bytecodes(filters)),),patch(self._module("compile_hogql_for_streaming"), side_effect=compile_stub),- patch(self._module("get_client"), return_value=_AsyncClientContextManager(mock_client)),+ patch(+ "posthog.temporal.messaging.clickhouse_concurrency.get_client",+ return_value=_AsyncClientContextManager(mock_client),+ ),patch(self._module("evaluate_combined_filters_with_fallback_sync"), side_effect=eval_stub),patch(self._module("get_producer"), return_value=producer),patch(self._module("Heartbeater"), _NoopHeartbeater),diff --git a/posthog/temporal/messaging/test/test_realtime_cohort_calculation_workflow.py b/posthog/temporal/messaging/test/test_realtime_cohort_calculation_workflow.pyindex 77b44015463a..5eba6bd1cf2b 100644--- a/posthog/temporal/messaging/test/test_realtime_cohort_calculation_workflow.py+++ b/posthog/temporal/messaging/test/test_realtime_cohort_calculation_workflow.py@@ -1,12 +1,15 @@import os+from types import TracebackTypeimport pytest-from unittest.mock import Mock, patch+from unittest.mock import AsyncMock, Mock, patchfrom posthog.temporal.messaging.realtime_cohort_calculation_workflow import (+ RealtimeCohortCalculationWorkflowInputs,_batch_update_cohort_metrics,build_final_query,flush_kafka_batch,+ process_realtime_cohort_calculation_activity,)from posthog.temporal.messaging.realtime_cohort_calculation_workflow_coordinator import (CohortSelectionActivityInput,@@ -1744,3 +1747,79 @@ class TestFinalQueryMembershipStatuses:# Unchanged member: present in both → WHERE filters it out entirelyassert passes_where(pid, pid) is False+++class _AsyncClientContextManager:+ def __init__(self, client: Mock) -> None:+ self.client = client++ async def __aenter__(self) -> Mock:+ return self.client++ async def __aexit__(+ self,+ exc_type: type[BaseException] | None,+ exc_value: BaseException | None,+ traceback: TracebackType | None,+ ) -> None:+ return None+++class _NoopHeartbeater:+ def __init__(self, details: tuple[str, ...] = (), factor: int = 120) -> None:+ self.details = details++ async def __aenter__(self) -> "_NoopHeartbeater":+ return self++ async def __aexit__(+ self,+ exc_type: type[BaseException] | None,+ exc_value: BaseException | None,+ traceback: TracebackType | None,+ ) -> None:+ return None+++class TestRealtimeCohortConcurrencyGate:+ @pytest.mark.asyncio+ async def test_activity_opens_clickhouse_client_through_gated_wrapper(self):+ # Guards the concurrency cap for the one gated site the other six tests don't execute:+ # if this activity's ClickHouse access stops flowing through get_messaging_client (the exact+ # way the production 202 could recur), clickhouse_concurrency.get_client is no longer the+ # symbol invoked and this assertion fails.+ # `yield` after `return` never runs, but its presence makes this an async generator that+ # streams zero rows — matching stream_query_as_jsonl's shape.+ async def empty_stream(*args, **kwargs):+ return+ yield++ mock_client = Mock()+ mock_client.stream_query_as_jsonl = lambda *args, **kwargs: empty_stream()++ cohort = Mock()+ cohort.pk = 10+ cohort.team_id = 1+ cohort.team = Mock()+ cohort.name = "realtime cohort"++ cohort_model = Mock()+ cohort_model.objects.filter.return_value.select_related.return_value = [cohort]++ get_client_mock = Mock(return_value=_AsyncClientContextManager(mock_client))+ module = "posthog.temporal.messaging.realtime_cohort_calculation_workflow"++ with (+ patch("posthog.temporal.messaging.clickhouse_concurrency.get_client", get_client_mock),+ patch(f"{module}.Cohort", cohort_model),+ patch(f"{module}.HogQLRealtimeCohortQuery"),+ patch(f"{module}.prepare_and_print_ast", return_value=("SELECT 1", {})),+ patch(f"{module}.get_producer", return_value=Mock()),+ patch(f"{module}.Heartbeater", _NoopHeartbeater),+ patch(f"{module}._batch_update_cohort_metrics", AsyncMock(return_value=0)),+ patch(f"{module}.get_cohort_calculation_success_metric", return_value=Mock()),+ patch(f"{module}.get_cohort_calculation_failure_metric", return_value=Mock()),+ ):+ await process_realtime_cohort_calculation_activity(RealtimeCohortCalculationWorkflowInputs(cohort_id=10))++ get_client_mock.assert_called_once_with(team_id=1)