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.

perf(web-analytics): serve live and warm precompute in background on miss (#72959)

Lucas Ricoy3ee708e22103
diff --git a/products/analytics_platform/backend/lazy_computation/lazy_computation_executor.py b/products/analytics_platform/backend/lazy_computation/lazy_computation_executor.py
index 0edc884aea0b..a50ca42fb02c 100644
--- a/products/analytics_platform/backend/lazy_computation/lazy_computation_executor.py
+++ b/products/analytics_platform/backend/lazy_computation/lazy_computation_executor.py
@@ -821,6 +821,7 @@ class LazyComputationExecutor:
stale_pending_threshold_seconds: float = DEFAULT_STALE_PENDING_THRESHOLD_SECONDS,
ch_start_grace_period_seconds: float = DEFAULT_CH_START_GRACE_PERIOD_SECONDS,
stale_while_revalidate_seconds: float | None = None,
+ run_inserts: bool = True,
) -> None:
if stale_while_revalidate_seconds is not None and stale_while_revalidate_seconds >= EXPIRY_BUFFER_SECONDS:
raise ValueError("stale_while_revalidate_seconds must be below EXPIRY_BUFFER_SECONDS")
@@ -832,6 +833,11 @@ class LazyComputationExecutor:
self.stale_pending_threshold_seconds = stale_pending_threshold_seconds
self.ch_start_grace_period_seconds = ch_start_grace_period_seconds
self.stale_while_revalidate_seconds = stale_while_revalidate_seconds
+ # Check-only mode: never create jobs or wait on pending ones. A request
+ # either gets served from covering READY jobs (fresh, or stale within the
+ # revalidate grace) or is told `ready=False` immediately so it can fall
+ # back to a live query while something else computes in the background.
+ self.run_inserts = run_inserts
def execute(
self,
@@ -871,7 +877,11 @@ class LazyComputationExecutor:
had_ready_at_start: bool | None = None
def _log_execution(outcome: str, result: LazyComputationResult) -> None:
- if jobs_created == 0 and not waited_job_ids:
+ if outcome == "check_miss":
+ # Check-only misses return before any job is created or waited on,
+ # which the branch below would misread as a cache hit.
+ cache_state = "partial_hit" if had_ready_at_start else "miss"
+ elif jobs_created == 0 and not waited_job_ids:
cache_state = "hit"
elif had_ready_at_start:
cache_state = "partial_hit"
@@ -944,6 +954,17 @@ class LazyComputationExecutor:
_log_execution("stale_hit", result)
return result
+ # Check-only mode: the range isn't fully covered by servable READY
+ # jobs (the stale-serve above would have returned), and this request
+ # must not compute inline or block on someone else's pending job —
+ # report the miss so the caller serves live and warms in background.
+ if not self.run_inserts and (ttl_ranges or pending_jobs):
+ result = LazyComputationResult(
+ ready=False, job_ids=[], errors=errors, memory_exceeded=memory_exceeded
+ )
+ _log_execution("check_miss", result)
+ return result
+
# Step 3: Insert missing ranges
did_work = False
if ttl_ranges and failures <= self.max_retries:
@@ -1196,6 +1217,7 @@ def ensure_precomputed(
wait_timeout_seconds: float | None = None,
stale_while_revalidate_seconds: float | None = None,
modifiers: HogQLQueryModifiers | None = None,
+ run_inserts: bool = True,
) -> LazyComputationResult:
"""
Ensure lazy-computed data exists for the given query and time range.
@@ -1348,6 +1370,7 @@ def ensure_precomputed(
ttl_schedule=ttl_schedule,
wait_timeout_seconds=wait_timeout_seconds if wait_timeout_seconds is not None else DEFAULT_WAIT_TIMEOUT_SECONDS,
stale_while_revalidate_seconds=stale_while_revalidate_seconds,
+ run_inserts=run_inserts,
)
return executor.execute(team, query_info, time_range_start, time_range_end, run_insert=_run_manual_insert)
diff --git a/products/analytics_platform/backend/lazy_computation/tests/test_lazy_computation_executor.py b/products/analytics_platform/backend/lazy_computation/tests/test_lazy_computation_executor.py
index 9f25a54f3cb7..1cf0a7242728 100644
--- a/products/analytics_platform/backend/lazy_computation/tests/test_lazy_computation_executor.py
+++ b/products/analytics_platform/backend/lazy_computation/tests/test_lazy_computation_executor.py
@@ -3050,3 +3050,67 @@ class TestExecuteOOMAndBudget(ClickhouseTestMixin, BaseTest):
assert result.ready is False
assert any("Timeout" in e for e in result.errors)
assert 1 <= len(calls) < 7
+
+
+class TestCheckOnlyMode(BaseTest):
+ """`run_inserts=False`: a user-facing read is either served from covering READY
+ jobs or told `ready=False` immediately — it must never create jobs, run inserts,
+ or block on another executor's pending job (the inline-backfill self-DoS)."""
+
+ def _execute(self, start: datetime, end: datetime) -> LazyComputationResult:
+ query = parse_select("SELECT 1")
+ assert isinstance(query, ast.SelectQuery)
+ query_info = QueryInfo(query=query, table=LazyComputationTable.PREAGGREGATION_RESULTS, timezone="UTC")
+
+ def forbidden_insert(team, job):
+ raise AssertionError("check-only mode must never run inserts")
+
+ return LazyComputationExecutor(run_inserts=False).execute(
+ team=self.team,
+ query_info=query_info,
+ start=start,
+ end=end,
+ run_insert=forbidden_insert,
+ )
+
+ def _ready_job(self, start: datetime, end: datetime) -> PreaggregationJob:
+ query = parse_select("SELECT 1")
+ assert isinstance(query, ast.SelectQuery)
+ return PreaggregationJob.objects.create(
+ team=self.team,
+ query_hash=compute_query_hash(
+ QueryInfo(query=query, table=LazyComputationTable.PREAGGREGATION_RESULTS, timezone="UTC")
+ ),
+ time_range_start=start,
+ time_range_end=end,
+ status=PreaggregationJob.Status.READY,
+ computed_at=django_timezone.now(),
+ expires_at=django_timezone.now() + timedelta(hours=6),
+ )
+
+ def test_served_when_ready_jobs_cover_range(self):
+ job = self._ready_job(datetime(2024, 1, 1, tzinfo=UTC), datetime(2024, 1, 3, tzinfo=UTC))
+ result = self._execute(datetime(2024, 1, 1, tzinfo=UTC), datetime(2024, 1, 3, tzinfo=UTC))
+ assert result.ready is True
+ assert result.job_ids == [job.id]
+
+ def test_miss_creates_no_jobs(self):
+ result = self._execute(datetime(2024, 1, 1, tzinfo=UTC), datetime(2024, 1, 3, tzinfo=UTC))
+ assert result.ready is False
+ assert PreaggregationJob.objects.filter(team=self.team).count() == 0
+
+ def test_partial_coverage_is_a_miss(self):
+ self._ready_job(datetime(2024, 1, 1, tzinfo=UTC), datetime(2024, 1, 2, tzinfo=UTC))
+ result = self._execute(datetime(2024, 1, 1, tzinfo=UTC), datetime(2024, 1, 3, tzinfo=UTC))
+ assert result.ready is False
+ assert PreaggregationJob.objects.filter(team=self.team).count() == 1 # untouched
+
+ def test_pending_job_is_a_miss_without_waiting(self):
+ job = self._ready_job(datetime(2024, 1, 1, tzinfo=UTC), datetime(2024, 1, 3, tzinfo=UTC))
+ job.status = PreaggregationJob.Status.PENDING
+ job.computed_at = None
+ job.save()
+ started = time_mod.monotonic()
+ result = self._execute(datetime(2024, 1, 1, tzinfo=UTC), datetime(2024, 1, 3, tzinfo=UTC))
+ assert result.ready is False
+ assert time_mod.monotonic() - started < 5, "check-only must not block on pending jobs"
diff --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.py
index d66db9622e88..0a27fa6072af 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
@@ -541,3 +541,50 @@ class TestStaleRevalidationEnqueue(BaseTest):
delay.side_effect = Exception("broker down")
handle_stale_served(runner=runner, family="web_overview")
assert get_query_tag_value("precompute_stale") is True
+
+
+class TestServeLiveWarmBehind(BaseTest):
+ """User-facing ensures are check-only (never insert inline); a miss enqueues
+ a background warm. Background warming triggers keep computing inline —
+ without that split, either dashboards pay for their own backfill again
+ (the inline self-DoS) or the warmers stop producing jobs entirely."""
+
+ def _runner(self):
+ runner = mock.Mock()
+ runner.team = self.team
+ runner.query = mock.Mock()
+ return runner
+
+ @mock.patch(f"{_COMMON}.enqueue_stale_revalidation")
+ @mock.patch(f"{_COMMON}.ensure_precomputed")
+ def test_user_facing_is_check_only_and_warms_on_miss(self, mock_ensure, mock_enqueue):
+ mock_ensure.return_value = LazyComputationResult(ready=False, job_ids=[], memory_exceeded=False)
+ runner = self._runner()
+ web_ensure_precomputed(
+ team=self.team, runner=runner, family="web_overview", ttl_seconds={"default": 3600}, table=None
+ )
+ assert mock_ensure.call_args.kwargs["run_inserts"] is False
+ assert "runner" not in mock_ensure.call_args.kwargs
+ assert "family" not in mock_ensure.call_args.kwargs
+ mock_enqueue.assert_called_once_with(team=self.team, query=runner.query, family="web_overview")
+
+ @mock.patch(f"{_COMMON}.enqueue_stale_revalidation")
+ @mock.patch(f"{_COMMON}.ensure_precomputed")
+ def test_user_facing_hit_does_not_enqueue(self, mock_ensure, mock_enqueue):
+ mock_ensure.return_value = LazyComputationResult(ready=True, job_ids=[], memory_exceeded=False)
+ web_ensure_precomputed(
+ team=self.team, runner=self._runner(), family="web_overview", ttl_seconds={"default": 3600}, table=None
+ )
+ mock_enqueue.assert_not_called()
+
+ @mock.patch(f"{_COMMON}.enqueue_stale_revalidation")
+ @mock.patch(f"{_COMMON}.ensure_precomputed")
+ def test_background_warming_still_inserts_inline(self, mock_ensure, mock_enqueue):
+ mock_ensure.return_value = LazyComputationResult(ready=False, job_ids=[], memory_exceeded=False)
+ with tags_context(trigger="webAnalyticsEagerBaselineWarming"):
+ web_ensure_precomputed(
+ team=self.team, runner=self._runner(), family="web_overview", ttl_seconds={"default": 3600}, table=None
+ )
+ assert mock_ensure.call_args.kwargs["run_inserts"] is True
+ # The warmer IS the refresh mechanism; a miss must not re-enqueue itself.
+ mock_enqueue.assert_not_called()
diff --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.py
index cb74218ac8c1..41be07364809 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
@@ -23,6 +23,7 @@ from posthog.schema import (
from posthog.hogql import ast
from posthog.clickhouse.client import sync_execute
+from posthog.clickhouse.query_tagging import tags_context
from posthog.models.utils import uuid7
from products.analytics_platform.backend.models.preaggregation_job import PreaggregationJob
@@ -173,6 +174,13 @@ class TestWebStatsLazyPrecompute(ClickhouseTestMixin, APIBaseTest):
)
def _run(self, query: WebStatsTableQuery):
+ # Serve-live-warm-behind: user-facing reads never insert inline, so warm
+ # eligible shapes first under a background trigger (inline inserts allowed
+ # there), then assert on the converged user-facing read. Fall-through
+ # shapes ignore the warm pass and take the live path as before.
+ if query.useWebAnalyticsPrecompute:
+ with tags_context(trigger="webAnalyticsEagerBaselineWarming"):
+ WebStatsTableQueryRunner(team=self.team, query=query).calculate()
return WebStatsTableQueryRunner(team=self.team, query=query).calculate()
@staticmethod
@@ -481,8 +489,10 @@ class TestWebStatsLazyPrecompute(ClickhouseTestMixin, APIBaseTest):
@freeze_time("2024-01-15T12:00:00Z")
def test_query_optin_alone_falls_through_when_org_flag_disabled(self):
+ # Direct user-facing calculate (no warm pass): warming triggers bypass the
+ # org flag by design, so the helper's warm pre-pass would create jobs here.
self._seed()
- self._run(self._build_query(opt_in_precompute=True))
+ WebStatsTableQueryRunner(team=self.team, query=self._build_query(opt_in_precompute=True)).calculate()
assert self._job_count() == 0
diff --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.py
index 77aee4214c9a..868fb3d2a042 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
@@ -20,6 +20,7 @@ from posthog.schema import (
)
from posthog.clickhouse.client import sync_execute
+from posthog.clickhouse.query_tagging import tags_context
from posthog.models.utils import uuid7
from products.analytics_platform.backend.models.preaggregation_job import PreaggregationJob
@@ -114,6 +115,12 @@ class TestWebVitalsPathsLazyPrecompute(ClickhouseTestMixin, APIBaseTest):
)
def _run(self, query: WebVitalsPathBreakdownQuery):
+ # Serve-live-warm-behind: user-facing reads never insert inline, so warm
+ # eligible shapes under a background trigger first, then assert on the
+ # converged user-facing read.
+ if query.useWebAnalyticsPrecompute:
+ with tags_context(trigger="webAnalyticsEagerBaselineWarming"):
+ WebVitalsPathBreakdownQueryRunner(team=self.team, query=query).calculate()
return WebVitalsPathBreakdownQueryRunner(team=self.team, query=query).calculate()
@staticmethod
@@ -233,8 +240,12 @@ class TestWebVitalsPathsLazyPrecompute(ClickhouseTestMixin, APIBaseTest):
@freeze_time("2024-01-15T12:00:00Z")
def test_query_optin_alone_falls_through_when_org_flag_disabled(self):
+ # Direct user-facing calculate (no warm pass): warming triggers bypass the
+ # org flag by design, so the helper's warm pre-pass would create jobs here.
self._seed()
- response = self._run(self._build_query(opt_in_precompute=True))
+ response = WebVitalsPathBreakdownQueryRunner(
+ team=self.team, query=self._build_query(opt_in_precompute=True)
+ ).calculate()
assert response.preComputeStrategy != WebAnalyticsPreComputeStrategy.LAZY_PRECOMPUTE
assert self._job_count() == 0
diff --git a/products/web_analytics/backend/hogql_queries/web_goals_lazy_precompute.py b/products/web_analytics/backend/hogql_queries/web_goals_lazy_precompute.py
index 9876313519fa..e27344152872 100644
--- a/products/web_analytics/backend/hogql_queries/web_goals_lazy_precompute.py
+++ b/products/web_analytics/backend/hogql_queries/web_goals_lazy_precompute.py
@@ -301,6 +301,8 @@ def ensure_web_goals_precomputed(
placeholders[f"action_{n}_id"] = ast.Constant(value=int(action.id))
return web_ensure_precomputed(
+ runner=runner,
+ family=_FAMILY,
team=runner.team,
insert_query=_build_insert_query(actions),
time_range_start=time_range_start,
diff --git a/products/web_analytics/backend/hogql_queries/web_lazy_precompute_common.py b/products/web_analytics/backend/hogql_queries/web_lazy_precompute_common.py
index 5e89c4e275a0..d45d2823fdc7 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
@@ -138,6 +138,12 @@ BACKGROUND_WARMING_TRIGGERS = frozenset(
# still exist).
STALE_WHILE_REVALIDATE_SECONDS = 6 * 60 * 60
+WEB_ANALYTICS_LAZY_PRECOMPUTE_CHECK_MISS = Counter(
+ "web_analytics_lazy_precompute_check_miss_total",
+ "User-facing reads that found no covering READY jobs, fell back to the live query, and enqueued a background warm.",
+ labelnames=["family"],
+)
+
WEB_ANALYTICS_LAZY_PRECOMPUTE_STALE_SERVED = Counter(
"web_analytics_lazy_precompute_stale_served_total",
"Reads served from expired-within-grace jobs instead of recomputing inline (stale-while-revalidate).",
@@ -226,10 +232,20 @@ def web_ensure_precomputed(*, team: Team, **kwargs: Any) -> LazyComputationResul
and would serve stale to themselves). Callers that see `stale=True` must hand the
result to `handle_stale_served` so the background revalidation actually happens.
"""
+ runner = kwargs.pop("runner", None)
+ family = kwargs.pop("family", None)
+ background = is_background_warming_request()
if "stale_while_revalidate_seconds" not in kwargs:
kwargs["stale_while_revalidate_seconds"] = resolve_stale_while_revalidate_seconds(
STALE_WHILE_REVALIDATE_SECONDS, BACKGROUND_WARMING_TRIGGERS
)
+ # User-facing requests never compute inline: they are served from covering
+ # READY jobs (fresh or within the stale grace) or told "miss" immediately so
+ # the caller falls back to the live query. Construction happens only on
+ # background triggers (warmers, the revalidation task) — a cold dashboard
+ # must not pay for its own backfill.
+ if "run_inserts" not in kwargs:
+ kwargs["run_inserts"] = background
pinned = is_team_oom_pinned(team.id)
if "ttl_seconds" in kwargs:
existing = kwargs["ttl_seconds"]
@@ -248,6 +264,11 @@ def web_ensure_precomputed(*, team: Team, **kwargs: Any) -> LazyComputationResul
schedule = replace(schedule, max_window_days=OOM_PIN_WINDOW_DAYS)
kwargs["ttl_seconds"] = schedule
result = ensure_precomputed(team=team, **kwargs)
+ if not result.ready and not background and runner is not None and family is not None:
+ # Check-only miss: warm in the background (debounced per team/family/shape)
+ # so the next visit is served from precompute while this one goes live.
+ WEB_ANALYTICS_LAZY_PRECOMPUTE_CHECK_MISS.labels(family=family).inc()
+ enqueue_stale_revalidation(team=team, query=runner.query, family=family)
if result.memory_exceeded:
pin_team_oom(team.id) # set or refresh the cap so a still-OOMing team stays pinned
if not pinned:
diff --git a/products/web_analytics/backend/hogql_queries/web_overview_lazy_precompute.py b/products/web_analytics/backend/hogql_queries/web_overview_lazy_precompute.py
index 0dc1bd8a6d01..30ea5d0edb22 100644
--- a/products/web_analytics/backend/hogql_queries/web_overview_lazy_precompute.py
+++ b/products/web_analytics/backend/hogql_queries/web_overview_lazy_precompute.py
@@ -202,6 +202,8 @@ def ensure_web_overview_precomputed(
insert_query = JOIN_INSERT_QUERY_TEMPLATE
return web_ensure_precomputed(
+ runner=runner,
+ family=_FAMILY,
team=runner.team,
insert_query=insert_query,
time_range_start=time_range_start,
diff --git a/products/web_analytics/backend/hogql_queries/web_stats_frustration_lazy_precompute.py b/products/web_analytics/backend/hogql_queries/web_stats_frustration_lazy_precompute.py
index 5a1b413826f8..161ce588aecc 100644
--- a/products/web_analytics/backend/hogql_queries/web_stats_frustration_lazy_precompute.py
+++ b/products/web_analytics/backend/hogql_queries/web_stats_frustration_lazy_precompute.py
@@ -267,6 +267,8 @@ def ensure_web_stats_frustration_precomputed(
}
return web_ensure_precomputed(
+ runner=runner,
+ family=_FAMILY,
team=runner.team,
insert_query=INSERT_QUERY_TEMPLATE,
time_range_start=time_range_start,
diff --git a/products/web_analytics/backend/hogql_queries/web_stats_lazy_precompute.py b/products/web_analytics/backend/hogql_queries/web_stats_lazy_precompute.py
index b0aa5216226b..5c593ada755b 100644
--- a/products/web_analytics/backend/hogql_queries/web_stats_lazy_precompute.py
+++ b/products/web_analytics/backend/hogql_queries/web_stats_lazy_precompute.py
@@ -278,6 +278,8 @@ def ensure_web_stats_precomputed(
}
return web_ensure_precomputed(
+ runner=runner,
+ family=_FAMILY,
team=runner.team,
insert_query=INSERT_QUERY_TEMPLATE,
time_range_start=time_range_start,
diff --git a/products/web_analytics/backend/hogql_queries/web_stats_paths_lazy_precompute.py b/products/web_analytics/backend/hogql_queries/web_stats_paths_lazy_precompute.py
index 9dfbdd3595bb..02d7202701df 100644
--- a/products/web_analytics/backend/hogql_queries/web_stats_paths_lazy_precompute.py
+++ b/products/web_analytics/backend/hogql_queries/web_stats_paths_lazy_precompute.py
@@ -639,6 +639,8 @@ def ensure_web_stats_paths_precomputed(
else:
wait_timeout = PATHS_USER_ENSURE_WAIT_SECONDS
return web_ensure_precomputed(
+ runner=runner,
+ family=_FAMILY,
team=runner.team,
insert_query=insert_query,
time_range_start=time_range_start,
diff --git a/products/web_analytics/backend/hogql_queries/web_vitals_paths_lazy_precompute.py b/products/web_analytics/backend/hogql_queries/web_vitals_paths_lazy_precompute.py
index 1dd9bafacf23..8496fe4104e3 100644
--- a/products/web_analytics/backend/hogql_queries/web_vitals_paths_lazy_precompute.py
+++ b/products/web_analytics/backend/hogql_queries/web_vitals_paths_lazy_precompute.py
@@ -207,6 +207,8 @@ def ensure_web_vitals_paths_precomputed(
}
return web_ensure_precomputed(
+ runner=runner,
+ family=_FAMILY,
team=runner.team,
insert_query=INSERT_QUERY_TEMPLATE,
time_range_start=time_range_start,