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.

feat(web-analytics): volume floor for precompute reads and warming (#86728)

Lucas Ricoyc28cbc3401dd
diff --git a/posthog/settings/web.py b/posthog/settings/web.py
index 227cbe2e8c8d..fe7ccaaf620d 100644
--- a/posthog/settings/web.py
+++ b/posthog/settings/web.py
@@ -1328,6 +1328,14 @@ WEB_ANALYTICS_LAZY_PRECOMPUTE_TEAM_IDS: list[int] = [
for team_id in get_list(get_from_env("WEB_ANALYTICS_LAZY_PRECOMPUTE_TEAM_IDS", _LAZY_PRECOMPUTE_DEFAULT_TEAM_IDS))
]
+# Weekly (7-day) event-volume floor below which a team gets neither precompute
+# reads nor warming — their live path is sub-second and always fresh, while
+# bucket builds cost more than they save. 0 disables the floor. Enforced
+# fail-open: reads fall back to precompute when the volume set is unpublished.
+WEB_ANALYTICS_PRECOMPUTE_MIN_WEEKLY_EVENTS: int = get_from_env(
+ "WEB_ANALYTICS_PRECOMPUTE_MIN_WEEKLY_EVENTS", 100_000, type_cast=int
+)
+
# Dogfooding list for the precompute-backed web analytics trends path — teams
# here take it regardless of the `web-analytics-trends-precompute` rollout flag.
# The shared precompute enrollment gate still applies underneath.
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 c47cb9b29a01..02dd79bf1a98 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
@@ -36,13 +36,18 @@ from products.analytics_platform.backend.lazy_computation.lazy_computation_execu
TtlSchedule,
)
from products.web_analytics.backend.hogql_queries.stats_table import WebStatsTableQueryRunner
+from products.web_analytics.backend.hogql_queries.web_analytics_lazy_precompute import can_use_lazy_precompute
from products.web_analytics.backend.hogql_queries.web_lazy_precompute_common import (
+ _VOLUME_FLOOR_LOCAL_CACHE,
OOM_PIN_TTL_SECONDS,
REVALIDATION_START_DELAY_SECONDS,
REVALIDATION_TRIGGER,
SESSION_SETTLING_SECONDS,
STALE_WHILE_REVALIDATE_SECONDS,
TEAM_SHAPE_SET_TTL_SECONDS,
+ VOLUME_FLOOR_READY_KEY,
+ VOLUME_FLOOR_TEAMS_KEY,
+ BelowVolumeFloor,
DateRangeOverMax,
PerQueryOptedOut,
PropertyAccessControlled,
@@ -55,10 +60,12 @@ from products.web_analytics.backend.hogql_queries.web_lazy_precompute_common imp
handle_stale_served,
host_filter_expr,
is_precompute_enabled_for_team,
+ is_team_above_volume_floor,
is_team_oom_pinned,
lazy_precompute_ineligible_reason,
log_eligibility_outcome,
pin_team_oom,
+ publish_volume_floor_teams,
try_reserve_precompute_shape,
web_ensure_precomputed,
)
@@ -336,6 +343,16 @@ class TestCacheKeyVariesWithRolloutState(BaseTest):
key_disabled = self._cache_key()
assert key_enabled != key_disabled
+ def test_crossing_the_volume_floor_changes_cache_key(self) -> None:
+ # A team crossing below the floor switches to the live path; the key must
+ # change so a precompute-produced response is not served until it stales.
+ with mock.patch(f"{self._RUNNER_MOD}.is_precompute_enabled_for_team", return_value=True):
+ with mock.patch(f"{self._RUNNER_MOD}.is_team_above_volume_floor", return_value=True):
+ key_above = self._cache_key()
+ with mock.patch(f"{self._RUNNER_MOD}.is_team_above_volume_floor", return_value=False):
+ key_below = self._cache_key()
+ assert key_above != key_below
+
class TestHostFilterExpr(BaseTest):
def test_empty_properties_is_true_constant(self) -> None:
@@ -794,6 +811,124 @@ class TestWebEnsurePrecomputed(BaseTest):
assert schedule.get_ttl(fresh_window_start) == 3600
+class TestVolumeFloor(BaseTest):
+ def setUp(self):
+ super().setUp()
+ _VOLUME_FLOOR_LOCAL_CACHE.clear()
+
+ def tearDown(self):
+ client = redis.get_client()
+ client.delete(VOLUME_FLOOR_TEAMS_KEY, VOLUME_FLOOR_READY_KEY, f"{VOLUME_FLOOR_TEAMS_KEY}:staging")
+ _VOLUME_FLOOR_LOCAL_CACHE.clear()
+ super().tearDown()
+
+ @override_settings(WEB_ANALYTICS_PRECOMPUTE_MIN_WEEKLY_EVENTS=100_000)
+ def test_fail_open_until_published_then_enforces_membership(self):
+ assert is_team_above_volume_floor(self.team.pk) is True # unpublished: fail open
+ _VOLUME_FLOOR_LOCAL_CACHE.clear()
+
+ publish_volume_floor_teams([self.team.pk + 1])
+ assert is_team_above_volume_floor(self.team.pk) is False
+ assert is_team_above_volume_floor(self.team.pk + 1) is True
+ _VOLUME_FLOOR_LOCAL_CACHE.clear()
+
+ # Republish replaces the whole set: the previous member drops out.
+ publish_volume_floor_teams([self.team.pk])
+ assert is_team_above_volume_floor(self.team.pk) is True
+ assert is_team_above_volume_floor(self.team.pk + 1) is False
+
+ @override_settings(WEB_ANALYTICS_PRECOMPUTE_MIN_WEEKLY_EVENTS=100_000)
+ def test_hysteresis_keeps_existing_members_above_exit_floor(self):
+ member = self.team.pk + 1
+ newcomer = self.team.pk + 2
+ publish_volume_floor_teams([member])
+ # Next pass: member fell under the entry floor but stays above the exit
+ # floor; newcomer is between the floors and was never a member.
+ publish_volume_floor_teams([], above_exit_floor=[member, newcomer])
+ assert is_team_above_volume_floor(member) is True
+ assert is_team_above_volume_floor(newcomer) is False
+
+ @override_settings(WEB_ANALYTICS_PRECOMPUTE_MIN_WEEKLY_EVENTS=100_000)
+ def test_env_enrolled_teams_bypass_the_floor(self):
+ publish_volume_floor_teams([self.team.pk + 1])
+ with override_settings(WEB_ANALYTICS_LAZY_PRECOMPUTE_TEAM_IDS=[self.team.pk]):
+ assert is_team_above_volume_floor(self.team.pk) is True
+
+ @override_settings(WEB_ANALYTICS_PRECOMPUTE_MIN_WEEKLY_EVENTS=100_000)
+ def test_empty_publish_enforces_below_floor_for_everyone(self):
+ publish_volume_floor_teams([self.team.pk])
+ _VOLUME_FLOOR_LOCAL_CACHE.clear()
+ # No team above the floor is a valid verdict, not an error: the set is
+ # dropped, the sentinel stays, and every non-enrolled team reads below
+ # floor instead of the publish raising mid-pipeline.
+ publish_volume_floor_teams([])
+ assert is_team_above_volume_floor(self.team.pk) is False
+
+ @override_settings(WEB_ANALYTICS_PRECOMPUTE_MIN_WEEKLY_EVENTS=100_000)
+ def test_lost_teams_set_fails_open_despite_sentinel(self):
+ publish_volume_floor_teams([self.team.pk + 1])
+ _VOLUME_FLOOR_LOCAL_CACHE.clear()
+ # Eviction or TTL drift can lose the set while the sentinel survives;
+ # that must read as "state lost, fail open", not fleet-wide below-floor.
+ redis.get_client().delete(VOLUME_FLOOR_TEAMS_KEY)
+ assert is_team_above_volume_floor(self.team.pk) is True
+
+ @override_settings(WEB_ANALYTICS_PRECOMPUTE_MIN_WEEKLY_EVENTS=0)
+ def test_zero_floor_disables_the_check(self):
+ publish_volume_floor_teams([self.team.pk + 1])
+ assert is_team_above_volume_floor(self.team.pk) is True
+
+ @override_settings(WEB_ANALYTICS_PRECOMPUTE_MIN_WEEKLY_EVENTS=100_000)
+ def test_gate_rejects_below_floor_team_including_background(self):
+ publish_volume_floor_teams([self.team.pk + 1])
+ runner = WebOverviewQueryRunner(
+ query=WebOverviewQuery(dateRange=DateRange(date_from="-7d"), properties=[]), team=self.team
+ )
+ with mock.patch(
+ "products.web_analytics.backend.hogql_queries.web_lazy_precompute_common.posthoganalytics.feature_enabled",
+ return_value=True,
+ ):
+ with self.assertRaises(BelowVolumeFloor):
+ check_common_eligibility(
+ team=self.team,
+ use_web_analytics_precompute=None,
+ conversion_goal=None,
+ sampling=None,
+ modifiers=runner.modifiers,
+ properties=[],
+ resolve_date_range=lambda: (None, None),
+ )
+ # The floor must hold for warming replays too — building buckets
+ # for a below-floor team is the waste the floor exists to stop.
+ with tags_context(trigger="webAnalyticsStaleRevalidation", feature=Feature.CACHE_WARMUP):
+ with self.assertRaises(BelowVolumeFloor):
+ check_common_eligibility(
+ team=self.team,
+ use_web_analytics_precompute=None,
+ conversion_goal=None,
+ sampling=None,
+ modifiers=runner.modifiers,
+ properties=[],
+ resolve_date_range=lambda: (None, None),
+ )
+
+ @override_settings(WEB_ANALYTICS_PRECOMPUTE_MIN_WEEKLY_EVENTS=100_000)
+ def test_overview_stats_trends_gate_rejects_below_floor_team(self):
+ # Overview, stats, and trends reach the gate through `can_use_lazy_precompute`
+ # / `check_common_eligible`, not `check_common_eligibility`. Without the floor
+ # check there, a below-floor team keeps serving those primary tiles from
+ # precompute. The flag is forced on so the floor is the only rejection reason.
+ publish_volume_floor_teams([self.team.pk + 1])
+ runner = WebOverviewQueryRunner(
+ query=WebOverviewQuery(dateRange=DateRange(date_from="-7d"), properties=[]), team=self.team
+ )
+ with mock.patch(
+ "products.web_analytics.backend.hogql_queries.web_analytics_lazy_precompute.is_precompute_enabled_for_team",
+ return_value=True,
+ ):
+ assert can_use_lazy_precompute(runner, log_prefix="web_overview") is False
+
+
class TestStaleRevalidationEnqueue(BaseTest):
def setUp(self):
super().setUp()
diff --git a/products/web_analytics/backend/hogql_queries/test/test_web_trends_lazy_precompute.py b/products/web_analytics/backend/hogql_queries/test/test_web_trends_lazy_precompute.py
index fa83831a84b7..9b8059993972 100644
--- a/products/web_analytics/backend/hogql_queries/test/test_web_trends_lazy_precompute.py
+++ b/products/web_analytics/backend/hogql_queries/test/test_web_trends_lazy_precompute.py
@@ -275,6 +275,23 @@ class TestWebTrendsLazyPrecompute(ClickhouseTestMixin, APIBaseTest):
assert PreaggregationJob.objects.filter(team_id=self.team.pk).count() == 0
assert sum(response.results[0]["data"]) == 2
+ def test_cache_key_varies_with_volume_floor(self) -> None:
+ # Trends builds its cache key via get_cache_payload, not the base runner's
+ # get_cache_key, so the base runner's _vf suffix does not cover it. A team
+ # crossing below the floor switches to the live path; its key must change
+ # so a stale precompute result is not served until it ages out.
+ runner = WebTrendsQueryRunner(team=self.team, query=self._build_query())
+ mod = "products.web_analytics.backend.hogql_queries.web_trends"
+ with (
+ patch(f"{mod}.is_trends_precompute_enabled_for_team", return_value=True),
+ patch(f"{mod}.is_precompute_enabled_for_team", return_value=True),
+ ):
+ with patch(f"{mod}.is_team_above_volume_floor", return_value=True):
+ key_above = runner.get_cache_key()
+ with patch(f"{mod}.is_team_above_volume_floor", return_value=False):
+ key_below = runner.get_cache_key()
+ assert key_above != key_below
+
@parameterized.expand(
[
# Shapes the buckets can't reproduce must fall back — serving them
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 7df594743346..d89536ec5f1c 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
@@ -30,6 +30,7 @@ from products.access_control.backend.facade.api import team_has_property_access_
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,
+ is_team_above_volume_floor,
set_lazy_precompute_ineligible_reason,
)
@@ -129,6 +130,18 @@ class PerQueryOptedOut(LazyPrecomputeIneligible):
pass
+class BelowVolumeFloor(LazyPrecomputeIneligible):
+ """The team's 7-day event volume is under the precompute floor — its live
+ path is sub-second and always fresh, so the query stays live.
+
+ Deliberately duplicated from `web_lazy_precompute_common.BelowVolumeFloor`:
+ the two modules keep parallel `LazyPrecomputeIneligible` hierarchies, so each
+ gate must raise its own module's class to be caught by its own `except`.
+ Keep the two in sync. Both share the name, so logs/metrics keyed on
+ `type(exc).__name__` collapse to one label regardless of which gate fired.
+ """
+
+
class NonIntegerTimezone(LazyPrecomputeIneligible):
pass
@@ -259,6 +272,13 @@ def check_common_eligible(runner: LazyPrecomputeRunner, *, require_integer_timez
if query.useWebAnalyticsPrecompute is False:
raise PerQueryOptedOut()
+ # Below-floor teams serve live (sub-second, always fresh). Checked here too,
+ # not only in `check_common_eligibility`: overview, stats, and trends reach
+ # the gate through this function, so without it the floor never covers the
+ # primary dashboard tiles. Deliberately checked for background warming too.
+ if not is_team_above_volume_floor(runner.team.pk):
+ raise BelowVolumeFloor()
+
# Half-hour-offset timezones (IST +5:30, Newfoundland -3:30, Nepal +5:45, etc.)
# can't be served by UTC hourly buckets without sub-hour precision. Skip them
# rather than return wrong totals on the boundary days. Runners that bucket
diff --git a/products/web_analytics/backend/hogql_queries/web_analytics_query_runner.py b/products/web_analytics/backend/hogql_queries/web_analytics_query_runner.py
index 1a320e9cb252..87b94273daf0 100644
--- a/products/web_analytics/backend/hogql_queries/web_analytics_query_runner.py
+++ b/products/web_analytics/backend/hogql_queries/web_analytics_query_runner.py
@@ -62,6 +62,7 @@ from products.web_analytics.backend.hogql_queries.traffic_type import get_traffi
from products.web_analytics.backend.hogql_queries.web_lazy_precompute_common import (
compute_filters_eligibility_hash,
is_precompute_enabled_for_team,
+ is_team_above_volume_floor,
)
logger = structlog.get_logger(__name__)
@@ -768,7 +769,12 @@ WHERE and(
# (the kill switch) must not keep serving cached precompute-produced
# responses until they stale out.
precompute = is_precompute_enabled_for_team(self.team)
- key = f"{original}_{self.team.path_cleaning_filters}_pc{int(precompute)}"
+ # The volume-floor verdict is part of the key too: a team crossing below
+ # the floor switches to the live path, so a precompute-produced response
+ # under the old key must not keep serving until it stales out. Only read
+ # the floor when precompute is on — otherwise it can't change the result.
+ above_floor = precompute and is_team_above_volume_floor(self.team.pk)
+ key = f"{original}_{self.team.path_cleaning_filters}_pc{int(precompute)}_vf{int(above_floor)}"
# A rewritten filter selects a different population for the same query, so
# rewritten and entry-attributed runs must not share cache entries.
if self.rewritten_first_pageview_filters:
diff --git a/products/web_analytics/backend/hogql_queries/web_calendar_heatmap.py b/products/web_analytics/backend/hogql_queries/web_calendar_heatmap.py
index 1623b97b7ccb..0fbe72d9a133 100644
--- a/products/web_analytics/backend/hogql_queries/web_calendar_heatmap.py
+++ b/products/web_analytics/backend/hogql_queries/web_calendar_heatmap.py
@@ -33,6 +33,7 @@ from products.web_analytics.backend.hogql_queries.web_analytics_lazy_precompute
from products.web_analytics.backend.hogql_queries.web_lazy_precompute_common import (
handle_stale_served,
is_precompute_enabled_for_team,
+ is_team_above_volume_floor,
)
from products.web_analytics.backend.hogql_queries.web_overview import WebOverviewQueryRunner
from products.web_analytics.backend.hogql_queries.web_overview_lazy_precompute import (
@@ -254,9 +255,12 @@ class WebCalendarHeatmapTrendsQueryRunner(CalendarHeatmapTrendsQueryRunner):
# Rollout state in the cache key = immediate kill switch: disabling a
# flag must not keep serving cached precompute-derived results until
# they stale out (same mechanism as WebTrendsQueryRunner).
- payload["web_trends_precompute"] = is_trends_precompute_enabled_for_team(
- self.team
- ) and is_precompute_enabled_for_team(self.team)
+ precompute = is_trends_precompute_enabled_for_team(self.team) and is_precompute_enabled_for_team(self.team)
+ payload["web_trends_precompute"] = precompute
+ # The volume floor also flips the serving path (precompute <-> live), so
+ # it must vary the key too: a team crossing below the floor keeps serving
+ # a stale precompute result otherwise. Read it only when precompute is on.
+ payload["web_trends_above_floor"] = precompute and is_team_above_volume_floor(self.team.pk)
return payload
def _calculate(self) -> TrendsQueryResponse:
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 2fd2e56859c4..57956b8c8588 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
@@ -10,6 +10,7 @@ too, bounding how many namespaces the loosened filter gate lets a team mint.
"""
import json
+import time
import hashlib
from collections.abc import Callable
from dataclasses import replace
@@ -65,6 +66,96 @@ def _oom_pin_key(team_id: int) -> str:
return f"{TEAM_OOM_PIN_REDIS_PREFIX}{team_id}"
+# Above-floor team set, refreshed by the hourly demand warmer from a
+# marks-only fleet event count. Reads consult it fail-open: an unpublished or
+# expired set (sentinel absent, or Redis down) keeps current behavior, so the
+# floor can only narrow precompute when the warmer is actively maintaining it.
+VOLUME_FLOOR_TEAMS_KEY = "{web_precompute_volume_floor}:teams"
+VOLUME_FLOOR_READY_KEY = "{web_precompute_volume_floor}:ready"
+VOLUME_FLOOR_TTL_SECONDS = 48 * 3600
+
+
+# One dashboard load passes the gate once per family, so cache the verdict
+# in-process for a short window. 60s is far below the hourly publish cadence,
+# and the dict is bounded per process by web analytics' active-team working set.
+_VOLUME_FLOOR_LOCAL_CACHE: dict[int, tuple[float, bool]] = {}
+_VOLUME_FLOOR_LOCAL_CACHE_SECONDS = 60.0
+_VOLUME_FLOOR_LOCAL_CACHE_MAX_ENTRIES = 50_000
+
+
+def is_team_above_volume_floor(team_id: int) -> bool:
+ if settings.WEB_ANALYTICS_PRECOMPUTE_MIN_WEEKLY_EVENTS <= 0:
+ return True
+ # Explicit env enrollment beats the volume heuristic: those teams were
+ # opted in deliberately (dogfooding, support escalations) regardless of size.
+ if team_id in settings.WEB_ANALYTICS_LAZY_PRECOMPUTE_TEAM_IDS:
+ return True
+ cached = _VOLUME_FLOOR_LOCAL_CACHE.get(team_id)
+ if cached is not None and time.monotonic() - cached[0] < _VOLUME_FLOOR_LOCAL_CACHE_SECONDS:
+ return cached[1]
+ try:
+ client = redis.get_client()
+ # Membership first: above-floor teams (the vast majority of gate
+ # traffic) resolve in one round trip. On a miss, the floor only
+ # enforces when BOTH keys exist: the sentinel alone is not trusted, so
+ # a lost or expired teams set (eviction, TTL drift) fails open instead
+ # of silently disabling precompute fleet-wide. Intentionally-empty
+ # publishes keep the set alive via a placeholder member.
+ # Accepted transient: a reader racing the very first publish can miss
+ # membership then see both keys, reading below-floor for up to the
+ # local cache window — it degrades to the live path, never breaks.
+ if client.sismember(VOLUME_FLOOR_TEAMS_KEY, str(team_id)):
+ result = True
+ else:
+ result = not (client.exists(VOLUME_FLOOR_READY_KEY) and client.exists(VOLUME_FLOOR_TEAMS_KEY))
+ except Exception:
+ logger.exception("web_precompute_volume_floor_check_failed", team_id=team_id)
+ result = True
+ if len(_VOLUME_FLOOR_LOCAL_CACHE) >= _VOLUME_FLOOR_LOCAL_CACHE_MAX_ENTRIES:
+ _VOLUME_FLOOR_LOCAL_CACHE.clear()
+ _VOLUME_FLOOR_LOCAL_CACHE[team_id] = (time.monotonic(), result)
+ return result
+
+
+def publish_volume_floor_teams(above_floor: list[int], above_exit_floor: Optional[list[int]] = None) -> None:
+ """Atomically replace the above-floor set. RENAME keeps readers off a
+ half-written set; the TTLs make a dead warmer fail open within 48h.
+
+ `above_exit_floor` enables hysteresis: teams in it that are already
+ members stay members even when they fell under the entry floor, so a team
+ oscillating around the threshold does not flap in and out hourly (each
+ exit discards warm buckets that re-entry rebuilds from scratch).
+ """
+ client = redis.get_client()
+ members: set[str] = {str(t) for t in above_floor}
+ if above_exit_floor:
+ try:
+ current = {m.decode() if isinstance(m, bytes) else str(m) for m in client.smembers(VOLUME_FLOOR_TEAMS_KEY)}
+ except Exception:
+ # Degrading to no hysteresis evicts every between-floors member
+ # this pass; they re-enter next pass if they recover. Loud so a
+ # persistent Redis problem does not silently churn buckets.
+ logger.exception("web_precompute_volume_floor_hysteresis_read_failed")
+ current = set()
+ members |= {str(t) for t in above_exit_floor if str(t) in current}
+ member_list = sorted(members)
+ if not member_list:
+ # An empty publish is a valid verdict (no team above the floor). A
+ # placeholder member keeps the set alive: RENAME from a never-written
+ # staging key would raise mid-transaction, and the gate reads a
+ # MISSING set as "lost, fail open" rather than "empty, enforce".
+ member_list = ["__none__"]
+ tmp_key = f"{VOLUME_FLOOR_TEAMS_KEY}:staging"
+ pipe = client.pipeline()
+ pipe.delete(tmp_key)
+ for chunk_start in range(0, len(member_list), 5000):
+ pipe.sadd(tmp_key, *member_list[chunk_start : chunk_start + 5000])
+ pipe.rename(tmp_key, VOLUME_FLOOR_TEAMS_KEY)
+ pipe.expire(VOLUME_FLOOR_TEAMS_KEY, VOLUME_FLOOR_TTL_SECONDS)
+ pipe.set(VOLUME_FLOOR_READY_KEY, "1", ex=VOLUME_FLOOR_TTL_SECONDS)
+ pipe.execute()
+
+
def is_team_oom_pinned(team_id: int) -> bool:
"""Whether the team has hit an OOM recently and should cap its insert windows.
@@ -542,6 +633,11 @@ class NonIntegerTimezone(LazyPrecomputeIneligible):
pass
+class BelowVolumeFloor(LazyPrecomputeIneligible):
+ """The team's 7-day event volume is under the precompute floor — its live
+ path is sub-second and always fresh, so the query stays live."""
+
+
class ConversionGoalUnsupported(LazyPrecomputeIneligible):
pass
@@ -673,6 +769,13 @@ def check_common_eligibility(
if use_web_analytics_precompute is False:
raise PerQueryOptedOut()
+ # After the free local checks (this one costs a Redis round trip on local
+ # cache miss). Deliberately checked for background warming too: the floor
+ # exists to stop building buckets for teams whose live path already
+ # serves them better.
+ if not is_team_above_volume_floor(team.pk):
+ raise BelowVolumeFloor()
+
if not is_integer_timezone(team.timezone):
raise NonIntegerTimezone()
diff --git a/products/web_analytics/backend/hogql_queries/web_trends.py b/products/web_analytics/backend/hogql_queries/web_trends.py
index 98eb56db9892..ba9262459d10 100644
--- a/products/web_analytics/backend/hogql_queries/web_trends.py
+++ b/products/web_analytics/backend/hogql_queries/web_trends.py
@@ -1,7 +1,10 @@
from posthog.schema import QueryTiming, ResolvedDateRangeResponse, TrendsQueryResponse
from products.product_analytics.backend.facade.queries import TrendsQueryRunner
-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 (
+ is_precompute_enabled_for_team,
+ is_team_above_volume_floor,
+)
from products.web_analytics.backend.hogql_queries.web_trends_lazy_precompute import (
execute_lazy_precomputed_trends,
is_trends_precompute_enabled_for_team,
@@ -25,9 +28,12 @@ class WebTrendsQueryRunner(TrendsQueryRunner):
# immediate kill switch: without this, cached precompute-served results
# keep being returned until they stale out naturally (the overview
# runner does the same via its `_pc` cache-key suffix).
- payload["web_trends_precompute"] = is_trends_precompute_enabled_for_team(
- self.team
- ) and is_precompute_enabled_for_team(self.team)
+ precompute = is_trends_precompute_enabled_for_team(self.team) and is_precompute_enabled_for_team(self.team)
+ payload["web_trends_precompute"] = precompute
+ # The volume floor also flips the serving path (precompute <-> live), so
+ # it must vary the key too: a team crossing below the floor keeps serving
+ # a stale precompute result otherwise. Read it only when precompute is on.
+ payload["web_trends_above_floor"] = precompute and is_team_above_volume_floor(self.team.pk)
return payload
def _calculate(self) -> TrendsQueryResponse:
diff --git a/products/web_analytics/backend/hogql_queries/web_vitals_timeseries.py b/products/web_analytics/backend/hogql_queries/web_vitals_timeseries.py
index 8c613ea05799..bbb4dcec31a4 100644
--- a/products/web_analytics/backend/hogql_queries/web_vitals_timeseries.py
+++ b/products/web_analytics/backend/hogql_queries/web_vitals_timeseries.py
@@ -5,7 +5,10 @@ from posthog.schema import QueryTiming, ResolvedDateRangeResponse, TrendsQuery,
from posthog.schema_helpers import to_dict
from products.product_analytics.backend.facade.queries import TrendsQueryRunner
-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 (
+ is_precompute_enabled_for_team,
+ is_team_above_volume_floor,
+)
from products.web_analytics.backend.hogql_queries.web_vitals_timeseries_lazy_precompute import (
execute_lazy_precomputed_vitals_timeseries,
is_vitals_precompute_enabled_for_team,
@@ -42,9 +45,12 @@ class WebVitalsQueryRunner(TrendsQueryRunner):
# Rollout state in the cache key = immediate kill switch: disabling a
# flag must not keep serving cached precompute-derived results until
# they stale out (same mechanism as WebTrendsQueryRunner).
- payload["web_vitals_timeseries_precompute"] = is_vitals_precompute_enabled_for_team(
- self.team
- ) and is_precompute_enabled_for_team(self.team)
+ precompute = is_vitals_precompute_enabled_for_team(self.team) and is_precompute_enabled_for_team(self.team)
+ payload["web_vitals_timeseries_precompute"] = precompute
+ # The volume floor also flips the serving path (precompute <-> live), so
+ # it must vary the key too: a team crossing below the floor keeps serving
+ # a stale precompute result otherwise. Read it only when precompute is on.
+ payload["web_vitals_timeseries_above_floor"] = precompute and is_team_above_volume_floor(self.team.pk)
# `super()` serializes only the inner TrendsQuery, but the precompute
# read builds its jobs from the wrapper's own filters (see
# `_build_inner_path_breakdown_query`). Fold those into the key — using
diff --git a/products/web_analytics/dags/cache_warming.py b/products/web_analytics/dags/cache_warming.py
index 8be6b95c82ab..e9b8b3fe16f5 100644
--- a/products/web_analytics/dags/cache_warming.py
+++ b/products/web_analytics/dags/cache_warming.py
@@ -11,6 +11,7 @@ from concurrent.futures import FIRST_COMPLETED, ThreadPoolExecutor, wait
from datetime import datetime, timedelta
from typing import TYPE_CHECKING, Optional
+from django.conf import settings
from django.core.exceptions import ObjectDoesNotExist
from django.db import close_old_connections
from django.utils.dateparse import parse_datetime
@@ -23,7 +24,8 @@ from prometheus_client import Counter, Gauge
from posthog.hogql.constants import LimitContext
from posthog.clickhouse.client import sync_execute
-from posthog.clickhouse.query_tagging import Feature, reset_query_tags, tag_queries
+from posthog.clickhouse.client.connection import Workload
+from posthog.clickhouse.query_tagging import Feature, Product, reset_query_tags, tag_queries
from posthog.dags.common import JobOwners
from posthog.event_usage import EventSource
from posthog.exceptions import ClickHouseAtCapacity
@@ -43,6 +45,8 @@ from products.web_analytics.backend.hogql_queries.web_lazy_precompute_common imp
BACKGROUND_WARMING_TRIGGERS,
MAX_PRECOMPUTE_DAYS,
SHAPE_CAP_KEY_IGNORED_QUERY_FIELDS,
+ is_team_above_volume_floor,
+ publish_volume_floor_teams,
)
from products.web_analytics.backend.hogql_queries.web_overview_lazy_precompute import (
can_use_lazy_precompute as can_use_overview_lazy_precompute,
@@ -620,7 +624,59 @@ def _write_cached_warmable_queries(days: int, minimum_query_count: int, max_shap
@dagster.op
-def get_warmable_queries_op(context: dagster.OpExecutionContext) -> list[dict]:
+def publish_volume_floor_op(context: dagster.OpExecutionContext) -> bool:
+ """Refresh the above-floor team set the shared eligibility gate reads.
+
+ The count reads only the timestamp column over a 7-day window on the
+ OFFLINE workload; publishing before selection means this hour's warming
+ pass and all reads share one fresh floor. Fail-open by design: on any
+ error the previous set (or its expiry) governs and warming proceeds.
+ """
+ floor = settings.WEB_ANALYTICS_PRECOMPUTE_MIN_WEEKLY_EVENTS
+ if floor <= 0:
+ context.log.info("Volume floor disabled (WEB_ANALYTICS_PRECOMPUTE_MIN_WEEKLY_EVENTS <= 0).")
+ return True
+ try:
+ # Scan down to the exit floor (half the entry floor) so hysteresis has
+ # the candidates it needs: existing members stay until they fall below
+ # the exit floor instead of flapping around the entry threshold.
+ exit_floor = max(1, floor // 2)
+ tag_queries(feature=Feature.CACHE_WARMUP, trigger="webAnalyticsQueryWarming", product=Product.WEB_ANALYTICS)
+ rows = sync_execute(
+ """
+ SELECT team_id, count() AS ev7d
+ FROM events
+ WHERE timestamp > now() - INTERVAL 7 DAY AND timestamp < now()
+ GROUP BY team_id
+ HAVING ev7d >= %(exit_floor)s
+ """,
+ {"exit_floor": exit_floor},
+ workload=Workload.OFFLINE,
+ # Bound the fleet scan like the shape-selection query: a marks-only
+ # count still reads the timestamp column across every team, so cap it
+ # rather than let a plan regression drain offline capacity to timeout.
+ settings={"max_bytes_to_read": _SELECTION_MAX_BYTES_TO_READ, "max_execution_time": 300},
+ )
+ above_floor = [int(r[0]) for r in rows if int(r[1]) >= floor]
+ above_exit_floor = [int(r[0]) for r in rows]
+ if not above_floor:
+ # On any real fleet an empty result means the scan broke, not that
+ # every team shrank below the floor at once. Skip the publish so
+ # the previous set (or its 48h expiry, which fails open) governs.
+ context.log.error("Volume floor scan returned no teams; skipping publish (previous set governs).")
+ return True
+ publish_volume_floor_teams(above_floor, above_exit_floor=above_exit_floor)
+ context.log.info(
+ f"Published {len(above_floor)} teams at/above the {floor}-events/7d precompute floor "
+ f"(hysteresis band down to {exit_floor})."
+ )
+ except Exception:
+ context.log.exception("Volume floor refresh failed; readers keep the previous set (fail-open).")
+ return True
+
+
+def get_warmable_queries_op(context: dagster.OpExecutionContext, floor_published: bool = True) -> list[dict]:
days = get_instance_setting("WEB_ANALYTICS_WARMING_DAYS")
minimum_query_count = get_instance_setting("WEB_ANALYTICS_WARMING_MIN_QUERY_COUNT")
max_shapes = get_instance_setting("WEB_ANALYTICS_WARMING_MAX_SHAPES")
@@ -634,16 +690,36 @@ def get_warmable_queries_op(context: dagster.OpExecutionContext) -> list[dict]:
)
_write_cached_warmable_queries(days, minimum_query_count, max_shapes, queries)
- team_count = len({q["team_id"] for q in queries})
+ selected_count = len(queries)
+ # `cap_reached` keys off the pre-floor selection: the cap bounds the
+ # selection query, and floor-dropped shapes still consumed cap slots.
+ cap_reached = selected_count >= max_shapes
+ # The floor is enforced here, per replay, not in the selection SQL: keeping the
+ # cached selection floor-agnostic means a team that grows above the floor is
+ # warmed on the next pass, rather than waiting for the selection blob's TTL to
+ # lapse. Below-floor shapes that consumed cap slots are dropped here; a fresh
+ # `is_team_above_volume_floor` verdict (60s-cached) applies each pass.
+ queries = [q for q in queries if is_team_above_volume_floor(int(q["team_id"]))]
+ floor_dropped = selected_count - len(queries)
+ team_count = len({q["team_id"] for q in queries})
WARMING_SHAPES_SELECTED_GAUGE.set(len(queries))
source = "cached" if from_cache else "freshly selected"
- context.log.info(f"Warming {len(queries)} {source} hot query shapes across {team_count} teams")
+ context.log.info(
+ f"Warming {len(queries)} {source} hot query shapes across {team_count} teams"
+ + (
+ f" (volume floor dropped {floor_dropped} shapes under "
+ f"{settings.WEB_ANALYTICS_PRECOMPUTE_MIN_WEEKLY_EVENTS} events/7d)"
+ if floor_dropped
+ else ""
+ )
+ )
context.add_output_metadata(
{
"query_count": len(queries),
"team_count": team_count,
- "cap_reached": len(queries) >= max_shapes,
+ "floor_dropped": floor_dropped,
+ "cap_reached": cap_reached,
"from_cache": from_cache,
}
)
@@ -1199,7 +1275,8 @@ def report_warming_plan_op(context: dagster.OpExecutionContext, queries: list[di
},
)
def web_analytics_cache_warming_job():
- queries = get_warmable_queries_op()
+ floor_published = publish_volume_floor_op()
+ queries = get_warmable_queries_op(floor_published)
# Aliased so the config path stays ops.warm_queries_op.config — the split op
# takes the same WarmQueriesConfig, so saved Launchpad configs written for
# the pre-sharding single op keep binding unchanged.