: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(web-analytics): jitter warmer staleness checks to diffuse expiry storms (#75149)
Lucas Ricoybeb88af9c9b9
diff --git a/products/web_analytics/dags/cache_warming.py b/products/web_analytics/dags/cache_warming.pyindex 71c0216112b9..e98bbcc7b88d 100644--- a/products/web_analytics/dags/cache_warming.py+++ b/products/web_analytics/dags/cache_warming.py@@ -2,9 +2,11 @@ import reimport gzipimport jsonimport time+import zlibimport threadingimport statisticsfrom concurrent.futures import ThreadPoolExecutor, as_completed+from datetime import datetime, timedeltafrom typing import TYPE_CHECKING, Optionalfrom django.core.exceptions import ObjectDoesNotExist@@ -23,7 +25,7 @@ from posthog.clickhouse.query_tagging import Feature, reset_query_tags, tag_querfrom posthog.dags.common import JobOwnersfrom posthog.event_usage import EventSourcefrom posthog.exceptions_capture import capture_exception-from posthog.hogql_queries.query_runner import get_query_runner_or_none+from posthog.hogql_queries.query_runner import ExecutionMode, get_query_runner_or_nonefrom posthog.models import Teamfrom posthog.models.instance_setting import get_instance_settingfrom posthog.query_cache import QueryCache@@ -615,6 +617,32 @@ WARMING_PROGRESS_LOG_INTERVAL_SECONDS = 120# identity churn re-warming old days, one team's pathological filters).WARMING_SLOW_SHAPE_SECONDS = 15+# 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+# multi-hour expiry storm that monopolizes the hourly cadence until phases+# drift apart on their own. Evaluating staleness with the entry aged by a+# bounded offset warms each shape a little early — never late, so served+# freshness is untouched.+#+# The offset is seeded with (shape, last_refresh), not the shape alone: the+# warmer only samples staleness at run ticks, and with a threshold that is a+# whole number of ticks, every fixed offset below one tick collapses onto the+# same tick — a synchronized cohort would march in formation forever. Seeding+# with last_refresh keeps the offset stable between runs within a cycle (no+# flapping) but re-draws it each time the shape warms, so every cycle each+# shape independently lands one tick earlier or not — a synchronized cohort+# decays geometrically instead of persisting. Mean cost is ~30min early on a+# multi-hour cycle (~+10-15% warms), well inside the sharded pass's headroom.+WARMING_STALENESS_JITTER_MAX_SECONDS = 3600+++def _staleness_jitter(normalized_query_hash: object, last_refresh: datetime) -> timedelta:+ # crc32, not hash(): str hashing is salted per process, and the offset must+ # be reproducible across runs or it re-randomizes each hour and shapes flap.+ seed = f"{normalized_query_hash}:{last_refresh.isoformat()}".encode()+ return timedelta(seconds=zlib.crc32(seed) % WARMING_STALENESS_JITTER_MAX_SECONDS)+def _team_still_exists(team_id: int) -> bool:# Thin DB boundary so tests can pin the answer: pool worker threads hold their@@ -801,12 +829,26 @@ def _warm_queries(context: dagster.OpExecutionContext, mode: str, queries: list[if cached_data is not None:last_refresh = parse_datetime(cached_data["last_refresh"])- if not runner._is_stale(last_refresh):+ aged_refresh = (+ last_refresh - _staleness_jitter(query_info["normalized_query_hash"], last_refresh)+ if last_refresh+ else None+ )+ if not runner._is_stale(aged_refresh):WARMING_QUERIES_COUNTER.labels(outcome="skipped_fresh").inc()return "skipped_fresh"# TODO: We shouldn't try to run a query if it failed last run- runner.run(analytics_props={"source": EventSource.CACHE_WARMING})+ # Blocking-always, not the stale-checking default: run() re-checks+ # staleness internally against the entry's true last_refresh, so a+ # jitter-early warm would silently return the still-fresh cached+ # 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},+ )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.pyindex 2bb1bc63a7b1..e0f5a9ba26aa 100644--- a/products/web_analytics/dags/tests/test_cache_warming.py+++ b/products/web_analytics/dags/tests/test_cache_warming.py@@ -4,10 +4,13 @@ import jsonfrom posthog.test.base import BaseTestfrom unittest.mock import MagicMock, patch+from django.utils.dateparse import parse_datetime+import dagsterfrom parameterized import parameterizedfrom posthog.clickhouse.query_tagging import Feature, get_query_tags, reset_query_tags, tag_queries+from posthog.hogql_queries.query_runner import ExecutionModefrom posthog.models import Teamfrom products.web_analytics.backend.hogql_queries.web_lazy_precompute_common import is_background_warming_request@@ -552,6 +555,47 @@ class TestWarmQueriesOp(BaseTest):self.assertEqual(runner.run.call_count, expected_runs)+ def test_staleness_evaluated_on_jitter_aged_entry(self) -> None:+ # Shapes warmed together go stale together (fixed threshold), so a bulk+ # pass turns into a synchronized expiry storm hours later. The warmer+ # must evaluate staleness on the entry aged by the shape's deterministic+ # offset — warming early diffuses the cohort. If the jitter is dropped,+ # a boundary-fresh entry skips instead of warming and storms return.+ runner = MagicMock()+ runner.get_cache_key.return_value = "key-jitter"+ real_last_refresh = parse_datetime("2026-07-01T00:00:00Z")+ # Stale only if judged on a timestamp older than the true one, i.e.+ # exactly when the jitter aged it.+ runner._is_stale.side_effect = lambda last_refresh: last_refresh < real_last_refresh+ 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,+ ):+ entry = MagicMock()+ entry.as_full_response.return_value = {"last_refresh": "2026-07-01T00:00:00Z"}+ mock_cm.return_value.lookup.return_value.entry = entry+ warm_queries_op(+ dagster.build_op_context(),+ WarmQueriesConfig(),+ [+ {+ "team_id": self.team.pk,+ "query_json": {"kind": "WebOverviewQuery", "properties": []},+ "query_count": 5,+ "representative_query_count": 5,+ # crc32("h") % 3600 is nonzero, so the aged timestamp is+ # strictly older than the true one.+ "normalized_query_hash": "h",+ }+ ],+ )++ self.assertEqual(runner.run.call_count, 1)+ # Forcing matters: run()'s default mode re-checks staleness against the+ # true last_refresh and would return the fresh cached response, turning+ # the early warm into a silent no-op.+ self.assertEqual(runner.run.call_args.kwargs.get("execution_mode"), ExecutionMode.CALCULATE_BLOCKING_ALWAYS)+def test_team_ids_and_limit_scope_the_run(self) -> None:# A Launchpad run scoped to one team must not warm the fleet: launches# are mutually exclusive with the hourly schedule, so an unscoped manual