: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): spread cache warming and move jobs off minute zero (#106987)
Sandy Spicerfc201d54a231
diff --git a/docs/internal/web-analytics-query-serving.md b/docs/internal/web-analytics-query-serving.mdindex 2232779310f9..29dfee42bdbf 100644--- a/docs/internal/web-analytics-query-serving.md+++ b/docs/internal/web-analytics-query-serving.md@@ -142,11 +142,16 @@ Four writers keep buckets warm; user reads only ever consume.| System | Trigger tag | When | What it does || -------------------------------------------------------------------- | ---------------------------------- | --------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |-| Eager baseline warmer (Dagster, `eager_web_analytics_precompute.py`) | `webAnalyticsEagerBaselineWarming` | Hourly at :05 | Pre-warms the fixed dashboard matrix (overview, goals, vitals, one stats query per breakdown) over a trailing 28d window for flag-enrolled teams (cap 200, 45-min cycle budget) |-| Hourly demand warmer (Dagster, `cache_warming.py`) | `webAnalyticsQueryWarming` | Hourly | Selects hot shapes from query_log (kind `Web%`, ≥2 hits in 2 days; raw-path shapes keep a ≥10 bar), expands sub-30d ranges to −30d, replays via an 8-worker pool with the opt-in injected |+| Eager baseline warmer (Dagster, `eager_web_analytics_precompute.py`) | `webAnalyticsEagerBaselineWarming` | Hourly at :53 | Pre-warms the fixed dashboard matrix (overview, goals, vitals, one stats query per breakdown) over a trailing 28d window for flag-enrolled teams (cap 200, 45-min cycle budget) |+| Hourly demand warmer (Dagster, `cache_warming.py`) | `webAnalyticsQueryWarming` | Hourly at :03 | Selects hot shapes from query_log (kind `Web%`, ≥2 hits in 2 days; raw-path shapes keep a ≥10 bar), expands sub-30d ranges to −30d, replays via an 8-worker pool with the opt-in injected || Warm-behind on miss | (background warming request) | On any user-read miss | Debounced rebuild of exactly the shape that missed; self-heals first-hit misses in ~30–60s || Stale revalidation | `webAnalyticsStaleRevalidation` | On stale-grace serves | Refreshes expired buckets after serving the stale copy |+The demand warmer delays each team's first eligible work by a stable offset within ten minutes of its shard starting.+Manual runs have no release delay.+Worker capacity can delay a team beyond its release time; the offset is not a completion deadline.+The eager and demand jobs can still overlap if either pass runs long.+## Flags and team allowlists| Gate | Type | Controls |diff --git a/products/customer_analytics/backend/temporal/calendar_sync.py b/products/customer_analytics/backend/temporal/calendar_sync.pyindex 35ef124cc470..44b6dc97582d 100644--- a/products/customer_analytics/backend/temporal/calendar_sync.py+++ b/products/customer_analytics/backend/temporal/calendar_sync.py@@ -410,7 +410,12 @@ async def create_calendar_sync_coordinator_schedule(client: Client) -> None:id=f"{CALENDAR_SYNC_COORDINATOR_WORKFLOW_NAME}-workflow",task_queue=settings.VIDEO_EXPORT_TASK_QUEUE,),- spec=ScheduleSpec(intervals=[ScheduleIntervalSpec(every=timedelta(minutes=COORDINATOR_INTERVAL_MINUTES))]),+ spec=ScheduleSpec(+ intervals=[+ ScheduleIntervalSpec(every=timedelta(minutes=COORDINATOR_INTERVAL_MINUTES), offset=timedelta(minutes=2))+ ],+ jitter=timedelta(minutes=10),+ ),policy=SchedulePolicy(overlap=ScheduleOverlapPolicy.SKIP),)if await a_schedule_exists(client, CALENDAR_SYNC_COORDINATOR_SCHEDULE_ID):diff --git a/products/customer_analytics/backend/temporal/ownership_claims.py b/products/customer_analytics/backend/temporal/ownership_claims.pyindex 51ea45155e77..7ccee4a71ec0 100644--- a/products/customer_analytics/backend/temporal/ownership_claims.py+++ b/products/customer_analytics/backend/temporal/ownership_claims.py@@ -30,6 +30,7 @@ with workflow.unsafe.imports_passed_through():from posthog.dataclasses import frozenfrom posthog.models.scoping import team_scopefrom posthog.models.team import Team+ from posthog.scheduling.jitter import deterministic_offsetfrom posthog.sync import database_sync_to_asyncfrom posthog.temporal.common.heartbeat import Heartbeaterfrom posthog.temporal.common.schedule import a_create_schedule, a_schedule_exists, a_update_schedule@@ -188,7 +189,14 @@ def _build_ownership_claims_coordinator_schedule(state: ScheduleState) -> Scheduexecution_timeout=OWNERSHIP_CLAIMS_COORDINATOR_EXECUTION_TIMEOUT,retry_policy=RetryPolicy(maximum_attempts=1),),- spec=ScheduleSpec(intervals=[ScheduleIntervalSpec(every=OWNERSHIP_CLAIMS_INTERVAL)]),+ spec=ScheduleSpec(+ intervals=[+ ScheduleIntervalSpec(+ every=OWNERSHIP_CLAIMS_INTERVAL,+ offset=deterministic_offset(OWNERSHIP_CLAIMS_COORDINATOR_SCHEDULE_ID, OWNERSHIP_CLAIMS_INTERVAL),+ )+ ]+ ),state=state,policy=SchedulePolicy(overlap=ScheduleOverlapPolicy.SKIP),)diff --git a/products/web_analytics/PRECOMPUTATION.md b/products/web_analytics/PRECOMPUTATION.mdindex 2e87e475c757..074cd75659c5 100644--- a/products/web_analytics/PRECOMPUTATION.md+++ b/products/web_analytics/PRECOMPUTATION.md@@ -293,7 +293,7 @@ The runner re-partitions the resulting `(band, path, value)` tuples into the `goA cold or expired shape's first read serves the live path and only warms in the background — but for high-traffic teams the dashboard's main tiles are requested constantly, and there's no reason to let the first user of every cycle take that live-path miss. The eager job pre-warms the same lazy precompute cache (and the Django response cache) for a fixed query matrix, ahead of users.- **Location**: `products/web_analytics/dags/eager_web_analytics_precompute.py`-- **Schedule**: `5 * * * *` (hourly, offset 5 min from the existing `cache_warming_schedule` at `0 * * * *`); skipped if a prior run is still in flight (`check_for_concurrent_runs`).+- **Schedule**: `53 * * * *` (hourly, with its start outside the demand warmer's release window); skipped if a prior run is still in flight (`check_for_concurrent_runs`).- **Window**: trailing 28 days. The lazy precompute stores per-day buckets, so a 28-day warm naturally covers any sub-window the dashboard asks for.- **Matrix per team**: `WebOverviewQuery` + `WebGoalsQuery` + `WebVitalsPathBreakdownQuery` + one `WebStatsTableQuery` per `WebStatsBreakdown` rendered by the dashboard (~23 breakdowns including `FrustrationMetrics`).- **Per-query toggle**: every warmer query sets `useWebAnalyticsPrecompute=True` explicitly. Precompute now defaults on for enrolled teams (only an explicit `False` opts out), so this is redundant — kept to make the warmer's intent explicit.diff --git a/products/web_analytics/dags/cache_favicons.py b/products/web_analytics/dags/cache_favicons.pyindex 4afe09182ebd..64b6917ddf86 100644--- a/products/web_analytics/dags/cache_favicons.py+++ b/products/web_analytics/dags/cache_favicons.py@@ -223,7 +223,7 @@ cache_authorized_domain_favicons_job = dagster.define_asset_job(@dagster.schedule(- cron_schedule="0 3 * * *", # Daily at 3 AM UTC+ cron_schedule="37 3 * * *", # Daily at 03:37 UTCjob=cache_favicons_job,execution_timezone="UTC",tags={"owner": JobOwners.TEAM_WEB_ANALYTICS.value},@@ -233,7 +233,7 @@ def cache_favicons_schedule(_context: dagster.ScheduleEvaluationContext):@dagster.schedule(- cron_schedule="0 */6 * * *", # Every 6 hours+ cron_schedule="51 */6 * * *", # Every 6 hoursjob=cache_authorized_domain_favicons_job,execution_timezone="UTC",tags={"owner": JobOwners.TEAM_WEB_ANALYTICS.value},diff --git a/products/web_analytics/dags/cache_warming.py b/products/web_analytics/dags/cache_warming.pyindex 422c3ac387a4..2e2b0ff7389f 100644--- a/products/web_analytics/dags/cache_warming.py+++ b/products/web_analytics/dags/cache_warming.py@@ -21,6 +21,7 @@ import dagsterimport structlogfrom dagster import Backoff, Jitter, RetryPolicyfrom prometheus_client import Counter, Gauge+from pydantic import Fieldfrom posthog.hogql.constants import LimitContext@@ -35,6 +36,7 @@ from posthog.hogql_queries.query_runner import ExecutionMode, get_query_runner_ofrom posthog.models import Teamfrom posthog.models.instance_setting import get_instance_settingfrom posthog.query_cache import QueryCache+from posthog.scheduling.jitter import deterministic_offsetfrom posthog.settings import CLICKHOUSE_CLUSTERfrom posthog.storage import object_storage@@ -1107,6 +1109,12 @@ WARMING_PASS_DEADLINE_SECONDS = 3 * 3600# before the process exits hard rather than hanging on a blocked thread join.WARMING_CANCEL_GRACE_SECONDS = 60+# The hourly schedule starts each team at its own offset inside this window, so+# the pass does not send every team's first queries to the offline ClickHouse+# pool in the same minute. The window is far below the stall timeout, so a+# pass that is still releasing teams never looks stalled.+WARMING_RELEASE_WINDOW_SECONDS = 10 * 60+# 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@@ -1153,8 +1161,9 @@ def _team_still_exists(team_id: int) -> bool:class WarmQueriesConfig(dagster.Config):- """Launchpad knobs for targeted warming runs. The hourly schedule passes no- config, so it keeps the defaults; a manual launch can scope a run.+ """Launchpad knobs for targeted warming runs. The hourly schedule sets only+ `release_window_seconds` and keeps the other defaults; a manual launch can+ scope a run.The concurrent-run guard makes launches of this job mutually exclusive withthe hourly schedule, so bound a manual backfill with `limit` — an unbounded@@ -1170,6 +1179,10 @@ class WarmQueriesConfig(dagster.Config):team_ids: list[int] = []# Process at most this many shapes, hottest first (0 = no limit).limit: int = 0+ # Spread the teams' start times over this many seconds (0 = start every team at once).+ # Capped at the hourly window because a window near the stall timeout can leave a+ # shard with only waiting workers, and the stall guard then kills a healthy pass.+ release_window_seconds: int = Field(default=0, ge=0, le=WARMING_RELEASE_WINDOW_SECONDS)def _scope_queries(config: WarmQueriesConfig, queries: list[dict]) -> tuple[str, list[dict]]:@@ -1186,7 +1199,7 @@ def _scope_queries(config: WarmQueriesConfig, queries: list[dict]) -> tuple[str,@dagster.op(retry_policy=cache_warming_retry_policy)def warm_queries_op(context: dagster.OpExecutionContext, config: WarmQueriesConfig, queries: list[dict]) -> None:mode, queries = _scope_queries(config, queries)- _warm_queries(context, mode, queries)+ _warm_queries(context, mode, queries, release_window=timedelta(seconds=config.release_window_seconds))@dagster.op(out=dagster.DynamicOut(dict), retry_policy=cache_warming_retry_policy)@@ -1210,15 +1223,26 @@ def split_warmable_queries_op(context: dagster.OpExecutionContext, config: WarmQbuckets.setdefault(query_info["team_id"] % shards, []).append(query_info)context.log.info(f"Split {len(queries)} shapes into {len(buckets)} shards (mode={mode})")for shard_index in sorted(buckets):- yield dagster.DynamicOutput({"mode": mode, "queries": buckets[shard_index]}, mapping_key=f"shard_{shard_index}")+ yield dagster.DynamicOutput(+ {+ "mode": mode,+ "queries": buckets[shard_index],+ "release_window_seconds": config.release_window_seconds,+ },+ mapping_key=f"shard_{shard_index}",+ )@dagster.op(retry_policy=cache_warming_retry_policy)def warm_queries_shard_op(context: dagster.OpExecutionContext, shard: dict) -> None:- _warm_queries(context, shard["mode"], shard["queries"])+ _warm_queries(+ context, shard["mode"], shard["queries"], release_window=timedelta(seconds=shard["release_window_seconds"])+ )-def _warm_queries(context: dagster.OpExecutionContext, mode: str, queries: list[dict]) -> None:+def _warm_queries(+ context: dagster.OpExecutionContext, mode: str, queries: list[dict], release_window: timedelta = timedelta(0)+) -> None:team_ids = {q["team_id"] for q in queries}teams: dict[int, Team] = {t.pk: t for t in Team.objects.filter(pk__in=team_ids)}missing_teams = team_ids - teams.keys()@@ -1232,7 +1256,20 @@ def _warm_queries(context: dagster.OpExecutionContext, mode: str, queries: list[raw_preset_replays_by_team: dict[int, int] = {}seen_lock = threading.Lock()+ release_after = {+ team_id: deterministic_offset(str(team_id), release_window).total_seconds() for team_id in team_ids+ }+ # Submitted in release order, so a worker never waits on a late team while+ # shapes that are already released queue behind it.+ queries = sorted(queries, key=lambda query_info: release_after[query_info["team_id"]])+ stop_releasing = threading.Event()+def _warm_one(query_info: dict) -> str:+ release_in = release_after[query_info["team_id"]] - (time.monotonic() - started_at)+ # The wait ends early on cancellation, so a worker that has not started+ # its shape does not use up the cancellation grace period.+ if release_in > 0 and stop_releasing.wait(release_in):+ return "cancelled"# One line per shape, every outcome — deliberately verbose (~a line per# selected shape per run). Warm passes have repeatedly been slow for# reasons aggregate counters couldn't attribute (bucket identity churn,@@ -1423,7 +1460,10 @@ def _warm_queries(context: dagster.OpExecutionContext, mode: str, queries: list[processed = 0started_at = time.monotonic()last_log_at = started_at- context.log.info(f"Warming {total} shapes across {len(teams)} teams (mode={mode}, concurrency={concurrency})")+ context.log.info(+ f"Warming {total} shapes across {len(teams)} teams (mode={mode}, concurrency={concurrency}, "+ f"release window={int(release_window.total_seconds())}s)"+ )# No `with` block: the context manager's exit calls shutdown(wait=True),# which joins worker threads — on the exceptional paths below that would# re-block on the very wedged threads this code exists to escape.@@ -1511,7 +1551,10 @@ def _warm_queries(context: dagster.OpExecutionContext, mode: str, queries: list[# in-flight shapes a bounded grace to finish, then exit hard if any# remain — re-raising with blocked threads alive would just hang again# at the interpreter's exit join.+ stop_releasing.set()pool.shutdown(wait=False, cancel_futures=True)+ # wait() can report shutdown-cancelled futures as pending even though they are done.+ pending = {future for future in pending if not future.done()}if pending:_, still_pending = wait(pending, timeout=WARMING_CANCEL_GRACE_SECONDS)if still_pending:@@ -1642,7 +1685,7 @@ def web_analytics_cache_warming_dry_run_job():@dagster.schedule(- cron_schedule="0 * * * *",+ cron_schedule="3 * * * *",job=web_analytics_cache_warming_job,execution_timezone="UTC",tags={"owner": JobOwners.TEAM_WEB_ANALYTICS.value},@@ -1652,4 +1695,6 @@ def web_analytics_cache_warming_schedule(context: dagster.ScheduleEvaluationContif skip_reason:return skip_reason- return dagster.RunRequest()+ return dagster.RunRequest(+ run_config={"ops": {"warm_queries_op": {"config": {"release_window_seconds": WARMING_RELEASE_WINDOW_SECONDS}}}}+ )diff --git a/products/web_analytics/dags/eager_web_analytics_precompute.py b/products/web_analytics/dags/eager_web_analytics_precompute.pyindex b3fa69f62453..f9a62d7329d2 100644--- a/products/web_analytics/dags/eager_web_analytics_precompute.py+++ b/products/web_analytics/dags/eager_web_analytics_precompute.py@@ -694,10 +694,9 @@ def web_analytics_eager_backfill_job():# STOPPED) so the stop is an explicit operational toggle, not a silent# code-deploy behavior change.# Hourly. The lazy cache's 4h today-TTL absorbs missed cycles, so- # there's no need to align with shorter cadences. Offset by 5 min from- # the top of the hour to avoid colliding with the existing- # `web_analytics_cache_warming_schedule` (`0 * * * *`).- cron_schedule="5 * * * *",+ # there's no need to align with shorter cadences. Minute 53 puts its start+ # outside the cache warmer's ten-minute release window after minute 3.+ cron_schedule="53 * * * *",job=web_analytics_eager_baseline_warming_job,execution_timezone="UTC",tags={"owner": JobOwners.TEAM_WEB_ANALYTICS.value},diff --git a/products/web_analytics/dags/tests/test_cache_warming.py b/products/web_analytics/dags/tests/test_cache_warming.pyindex f072e74a2de3..18c81f991c49 100644--- a/products/web_analytics/dags/tests/test_cache_warming.py+++ b/products/web_analytics/dags/tests/test_cache_warming.py@@ -1,11 +1,12 @@import gzipimport jsonimport threading+from concurrent.futures import Futurefrom datetime import datetime, timedeltafrom types import SimpleNamespacefrom posthog.test.base import BaseTest-from unittest.mock import MagicMock, patch+from unittest.mock import MagicMock, call, patchfrom django.utils.dateparse import parse_datetime@@ -18,6 +19,7 @@ from posthog.hogql_queries.query_runner import ExecutionModefrom posthog.models import Teamfrom posthog.models.instance_setting import override_instance_configfrom posthog.query_cache import EntryFreshness+from posthog.scheduling.jitter import deterministic_offsetfrom products.web_analytics.backend.hogql_queries.web_lazy_precompute_common import is_background_warming_requestfrom products.web_analytics.backend.models.web_analytics_filter_preset import WebAnalyticsFilterPreset@@ -25,6 +27,7 @@ from products.web_analytics.dags import cache_warmingfrom products.web_analytics.dags.cache_warming import (PRESET_LANE_MAX_PRESETS_PER_TEAM,PRESET_LANE_MAX_SHAPES_PER_PRESET,+ WARMING_RELEASE_WINDOW_SECONDS,WarmQueriesConfig,build_replay_runner,canonicalize_lazy_replay_json,@@ -35,6 +38,8 @@ from products.web_analytics.dags.cache_warming import (queries_to_keep_fresh,split_warmable_queries_op,warm_queries_op,+ web_analytics_cache_warming_job,+ web_analytics_cache_warming_schedule,)@@ -456,6 +461,22 @@ class TestSplitWarmableQueries(BaseTest):with self.assertRaises(ValueError):list(split_warmable_queries_op(dagster.build_op_context(), WarmQueriesConfig(mode="bogus"), []))+ def test_hourly_schedule_config_reaches_every_shard(self) -> None:+ # The schedule writes its run config as a raw dict, so a renamed op alias or+ # config field fails every hourly launch. Dagster checks the window bound only+ # when the op builds WarmQueriesConfig, so the test builds it too.+ with patch("products.web_analytics.dags.cache_warming.check_for_concurrent_runs", return_value=None):+ request = web_analytics_cache_warming_schedule(dagster.build_schedule_context())+ assert isinstance(request, dagster.RunRequest)+ resolved = dagster.validate_run_config(web_analytics_cache_warming_job, request.run_config)+ config = WarmQueriesConfig(**resolved["ops"]["warm_queries_op"]["config"])++ outputs = list(+ split_warmable_queries_op(dagster.build_op_context(), config, [self._shape(1, 1), self._shape(2, 2)])+ )++ self.assertEqual({out.value["release_window_seconds"] for out in outputs}, {WARMING_RELEASE_WINDOW_SECONDS})+class TestFleetQuerySelection(BaseTest):@patch("products.web_analytics.dags.cache_warming.sync_execute")@@ -1153,6 +1174,92 @@ class TestWarmQueriesOp(BaseTest):# the early warm into a silent no-op.self.assertEqual(runner.run.call_args.kwargs.get("execution_mode"), ExecutionMode.CALCULATE_BLOCKING_ALWAYS)+ @parameterized.expand([("released", False, 2), ("cancelled", True, 1), ("cancelled_backlog", True, 3)])+ def test_release_window_delays_work_and_cancellation_wakes_workers(+ self, _name: str, cancel: bool, shape_count: int+ ) -> None:+ early_team = Team.objects.create(id=987655, organization=self.organization, name="early release")+ late_team = Team.objects.create(id=987654, organization=self.organization, name="late release")+ window = timedelta(minutes=10)+ early_delay = deterministic_offset(str(early_team.pk), window).total_seconds()+ late_delay = deterministic_offset(str(late_team.pk), window).total_seconds()+ self.assertLess(0, early_delay)+ self.assertLess(early_delay, late_delay)+ clock = SimpleNamespace(now=0.0)+ entered = threading.Event()+ stop = threading.Event()+ finish_worker = threading.Event()+ waits: list[float] = []+ real_wait = cache_warming.wait++ class ControlledRelease:+ def wait(self, timeout: float) -> bool:+ waits.append(timeout)+ entered.set()+ if cancel:+ stop.wait()+ finish_worker.wait()+ return True+ clock.now += timeout+ return False++ def set(self) -> None:+ stop.set()++ def wait_for_work(+ pending: set[Future[str]], timeout: float | None = None, return_when: str = "ALL_COMPLETED"+ ) -> tuple[set[Future[str]], set[Future[str]]]:+ if cancel and return_when == "FIRST_COMPLETED":+ self.assertTrue(entered.wait(5))+ raise KeyboardInterrupt()+ if cancel:+ finish_worker.set()+ for future in pending:+ if not future.cancelled():+ future.result(timeout=5)+ return real_wait(pending, timeout=0)+ done, remaining = real_wait(pending, timeout=5)+ self.assertFalse(remaining)+ return done, remaining++ context = dagster.build_op_context()+ try:+ with (+ patch(+ "products.web_analytics.dags.cache_warming.threading",+ SimpleNamespace(Lock=threading.Lock, Event=ControlledRelease),+ ),+ patch("products.web_analytics.dags.cache_warming.time", SimpleNamespace(monotonic=lambda: clock.now)),+ patch("products.web_analytics.dags.cache_warming.wait", side_effect=wait_for_work),+ patch("products.web_analytics.dags.cache_warming.WARMING_QUERIES_COUNTER") as counter,+ patch(+ "products.web_analytics.dags.cache_warming.os._exit", side_effect=AssertionError("unexpected exit")+ ),+ override_instance_config("WEB_ANALYTICS_WARMING_SHARD_THREADS", 1),+ ):+ # The early team's shape comes last, so it starts first only if the shapes are sorted by release time.+ shapes = [+ {"team_id": team.pk, "query_json": {"kind": "WebVitalsQuery"}, "normalized_query_hash": f"h{index}"}+ for index, team in enumerate([late_team] * (shape_count - 1) + [early_team])+ ]+ config = WarmQueriesConfig(release_window_seconds=int(window.total_seconds()))+ if cancel:+ with self.assertRaises(KeyboardInterrupt):+ warm_queries_op(context, config, shapes)+ counter.labels.assert_not_called()+ self.assertEqual(waits, [early_delay])+ else:+ warm_queries_op(context, config, shapes)+ self.assertEqual(+ counter.labels.call_args_list, [call(lane="demand", outcome="unsupported")] * shape_count+ )+ # The late team waits only for the part of its offset that the early team's wait did not cover.+ self.assertEqual(waits, [early_delay, late_delay - early_delay])+ self.assertEqual(clock.now, late_delay)+ finally:+ stop.set()+ finish_worker.set()+def test_cancellation_drains_or_exits_within_grace(self) -> None:# Cancellation mid-pass must not hand the executor a queue to drain nor# hang joining a wedged thread (codex/greptile P1: the with-block exit