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(web-analytics): retry warmer shapes on transient clickhouse capacity errors (#75148)

Lucas Ricoy928c8ee7bfbf
diff --git a/.github/workflows/ci-dagster.yml b/.github/workflows/ci-dagster.yml
index 4a72b6f42c23..0e8c7dfdf14d 100644
--- a/.github/workflows/ci-dagster.yml
+++ b/.github/workflows/ci-dagster.yml
@@ -110,6 +110,7 @@ jobs:
- 'posthog/schema_enums.py' # enum-only schema changes touch only this file
- 'posthog/utils.py'
- 'posthog/errors.py'
+ - 'posthog/exceptions.py'
- 'posthog/exceptions_capture.py'
- 'posthog/metrics.py'
- 'posthog/git.py'
diff --git a/products/web_analytics/dags/cache_warming.py b/products/web_analytics/dags/cache_warming.py
index e98bbcc7b88d..dc9925114aa1 100644
--- a/products/web_analytics/dags/cache_warming.py
+++ b/products/web_analytics/dags/cache_warming.py
@@ -3,6 +3,7 @@ import gzip
import json
import time
import zlib
+import random
import threading
import statistics
from concurrent.futures import ThreadPoolExecutor, as_completed
@@ -24,6 +25,7 @@ from posthog.clickhouse.client import sync_execute
from posthog.clickhouse.query_tagging import Feature, reset_query_tags, tag_queries
from posthog.dags.common import JobOwners
from posthog.event_usage import EventSource
+from posthog.exceptions import ClickHouseAtCapacity
from posthog.exceptions_capture import capture_exception
from posthog.hogql_queries.query_runner import ExecutionMode, get_query_runner_or_none
from posthog.models import Team
@@ -617,6 +619,17 @@ WARMING_PROGRESS_LOG_INTERVAL_SECONDS = 120
# identity churn re-warming old days, one team's pathological filters).
WARMING_SLOW_SHAPE_SECONDS = 15
+# The warmer shares its per-user ClickHouse query budget with every other
+# Dagster job (the `dagster` CH user has a hard simultaneous-query cap on the
+# sessions cluster), so a co-tenant burst surfaces here as 202/AtCapacity even
+# when the warmer itself is within budget. Those bursts are seconds-long;
+# failing the shape defers it a whole hour. A couple of jittered retries ride
+# them out, and sleeping in the worker thread throttles the pool exactly while
+# the cluster is saturated. Persistent saturation still fails fast: with the
+# cap sustained, each shape costs at most ~2 sleeps before reporting "failed".
+WARMING_CAPACITY_RETRIES = 2
+WARMING_CAPACITY_BACKOFF_RANGE_SECONDS = (5.0, 15.0)
+
# The shape-level staleness threshold is a fixed wall-clock delta, so shapes
# warmed together go stale together: any bulk pass (a cold drain, a deploy
# rotating cache hashes) synchronizes the fleet and every later run inherits a
@@ -750,6 +763,7 @@ def _warm_queries(context: dagster.OpExecutionContext, mode: str, queries: list[
date_from=date_range.get("date_from") if isinstance(date_range, dict) else None,
replay_date_from=query_info.get("_replay_date_from"),
was_cold=query_info.get("_was_cold"),
+ capacity_retries=query_info.get("_capacity_retries"),
normalized_query_hash=query_info.get("normalized_query_hash"),
)
except Exception:
@@ -845,10 +859,18 @@ def _warm_queries(context: dagster.OpExecutionContext, mode: str, queries: list[
# response and the early refresh — the whole point of the jitter —
# would never happen. The warmer has already made the staleness
# decision above; run() must not second-guess it.
- runner.run(
- execution_mode=ExecutionMode.CALCULATE_BLOCKING_ALWAYS,
- analytics_props={"source": EventSource.CACHE_WARMING},
- )
+ for attempt in range(WARMING_CAPACITY_RETRIES + 1):
+ try:
+ runner.run(
+ execution_mode=ExecutionMode.CALCULATE_BLOCKING_ALWAYS,
+ analytics_props={"source": EventSource.CACHE_WARMING},
+ )
+ break
+ except ClickHouseAtCapacity:
+ query_info["_capacity_retries"] = attempt + 1
+ if attempt == WARMING_CAPACITY_RETRIES:
+ raise
+ time.sleep(random.uniform(*WARMING_CAPACITY_BACKOFF_RANGE_SECONDS))
WARMING_QUERIES_COUNTER.labels(outcome="warmed").inc()
return "warmed"
except Exception as e:
diff --git a/products/web_analytics/dags/tests/test_cache_warming.py b/products/web_analytics/dags/tests/test_cache_warming.py
index e0f5a9ba26aa..6e65e90216e3 100644
--- a/products/web_analytics/dags/tests/test_cache_warming.py
+++ b/products/web_analytics/dags/tests/test_cache_warming.py
@@ -10,6 +10,7 @@ import dagster
from parameterized import parameterized
from posthog.clickhouse.query_tagging import Feature, get_query_tags, reset_query_tags, tag_queries
+from posthog.exceptions import ClickHouseAtCapacity
from posthog.hogql_queries.query_runner import ExecutionMode
from posthog.models import Team
@@ -467,6 +468,57 @@ class TestWarmQueriesOp(BaseTest):
self.assertEqual(runner.run.call_count, expected_runs)
+ @parameterized.expand(
+ [
+ # The dagster CH user's simultaneous-query cap is shared with other
+ # Dagster jobs, so co-tenant bursts hit the warmer as AtCapacity for
+ # a few seconds. A transient burst must be retried (deferring every
+ # affected shape a whole hour), while sustained
+ # saturation must still fail after the bounded retries — unbounded
+ # retrying would wedge every worker thread against a hard cap.
+ ("transient_202_recovers", [ClickHouseAtCapacity(), None], 2, False),
+ (
+ "persistent_202_fails",
+ [ClickHouseAtCapacity(), ClickHouseAtCapacity(), ClickHouseAtCapacity()],
+ 3,
+ True,
+ ),
+ ]
+ )
+ def test_at_capacity_retries_bounded(
+ self, _name: str, run_side_effect: list, expected_runs: int, expect_failure: bool
+ ) -> None:
+ runner = MagicMock()
+ runner.get_cache_key.return_value = f"key-{_name}"
+ runner.run.side_effect = run_side_effect
+ with (
+ patch(
+ "products.web_analytics.dags.cache_warming.build_replay_runner",
+ return_value=(runner, {}, True),
+ ),
+ patch("products.web_analytics.dags.cache_warming.QueryCache") as mock_cm,
+ patch("products.web_analytics.dags.cache_warming.time.sleep") as mock_sleep,
+ patch("products.web_analytics.dags.cache_warming.capture_exception") as mock_capture,
+ ):
+ mock_cm.return_value.lookup.return_value.entry = None
+ warm_queries_op(
+ dagster.build_op_context(),
+ WarmQueriesConfig(),
+ [
+ {
+ "team_id": self.team.pk,
+ "query_json": {"kind": "WebOverviewQuery", "properties": []},
+ "query_count": 10,
+ "representative_query_count": 10,
+ "normalized_query_hash": "h",
+ }
+ ],
+ )
+
+ self.assertEqual(runner.run.call_count, expected_runs)
+ self.assertEqual(mock_sleep.call_count, expected_runs - 1)
+ self.assertEqual(mock_capture.called, expect_failure)
+
@parameterized.expand(
[
# A churned team surfaces as a DoesNotExist from get_cache_key (the