: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
perf(web-analytics): delay background warms so dashboard bursts finish first (#73048)
Lucas Ricoyc00b4c17bdc2
diff --git a/products/web_analytics/backend/hogql_queries/test/test_web_goals_lazy_precompute.py b/products/web_analytics/backend/hogql_queries/test/test_web_goals_lazy_precompute.pyindex 78e02bcb6155..5515f60b8967 100644--- a/products/web_analytics/backend/hogql_queries/test/test_web_goals_lazy_precompute.py+++ b/products/web_analytics/backend/hogql_queries/test/test_web_goals_lazy_precompute.py@@ -264,7 +264,7 @@ class TestWebGoalsLazyPrecompute(ClickhouseTestMixin, APIBaseTest):return_value=LazyComputationResult(ready=True, job_ids=[], stale=True),),patch(- "products.web_analytics.backend.tasks.lazy_precompute_revalidation.revalidate_web_analytics_precompute.delay"+ "products.web_analytics.backend.tasks.lazy_precompute_revalidation.revalidate_web_analytics_precompute.apply_async") as delay,):reset_query_tags()@@ -272,4 +272,4 @@ class TestWebGoalsLazyPrecompute(ClickhouseTestMixin, APIBaseTest):execute_lazy_precomputed_read(runner)assert delay.call_count == 1- assert delay.call_args.kwargs["team_id"] == self.team.pk+ assert delay.call_args.kwargs["kwargs"]["team_id"] == self.team.pkdiff --git a/products/web_analytics/backend/hogql_queries/test/test_web_lazy_precompute_common.py b/products/web_analytics/backend/hogql_queries/test/test_web_lazy_precompute_common.pyindex 0a27fa6072af..84a9bbdd029d 100644--- a/products/web_analytics/backend/hogql_queries/test/test_web_lazy_precompute_common.py+++ b/products/web_analytics/backend/hogql_queries/test/test_web_lazy_precompute_common.py@@ -31,6 +31,7 @@ from products.analytics_platform.backend.lazy_computation.lazy_computation_execufrom products.web_analytics.backend.hogql_queries.stats_table import WebStatsTableQueryRunnerfrom products.web_analytics.backend.hogql_queries.web_lazy_precompute_common import (OOM_PIN_TTL_SECONDS,+ REVALIDATION_START_DELAY_SECONDS,REVALIDATION_TRIGGER,SESSION_SETTLING_SECONDS,STALE_WHILE_REVALIDATE_SECONDS,@@ -50,6 +51,7 @@ from products.web_analytics.backend.hogql_queries.web_lazy_precompute_common impweb_ensure_precomputed,)from products.web_analytics.backend.hogql_queries.web_overview import WebOverviewQueryRunner+from products.web_analytics.backend.tasks.lazy_precompute_revalidation import REVALIDATION_EXPIRES_SECONDS_COMMON = "products.web_analytics.backend.hogql_queries.web_lazy_precompute_common"@@ -493,12 +495,18 @@ class TestStaleRevalidationEnqueue(BaseTest):def tearDown(self):reset_query_tags()+ # Debounce/budget keys persist in the shared test Redis; scrub so tests+ # stay order-independent.+ client = redis.get_client()+ keys = client.keys(f"web_swr_reval*{self.team.pk}*")+ if keys:+ client.delete(*keys)super().tearDown()def _delay_patch(self):return mock.patch("products.web_analytics.backend.tasks.lazy_precompute_revalidation"- ".revalidate_web_analytics_precompute.delay"+ ".revalidate_web_analytics_precompute.apply_async")def test_handle_stale_served_tags_read_and_debounces_same_shape(self):@@ -512,7 +520,13 @@ class TestStaleRevalidationEnqueue(BaseTest):handle_stale_served(runner=runner, family="web_overview")assert get_query_tag_value("precompute_stale") is Trueassert delay.call_count == 1- payload = delay.call_args.kwargs+ # The warm gets a head start delay so it never contends with the+ # dashboard burst that enqueued it.+ assert delay.call_args.kwargs["countdown"] == REVALIDATION_START_DELAY_SECONDS+ # Expiry is measured from publication, so the head start must not eat+ # into the queue's pickup window.+ assert delay.call_args.kwargs["expires"] == REVALIDATION_START_DELAY_SECONDS + REVALIDATION_EXPIRES_SECONDS+ payload = delay.call_args.kwargs["kwargs"]assert payload["team_id"] == self.team.pkassert payload["query"]["kind"] == "WebOverviewQuery"@@ -531,6 +545,39 @@ class TestStaleRevalidationEnqueue(BaseTest):handle_stale_served(runner=stats_runner, family="web_stats")assert delay.call_count == 2+ def test_per_team_budget_bounds_distinct_shape_enqueues(self):+ # Filters/dates are request-controlled, so distinct shapes are unbounded;+ # the per-team budget must cap total enqueues per window regardless.+ from products.web_analytics.backend.hogql_queries.web_lazy_precompute_common import (+ REVALIDATION_TEAM_BUDGET_PER_WINDOW,+ )++ with self._delay_patch() as delay:+ for i in range(REVALIDATION_TEAM_BUDGET_PER_WINDOW + 10):+ query = WebOverviewQuery(+ dateRange=DateRange(date_from=f"2024-01-{(i % 27) + 1:02d}", date_to="2024-06-01"),+ properties=[+ EventPropertyFilter(key="$host", value=f"h{i}.example.com", operator=PropertyOperator.EXACT)+ ],+ )+ runner = WebOverviewQueryRunner(team=self.team, query=query)+ handle_stale_served(runner=runner, family="web_overview")+ assert delay.call_count == REVALIDATION_TEAM_BUDGET_PER_WINDOW++ # A budget-rejected shape must not stay debounce-locked: once the budget+ # window clears, the SAME shape (i=30 above was rejected) gets its warm+ # on the next request — the rejection must release its debounce claim.+ redis.get_client().delete(f"web_swr_reval_budget:{self.team.pk}")+ rejected_query = WebOverviewQuery(+ dateRange=DateRange(date_from=f"2024-01-{(30 % 27) + 1:02d}", date_to="2024-06-01"),+ properties=[EventPropertyFilter(key="$host", value="h30.example.com", operator=PropertyOperator.EXACT)],+ )+ with self._delay_patch() as delay:+ handle_stale_served(+ runner=WebOverviewQueryRunner(team=self.team, query=rejected_query), family="web_overview"+ )+ assert delay.call_count == 1+def test_broker_failure_does_not_break_the_stale_read_path(self):# handle_stale_served runs inside the families' read try/except before the stale# rows are read — a broker outage raising out of it would discard the stalediff --git a/products/web_analytics/backend/hogql_queries/test/test_web_overview_lazy_precompute.py b/products/web_analytics/backend/hogql_queries/test/test_web_overview_lazy_precompute.pyindex 45d93550299e..61c47af312ab 100644--- a/products/web_analytics/backend/hogql_queries/test/test_web_overview_lazy_precompute.py+++ b/products/web_analytics/backend/hogql_queries/test/test_web_overview_lazy_precompute.py@@ -688,7 +688,7 @@ class TestWebOverviewLazyPrecompute(ClickhouseTestMixin, APIBaseTest):return_value=LazyComputationResult(ready=True, job_ids=[], stale=True),),patch(- "products.web_analytics.backend.tasks.lazy_precompute_revalidation.revalidate_web_analytics_precompute.delay"+ "products.web_analytics.backend.tasks.lazy_precompute_revalidation.revalidate_web_analytics_precompute.apply_async") as delay,):reset_query_tags()@@ -696,7 +696,7 @@ class TestWebOverviewLazyPrecompute(ClickhouseTestMixin, APIBaseTest):execute_lazy_precomputed_read(runner)assert delay.call_count == 1- assert delay.call_args.kwargs["team_id"] == self.team.pk+ assert delay.call_args.kwargs["kwargs"]["team_id"] == self.team.pk@override_settings(IN_UNIT_TESTING=True)diff --git a/products/web_analytics/backend/hogql_queries/test/test_web_stats_frustration_lazy_precompute.py b/products/web_analytics/backend/hogql_queries/test/test_web_stats_frustration_lazy_precompute.pyindex 1f1892f4678b..81f6e127fdb2 100644--- a/products/web_analytics/backend/hogql_queries/test/test_web_stats_frustration_lazy_precompute.py+++ b/products/web_analytics/backend/hogql_queries/test/test_web_stats_frustration_lazy_precompute.py@@ -326,7 +326,7 @@ class TestWebStatsFrustrationLazyPrecompute(ClickhouseTestMixin, APIBaseTest):return_value=LazyComputationResult(ready=True, job_ids=[], stale=True),),patch(- "products.web_analytics.backend.tasks.lazy_precompute_revalidation.revalidate_web_analytics_precompute.delay"+ "products.web_analytics.backend.tasks.lazy_precompute_revalidation.revalidate_web_analytics_precompute.apply_async") as delay,):reset_query_tags()@@ -334,4 +334,4 @@ class TestWebStatsFrustrationLazyPrecompute(ClickhouseTestMixin, APIBaseTest):execute_lazy_precomputed_read(runner, limit=10, offset=0)assert delay.call_count == 1- assert delay.call_args.kwargs["team_id"] == self.team.pk+ assert delay.call_args.kwargs["kwargs"]["team_id"] == self.team.pkdiff --git a/products/web_analytics/backend/hogql_queries/test/test_web_stats_lazy_precompute.py b/products/web_analytics/backend/hogql_queries/test/test_web_stats_lazy_precompute.pyindex 41be07364809..546bc3491931 100644--- a/products/web_analytics/backend/hogql_queries/test/test_web_stats_lazy_precompute.py+++ b/products/web_analytics/backend/hogql_queries/test/test_web_stats_lazy_precompute.py@@ -738,7 +738,7 @@ class TestWebStatsLazyPrecompute(ClickhouseTestMixin, APIBaseTest):return_value=LazyComputationResult(ready=True, job_ids=[], stale=True),),patch(- "products.web_analytics.backend.tasks.lazy_precompute_revalidation.revalidate_web_analytics_precompute.delay"+ "products.web_analytics.backend.tasks.lazy_precompute_revalidation.revalidate_web_analytics_precompute.apply_async") as delay,):reset_query_tags()@@ -746,4 +746,4 @@ class TestWebStatsLazyPrecompute(ClickhouseTestMixin, APIBaseTest):execute_lazy_precomputed_read(runner)assert delay.call_count == 1- assert delay.call_args.kwargs["team_id"] == self.team.pk+ assert delay.call_args.kwargs["kwargs"]["team_id"] == self.team.pkdiff --git a/products/web_analytics/backend/hogql_queries/test/test_web_vitals_paths_lazy_precompute.py b/products/web_analytics/backend/hogql_queries/test/test_web_vitals_paths_lazy_precompute.pyindex 868fb3d2a042..81017f4df7ca 100644--- a/products/web_analytics/backend/hogql_queries/test/test_web_vitals_paths_lazy_precompute.py+++ b/products/web_analytics/backend/hogql_queries/test/test_web_vitals_paths_lazy_precompute.py@@ -329,7 +329,7 @@ class TestWebVitalsPathsLazyPrecompute(ClickhouseTestMixin, APIBaseTest):return_value=LazyComputationResult(ready=True, job_ids=[], stale=True),),patch(- "products.web_analytics.backend.tasks.lazy_precompute_revalidation.revalidate_web_analytics_precompute.delay"+ "products.web_analytics.backend.tasks.lazy_precompute_revalidation.revalidate_web_analytics_precompute.apply_async") as delay,):reset_query_tags()@@ -337,4 +337,4 @@ class TestWebVitalsPathsLazyPrecompute(ClickhouseTestMixin, APIBaseTest):execute_lazy_precomputed_read(runner)assert delay.call_count == 1- assert delay.call_args.kwargs["team_id"] == self.team.pk+ assert delay.call_args.kwargs["kwargs"]["team_id"] == self.team.pkdiff --git a/products/web_analytics/backend/hogql_queries/web_lazy_precompute_common.py b/products/web_analytics/backend/hogql_queries/web_lazy_precompute_common.pyindex d45d2823fdc7..7fda3d247d9d 100644--- a/products/web_analytics/backend/hogql_queries/web_lazy_precompute_common.py+++ b/products/web_analytics/backend/hogql_queries/web_lazy_precompute_common.py@@ -173,6 +173,30 @@ def is_background_warming_request() -> bool:# request) so two different stale families in one request each still get their refresh.REVALIDATION_DEBOUNCE_SECONDS = 10 * 60+# The shape debounce alone does not bound DISTINCT shapes: filters and date ranges are+# request-controlled, so a user (or runaway client) could mint arbitrarily many shapes+# and with them arbitrarily many queued warms. Cap total enqueues per team per debounce+# window; a full dashboard is ~8 families and a compare-period burst doubles some, so+# the budget comfortably covers legitimate use while bounding worker-held delayed tasks+# and background query volume alike.+#+# Scope: this budget only ever applies to USER-FACING requests. Both enqueue callers+# are unreachable from warming traffic — the check-miss enqueue in+# `web_ensure_precomputed` is gated on `not is_background_warming_request()`, and+# `handle_stale_served` can only fire for reads that received the stale grace, which+# warming requests never do. Dagster/celery warmers are unaffected.+REVALIDATION_TEAM_BUDGET_PER_WINDOW = 25++# Head start for the interactive burst: warms enqueued by a dashboard load run on the+# same team/cluster query slots as the dashboard's own live queries, so firing them+# immediately makes the background work contend with the very read it is serving.+# Dashboard bursts finish in seconds — 20s comfortably outlasts the slowest+# burst observed while keeping the warm (whose purpose is the NEXT visit)+# close behind. Celery holds countdown tasks worker-side until runnable, but+# the per-shape debounce bounds in-flight delayed tasks to at most one per+# (team, family, shape) per debounce window — a trickle, not a backlog.+REVALIDATION_START_DELAY_SECONDS = 20+def enqueue_stale_revalidation(*, team: Team, query: Any, family: str) -> None:"""Enqueue a background re-run of `query` so a stale-served read gets fresh data next time.@@ -185,15 +209,32 @@ def enqueue_stale_revalidation(*, team: Team, query: Any, family: str) -> None:# The task module imports this module (for the trigger constant), so the reverse# import must stay local to avoid a cycle.from products.web_analytics.backend.tasks.lazy_precompute_revalidation import ( # noqa: PLC0415+ REVALIDATION_EXPIRES_SECONDS,revalidate_web_analytics_precompute,)try:+ client = redis.get_client()debounce_key = f"web_swr_reval:{team.id}:{family}:{compute_filters_eligibility_hash(query, team.timezone)[:16]}"- if not redis.get_client().set(debounce_key, "1", ex=REVALIDATION_DEBOUNCE_SECONDS, nx=True):+ if not client.set(debounce_key, "1", ex=REVALIDATION_DEBOUNCE_SECONDS, nx=True):+ return+ budget_key = f"web_swr_reval_budget:{team.id}"+ spent = client.incr(budget_key)+ if spent == 1:+ client.expire(budget_key, REVALIDATION_DEBOUNCE_SECONDS)+ if spent > REVALIDATION_TEAM_BUDGET_PER_WINDOW:+ # Release the shape's debounce claim: no task was enqueued, so leaving+ # the key would lock the shape out of warming for the whole debounce+ # window even after the budget resets.+ client.delete(debounce_key)+ logger.warning("web_precompute.swr_revalidation_budget_exhausted", team_id=team.id, family=family)return- revalidate_web_analytics_precompute.delay(- team_id=team.id, query=query.model_dump(mode="json", exclude_none=True)+ revalidate_web_analytics_precompute.apply_async(+ kwargs={"team_id": team.id, "query": query.model_dump(mode="json", exclude_none=True)},+ countdown=REVALIDATION_START_DELAY_SECONDS,+ # `expires` is measured from publication; extend it by the countdown so+ # the queue keeps the task's full pickup window despite the head start.+ expires=REVALIDATION_START_DELAY_SECONDS + REVALIDATION_EXPIRES_SECONDS,)except Exception:WEB_ANALYTICS_LAZY_PRECOMPUTE_REVALIDATION_ENQUEUE_FAILED.labels(family=family).inc()