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): weekly precompute TTL jobs + disk spill on insert (#64093)

Lucas Ricoyb2a2a0e78e60
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 3079c1feb884..8fa84cd32b28 100644
--- a/products/analytics_platform/backend/lazy_computation/lazy_computation_executor.py
+++ b/products/analytics_platform/backend/lazy_computation/lazy_computation_executor.py
@@ -19,7 +19,11 @@ from clickhouse_driver.errors import ServerException
from prometheus_client import Counter
from posthog.hogql import ast
-from posthog.hogql.constants import HogQLQuerySettings, get_default_hogql_global_settings
+from posthog.hogql.constants import (
+ MAX_BYTES_BEFORE_EXTERNAL_GROUP_BY,
+ HogQLQuerySettings,
+ get_default_hogql_global_settings,
+)
from posthog.hogql.context import HogQLContext
from posthog.hogql.modifiers import create_default_modifiers_for_team
from posthog.hogql.parser import parse_select
@@ -127,11 +131,16 @@ LAZY_COMPUTATION_JOBS_FINISHED_TOTAL = Counter(
)
-def _get_insert_settings(team_id: int) -> dict:
+def _get_insert_settings(team_id: int, *, spill_to_disk: bool = False) -> dict:
"""Build ClickHouse settings for preaggregation INSERT queries.
Starts from the same HogQLGlobalSettings defaults that execute_hogql_query
uses for regular queries, then applies INSERT-specific overrides.
+
+ `spill_to_disk` is opt-in per precompute kind: it only helps inserts whose
+ GROUP BY hash table can grow large (high-cardinality breakdowns), and most
+ kinds never approach the threshold, so callers enable it deliberately rather
+ than paying for it everywhere.
"""
settings = get_default_hogql_global_settings(team_id=team_id).model_dump(exclude_none=True)
settings.pop("readonly", None) # INSERTs need write access
@@ -149,6 +158,14 @@ def _get_insert_settings(team_id: int) -> dict:
**HogQLQuerySettings(load_balancing="in_order").model_dump(exclude_none=True),
}
)
+ if spill_to_disk:
+ # Spill heavy GROUP BYs to disk instead of OOMing. This is a spill
+ # *threshold*, not a memory reservation — it lowers peak RAM (vs. holding
+ # the whole hash table in memory), so it never over-commits the cluster.
+ # High-traffic teams' breakdown inserts (e.g. frustration metrics) otherwise
+ # build hash tables past the cluster memory limit and fail with
+ # MEMORY_LIMIT_EXCEEDED.
+ settings["max_bytes_before_external_group_by"] = MAX_BYTES_BEFORE_EXTERNAL_GROUP_BY
return settings
@@ -1007,6 +1024,7 @@ def ensure_precomputed(
placeholders: dict[str, ast.Expr] | None = None,
sentinel_placeholders: set[str] | None = None,
query_type: str | None = None,
+ spill_to_disk: bool = False,
) -> LazyComputationResult:
"""
Ensure lazy-computed data exists for the given query and time range.
@@ -1121,7 +1139,7 @@ def ensure_precomputed(
sync_execute(
insert_sql,
values,
- settings=_get_insert_settings(t.id),
+ settings=_get_insert_settings(t.id, spill_to_disk=spill_to_disk),
)
ttl_schedule = parse_ttl_schedule(ttl_seconds, team.timezone)
diff --git a/products/web_analytics/backend/hogql_queries/web_analytics_lazy_precompute.py b/products/web_analytics/backend/hogql_queries/web_analytics_lazy_precompute.py
index 66fb91c3e2e1..bcaa37d72825 100644
--- a/products/web_analytics/backend/hogql_queries/web_analytics_lazy_precompute.py
+++ b/products/web_analytics/backend/hogql_queries/web_analytics_lazy_precompute.py
@@ -29,7 +29,10 @@ from posthog.hogql.transforms.preaggregated_table_transformation import is_integ
from posthog.models.team import Team
-from products.web_analytics.backend.hogql_queries.web_lazy_precompute_common import is_precompute_enabled_for_team
+from products.web_analytics.backend.hogql_queries.web_lazy_precompute_common import (
+ LAZY_TTL_SECONDS, # noqa: F401 — re-exported; several runners import it from this module
+ is_precompute_enabled_for_team,
+)
logger = structlog.get_logger(__name__)
@@ -60,19 +63,6 @@ WEB_ANALYTICS_LAZY_PRECOMPUTE_SUCCESS = Counter(
["family"],
)
-# Bucketing the precompute hourly keeps reads correct for any whole-hour-offset
-# timezone — boundaries line up exactly when the team-local window is converted
-# to UTC before filtering on `time_window_start`. Half-hour-offset timezones
-# (IST, Newfoundland, Nepal, etc.) are explicitly gated out below.
-LAZY_TTL_SECONDS: dict[str, int] = {
- # today: 2h — kept in sync with web_lazy_precompute_common.LAZY_TTL_SECONDS;
- # see there for the rationale (the ~6h result cache fronts these reads).
- "0d": 2 * 60 * 60,
- "1d": 60 * 60,
- "7d": 24 * 60 * 60,
- "default": 7 * 24 * 60 * 60,
-}
-
# Today the gate accepts: empty user filters, or a single EventPropertyFilter
# on `$host` with operator `exact`. Test-account filters are always allowed
# (their content is hashed into the cache key).
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 e7000bc8c9d4..c8f5b38c788a 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
@@ -306,6 +306,7 @@ def ensure_web_goals_precomputed(
table=LazyComputationTable.WEB_GOALS_PREAGGREGATED,
placeholders=placeholders,
query_type="web_goals_lazy_insert",
+ spill_to_disk=True, # per-action GROUP BY over a sessions join; can build a large hash table
)
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 b12b33edb57a..2ffc4b410baf 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
@@ -47,16 +47,26 @@ _FILTERS_ELIGIBILITY_HASH_IGNORED_QUERY_FIELDS: frozenset[str] = frozenset(
}
)
-# Hourly UTC bucketing TTL schedule. Today gets 2h: recomputing it more often
-# buys nothing, since the ~6h HogQL result cache already fronts these queries (a
-# cache hit never reads the precompute), and a tighter TTL just makes the warmer
-# re-scan the whole current day every tick — which is what kept a full warm pass
-# from finishing inside the hourly window. Older buckets get longer TTLs.
+# Hourly UTC bucketing TTL schedule. Two jobs in one:
+#
+# 1. Freshness — today gets 2h (recomputing it more often buys nothing: the ~6h
+# HogQL result cache already fronts these queries, so a cache hit never reads
+# the precompute). Older windows get progressively longer TTLs.
+# 2. Job sizing — `split_ranges_by_ttl` merges *consecutive days with the same
+# TTL* into one job. Distinct per-week TTLs therefore force weekly job
+# boundaries, so a 31-day warm splits into ≤7-day jobs instead of one ~24-day
+# block. That keeps each per-day INSERT's events↔sessions scan bounded — the
+# 24-day merge is what drove the multi-hundred-million-row scans that OOM the
+# insert on very high-traffic teams.
LAZY_TTL_SECONDS: dict[str, int] = {
- "0d": 2 * 60 * 60,
- "1d": 60 * 60,
- "7d": 24 * 60 * 60,
- "default": 7 * 24 * 60 * 60,
+ "0d": 2 * 60 * 60, # today
+ "1d": 60 * 60, # yesterday
+ "7d": 24 * 60 * 60, # days 2–7 → one ~6d job
+ "14d": 2 * 24 * 60 * 60, # days 8–14 → one 7d job
+ "21d": 4 * 24 * 60 * 60, # days 15–21 → one 7d job
+ "28d": 7 * 24 * 60 * 60, # days 22–28 → one 7d job
+ "35d": 10 * 24 * 60 * 60, # days 29–35 → one 7d job (covers the tail of a 31d warm)
+ "default": 14 * 24 * 60 * 60, # days 36+
}
# MVP user-filter allowlist: only an EventPropertyFilter on `$host` with
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 70c518d6fdaa..dfdba2c753e6 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
@@ -241,6 +241,7 @@ def ensure_web_stats_frustration_precomputed(
table=LazyComputationTable.WEB_STATS_FRUSTRATION_PREAGGREGATED,
placeholders=placeholders,
query_type="web_stats_frustration_lazy_insert",
+ spill_to_disk=True, # session-level GROUP BY over a sessions join; can build a large hash table
)
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 ccc21023dfe3..80a858cca6d8 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
@@ -283,6 +283,7 @@ def ensure_web_stats_precomputed(
table=LazyComputationTable.WEB_STATS_PREAGGREGATED,
placeholders=placeholders,
query_type=f"web_stats_{runner.query.breakdownBy.value}_lazy_insert",
+ spill_to_disk=True, # high-cardinality breakdown GROUP BY; can build a large hash table
)
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 87b2842ed8ec..846ebcc52252 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
@@ -299,6 +299,7 @@ def ensure_web_stats_paths_precomputed(
table=LazyComputationTable.WEB_STATS_PATHS_PREAGGREGATED,
placeholders=placeholders,
query_type="web_stats_paths_lazy_insert",
+ spill_to_disk=True, # high-cardinality path breakdown GROUP BY; can build a large hash table
)
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 adfbf1125aa0..6cf2e8d459d3 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
@@ -211,6 +211,7 @@ def ensure_web_vitals_paths_precomputed(
table=LazyComputationTable.WEB_VITALS_PATHS_PREAGGREGATED,
placeholders=placeholders,
query_type="web_vitals_paths_lazy_insert",
+ spill_to_disk=True, # high-cardinality path breakdown GROUP BY; can build a large hash table
)