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): make precompute stale grace env-tunable, default 4h (#104892)

Lucas Ricoy244c70d066c0
diff --git a/docs/internal/web-analytics-query-serving.md b/docs/internal/web-analytics-query-serving.md
index a06e3bfebfc5..bfa90271b9ca 100644
--- a/docs/internal/web-analytics-query-serving.md
+++ b/docs/internal/web-analytics-query-serving.md
@@ -37,7 +37,7 @@ request
│ range ≤ 90d, filters events-evaluable
│ (restricted teams: single exact $host only)
│ freshness: all day-buckets fresh per TTL band ──▶ serve *_lazy_query (~80–200ms)
- │ expired within 6h SWR grace ──▶ serve stale + enqueue revalidation
+ │ expired within the SWR grace (default 4h) ──▶ serve stale + enqueue revalidation
│ miss (NEVER builds inline — enqueues debounced background warm)
▼
[2] Preaggregated tables (deprecated)
@@ -158,7 +158,7 @@ Full details in [PRECOMPUTATION.md](../../products/web_analytics/PRECOMPUTATION.
| 22–35d | 12–14d |
| 36d+ | 21d |
-- Stale-while-revalidate: 6h grace; user reads inside it get the stale row instantly (tagged `precompute_stale=true`) with a Celery revalidation enqueued (10-min debounce). Background warmers are never served stale — they are the refresh.
+- Stale-while-revalidate: 4h grace by default, set by `WEB_ANALYTICS_PRECOMPUTE_STALE_GRACE_SECONDS` (read per call, so a new env value applies once the process restarts; must stay under the framework's 48h ClickHouse expiry buffer, which the executor enforces). User reads inside the grace get the stale row instantly (tagged `precompute_stale=true`) with a Celery revalidation enqueued (10-min debounce). Background warmers and forced refreshes are never served stale — they are the refresh.
- Session settling: 24h forward pad on event scans, matching the SDK session length cap.
- OOM protection: a team that OOMs during a build gets Redis-pinned for 14 days to 1-day insert windows.
- Max range: 90 days; wider requests are permanently live.
diff --git a/posthog/settings/web.py b/posthog/settings/web.py
index 3758be23cc98..2f5f5e745896 100644
--- a/posthog/settings/web.py
+++ b/posthog/settings/web.py
@@ -1482,6 +1482,16 @@ WEB_ANALYTICS_ACHIEVEMENTS_SWEEP_BATCH_SIZE: int = get_from_env(
"WEB_ANALYTICS_ACHIEVEMENTS_SWEEP_BATCH_SIZE", 100, type_cast=int
)
+# Stale-while-revalidate grace for user-facing web analytics precompute reads:
+# windows that expired within this many seconds are served from their
+# complete-but-stale rows instantly (with a background revalidation enqueued)
+# instead of recomputing inline. Lowering it bounds the staleness a user can
+# see at the cost of more reads falling through to the live query. Must stay
+# well under the precompute framework's 48h ClickHouse expiry buffer.
+WEB_ANALYTICS_PRECOMPUTE_STALE_GRACE_SECONDS: int = get_from_env(
+ "WEB_ANALYTICS_PRECOMPUTE_STALE_GRACE_SECONDS", 4 * 60 * 60, type_cast=int
+)
+
# Cohort the weekly AI path-cleaning-suggestion job runs for. Defaults to the precompute enrollment
# list (the teams "selected to test out precomputed analytics tables") so the two cohorts track each
# other unless explicitly overridden. Comma-separated env-var override, like the lists above.
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 538f8a327739..30cca5eb6c9a 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
@@ -47,7 +47,6 @@ from products.web_analytics.backend.hogql_queries.web_lazy_precompute_common imp
REVALIDATION_START_DELAY_SECONDS,
REVALIDATION_TRIGGER,
SESSION_SETTLING_SECONDS,
- STALE_WHILE_REVALIDATE_SECONDS,
STICKY_WARM_SHAPES_KEY,
TEAM_SHAPE_SET_TTL_SECONDS,
VOLUME_FLOOR_READY_KEY,
@@ -803,14 +802,16 @@ class TestWebEnsurePrecomputed(BaseTest):
def test_stale_while_revalidate_grace_by_trigger(self, _name, tags, mock_ensure):
mock_ensure.return_value = LazyComputationResult(ready=True, job_ids=[])
reset_query_tags()
- if tags is not None:
- with tags_context(**tags):
+ # Sentinel override proves the grace flows from the setting, not a hardcoded value.
+ with override_settings(WEB_ANALYTICS_PRECOMPUTE_STALE_GRACE_SECONDS=1234):
+ if tags is not None:
+ with tags_context(**tags):
+ web_ensure_precomputed(team=self.team, ttl_seconds={"default": 3600}, table=None)
+ else:
web_ensure_precomputed(team=self.team, ttl_seconds={"default": 3600}, table=None)
- else:
- web_ensure_precomputed(team=self.team, ttl_seconds={"default": 3600}, table=None)
grace = mock_ensure.call_args.kwargs["stale_while_revalidate_seconds"]
if tags is None:
- assert grace == STALE_WHILE_REVALIDATE_SECONDS
+ assert grace == 1234
else:
assert grace is None, f"background context {tags} must not be served stale"
@@ -823,15 +824,16 @@ class TestWebEnsurePrecomputed(BaseTest):
("force_async", ExecutionMode.CALCULATE_ASYNC_ALWAYS.value, None),
# A normal (non-forced) read must keep the grace, or every read pays a
# synchronous recompute and the serve-stale optimization is lost.
- ("blocking", ExecutionMode.RECENT_CACHE_CALCULATE_BLOCKING_IF_STALE.value, STALE_WHILE_REVALIDATE_SECONDS),
+ ("blocking", ExecutionMode.RECENT_CACHE_CALCULATE_BLOCKING_IF_STALE.value, 1234),
]
)
@mock.patch(f"{_COMMON}.ensure_precomputed")
def test_forced_refresh_bypasses_stale_grace(self, _name, execution_mode, expected_grace, mock_ensure):
mock_ensure.return_value = LazyComputationResult(ready=True, job_ids=[])
reset_query_tags()
- with tags_context(execution_mode=execution_mode):
- web_ensure_precomputed(team=self.team, ttl_seconds={"default": 3600}, table=None)
+ with override_settings(WEB_ANALYTICS_PRECOMPUTE_STALE_GRACE_SECONDS=1234):
+ with tags_context(execution_mode=execution_mode):
+ web_ensure_precomputed(team=self.team, ttl_seconds={"default": 3600}, table=None)
assert mock_ensure.call_args.kwargs["stale_while_revalidate_seconds"] == expected_grace
@parameterized.expand(
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 1767426de737..d30815e69477 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
@@ -273,14 +273,17 @@ BACKGROUND_WARMING_TRIGGERS = frozenset(
}
)
+
# Stale-while-revalidate window for *user-facing* requests: windows that expired within
# this grace are served from their existing (complete-but-stale) rows instantly instead
# of recomputing inline, and a background revalidation is enqueued. Refresh normally
# arrives within minutes via the revalidation task (plus the hourly eager warmer for
# warmed shapes) — the grace is the ceiling for revalidation failures and warmer
-# outages. Must stay well under the framework's 48h ClickHouse expiry buffer (rows must
-# still exist).
-STALE_WHILE_REVALIDATE_SECONDS = 6 * 60 * 60
+# outages. Env-tunable via WEB_ANALYTICS_PRECOMPUTE_STALE_GRACE_SECONDS (see
+# posthog/settings/web.py for the default and the freshness/hit-rate trade-off).
+def stale_while_revalidate_seconds() -> int:
+ return settings.WEB_ANALYTICS_PRECOMPUTE_STALE_GRACE_SECONDS
+
WEB_ANALYTICS_LAZY_PRECOMPUTE_CHECK_MISS = Counter(
"web_analytics_lazy_precompute_check_miss_total",
@@ -641,7 +644,7 @@ def web_ensure_precomputed(
kwargs["stale_while_revalidate_seconds"] = None
else:
kwargs["stale_while_revalidate_seconds"] = resolve_stale_while_revalidate_seconds(
- STALE_WHILE_REVALIDATE_SECONDS, BACKGROUND_WARMING_TRIGGERS
+ 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