: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
chore(web-analytics): document lazy precompute framework features (#118301)
Lucas Ricoy0d3a58226e03
diff --git a/docs/internal/web-analytics-query-serving.md b/docs/internal/web-analytics-query-serving.mdindex cf8ec7a74209..1fa7186b44f7 100644--- a/docs/internal/web-analytics-query-serving.md+++ b/docs/internal/web-analytics-query-serving.md@@ -34,7 +34,7 @@ request│ only an explicit useWebAnalyticsPrecompute: false rejects│ shape: family dispatch (see per-runner tables), no conversion goal,│ no sampling, integer timezone, `sessionsV2JoinMode` ≠ uuid,- │ range ≤ 90d, filters events-evaluable+ │ range ≤ MAX_PRECOMPUTE_DAYS, filters events-evaluable│ (restricted teams: single exact $host only)│ freshness: all day-buckets fresh per TTL band ──▶ serve *_lazy_query (~80–200ms)│ expired within the SWR grace (default 4h) ──▶ serve stale + enqueue revalidation@@ -161,12 +161,13 @@ Full details in [PRECOMPUTATION.md](../../products/web_analytics/PRECOMPUTATION.| 8–14d | 7d || 15–21d | 10d || 22–35d | 12–14d |-| 36d+ | 21d |+| 36d+ | 90d |- 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.+- Max range: `MAX_PRECOMPUTE_DAYS`; wider requests are permanently live.+- Framework rationale (freshness, stale grace, settling, OOM pin): see [design decisions](../../products/analytics_platform/backend/lazy_computation/README.md#design-decisions).## Session-grain precompute schema@@ -225,7 +226,7 @@ Suffix conventions: `*_lazy_query` = bucket read (served from precompute), `*_laFind the request in query_log and check `query_type`.A `*_lazy_query` taking seconds is a bucket-read problem (rare).-A fast-path or full-join tag on an enrolled team means the lazy gate rejected the query (filters, avg-time-on-page, >90d range, opt-out) or the buckets weren't fresh — in which case a background warm is already in flight and the next identical request should hit.+A fast-path or full-join tag on an enrolled team means the lazy gate rejected the query (filters, avg-time-on-page, range over `MAX_PRECOMPUTE_DAYS`, opt-out) or the buckets weren't fresh — in which case a background warm is already in flight and the next identical request should hit.Conversion goal property filters accept event, person, session and cohort filters. Unsupported filter types fail query validation. `includeTrafficMetrics` also retains session counts for page breakdowns with bounce rate or average time on page, including the join-free strategies.diff --git a/products/analytics_platform/backend/lazy_computation/README.md b/products/analytics_platform/backend/lazy_computation/README.mdindex 31b1a193d6c6..96a43ce187d7 100644--- a/products/analytics_platform/backend/lazy_computation/README.md+++ b/products/analytics_platform/backend/lazy_computation/README.md@@ -129,6 +129,31 @@ The `ttl_seconds` parameter accepts either an `int` (uniform TTL) or a `dict` maRules are matched most-specific first (shortest period wins). On the **read path**, existing jobs that are too stale for the requested TTL are skipped and recomputed. On the **write path**, each job is created with the TTL appropriate for its date range — ranges with different TTLs are never merged into a single job.+## Design decisions++Why the executor works the way it does, and what went wrong without each piece.+The code holds the current values.++### Freshness and expiry++- **Freshness is per reader, expiry is per creator (#47942).** A job's `expires_at` comes from the TTL of the caller that built it, but each reader judges freshness against its own schedule. The fresh lookup drops jobs past `expires_at`; a reader with `stale_while_revalidate_seconds` set still serves jobs inside that grace. Callers with different freshness needs share one job, and a stricter reader builds a replacement instead of forcing its TTL on everyone.+- **No force-rebuild parameter.** A builder that wants a window rebuilt early gives it a shorter TTL, which makes the existing job stale for that builder only. The shorter TTL also stamps a shorter `expires_at` on the new job, so readers rely on stale-while-revalidate to cover the gap until the next build.+- **Stale-while-revalidate (#70080).** User reads that would block on a rebuild get recently expired, complete rows at once, and the caller rebuilds in the background. The grace stays under the ClickHouse expiry buffer, because the rows are deleted after it.+- **Refreshers never get the grace (#70563).** A refresher served its own stale rows stores them as a fresh result and never recomputes, so nothing refreshes again. The rule lives in `stale_policy.py` so every product uses the same one.++### TTL schedule options++- **Settling period (#69554).** Web analytics sessions keep changing for 24 hours after a window ends. Jobs built before then froze in-motion bounce and duration values for a multi-day band TTL, mostly on the UTC edge windows of non-UTC teams.+- **Empty-result cap (#77835).** A data warehouse source that had not synced yet produced zero-row jobs, which served $0 cost days for the full band TTL. Empty jobs now expire sooner, but only while a late sync could still fill the window, so old history is not rescanned forever.+- **Default-band jitter (#96576).** A backfill built every frozen chunk on the same day, so all chunks expired together and the next read rebuilt the whole history. A stable per-window offset spreads those expiries.+- **Window-start invalidation (#105883).** A warmer that builds a window before it starts left an early snapshot that hid the data arriving once the window began. Such a snapshot is rejected at the window start, even within the stale grace.+- **Job width cap.** One GROUP BY over a high-cardinality team grows with the window, and a memory bump does not keep up with the largest teams. The same data fits over a narrower window, so callers cap job width and pin a team to 1-day jobs after an OOM (#64394).++### Inserts++- **Data-horizon clamp (#97251).** An experiment build "as of" a past moment inserted half a day but recorded the whole day as covered, so the missing hours were never rebuilt. Callers whose INSERT stops at `end` opt in, and the partial day becomes its own job.+- **Skipping replica quorum (#103220).** One down or stale-registered aux replica made every quorum INSERT fail, so precompute stopped region-wide. Background builders read their rows minutes later, so they skip quorum with `read_after_write=False`.+## Concurrency and race conditionsThe executor handles concurrent queries that need the same lazy-computed data.@@ -278,5 +303,5 @@ The `lazy_computation.executed` log line carries the same `outcome`, `cache_stat## TODOs- While we are waiting, we block an entire django thread despite not doing any useful work. We should make it easier for people to use e.g. celery with this, this would involve using async queries though.-- The stale enum value isn't used for anything, we just mark stale jobs as errored+- Crashed PENDING jobs are marked FAILED, not STALE. Only the staff invalidate endpoint (`precompute_debug`) sets STALE.- Add posthog logging for state transitionsdiff --git a/products/web_analytics/PRECOMPUTATION.md b/products/web_analytics/PRECOMPUTATION.mdindex 074cd75659c5..698de95f0dc6 100644--- a/products/web_analytics/PRECOMPUTATION.md+++ b/products/web_analytics/PRECOMPUTATION.md@@ -36,6 +36,10 @@ Both are `ReplacingMergeTree` (version column `computed_at`), sharded by `sipHasFor each team on a region-scoped allowlist it drives `ensure_precomputed` over a rolling 90-day window, chunked to one UTC day per INSERT.Every window is a `PreaggregationJob` (Postgres) with a `job_id` and a TTL by age (today 1h, ≤2 days 1 day, older 90 days); re-runs recompute only expired windows.The allowlist defaults per Cloud region (`DEFAULT_ROLLOUT_TEAM_IDS_BY_REGION`) and is overridable via `WEB_DIMENSIONAL_PRECOMPUTE_TEAM_IDS`; an empty list disables the job.+ The inserts carry the legacy job's memory and time ceilings, because one UTC day of a very large team outgrew the interactive defaults (#117339).+ They also narrow HogQL's 3-day session lookback to 25 hours, after the wider read ran the shared sessions node out of memory (#117872).+ The job has no stale grace or forced refresh of its own: today's window rebuilds only when a run finds its job expired.+ So the today TTL must be clearly shorter than the cron period, or a run skips a still-fresh window that then expires before the next run. Today the two are equal.- **Coverage**: the same stats-breakdown and overview shapes v2 serves — about 45% of user-facing web-analytics reads by shape (stats breakdowns on the stored dimensions, plus overview).Not goals, vitals, frustration metrics, external clicks, or the other engines (Trends / Retention / HogQL).Its differentiator over lazy: arbitrary multi-dimension filters within the fixed set resolve from one table, with no per-filter-combination warming.@@ -115,7 +119,7 @@ The 24 h pad matches the JS SDK's hard `SESSION_LENGTH_LIMIT` and covers effecti- `query.sampling.enabled` is True- `query.modifiers.sessionsV2JoinMode == "uuid"` (column type mismatch — temporary; should be re-enabled by re-typing `uniq_sessions_state` to `(uniq, UUID)`)- The team has any property-level access controls (`team_has_property_access_rules`) — precompute results are built userless and shared by a user-independent cache key, so they can't honor per-user property restrictions; the query falls through to the live path, which enforces them per requesting user-- Date range exceeds `MAX_PRECOMPUTE_DAYS` (90)+- Date range exceeds `MAX_PRECOMPUTE_DAYS`- Either date_from or date_to is NoneAny event/person filter shape is accepted: the `query.properties` list is translated via `property_to_expr`, and each distinct filter set becomes its own cache key (namespace). Session and cohort filters are refused (they fall through to the live path) — the userless precompute INSERT would apply them, but the live runners handle those types differently per family (web vitals drops them), so precomputing them would serve a different population than the live fallback. Filters the INSERT can't express fail the job and fall back to the live query automatically. Because any filter combination mints a new namespace, `web_ensure_precomputed` enforces a per-team distinct-shape ceiling (`WEB_ANALYTICS_PRECOMPUTE_MAX_SHAPES_PER_TEAM`, default 1000): once a team holds that many live shapes, a build for a _new_ shape drops to a check-only pass and serves live instead, while shapes the team already holds keep serving and refreshing. It is a coarse backstop, not a quota; 0 disables it.@@ -134,9 +138,16 @@ Different freshness per how recent the data is:| 8–14d | 7 days | Distinct per-week TTLs force weekly job boundaries, keeping INSERT scans bounded || 15–21d | 10 days | — || 22–35d | 12–14 d | — |-| 36d+ | 21 days | Bounded in practice by hash rotations (AST-affecting deploys rebuild everything) |+| 36d+ | 90 days | A year-long shape must not rescan a year of events each time the band expires |Stored via the `LAZY_TTL_SECONDS` dict in `web_lazy_precompute_common.py` (see the comment there for the full freshness-vs-job-sizing reasoning); consumed by `lazy_computation_executor.parse_ttl_schedule` against the team's timezone.+For the framework mechanisms behind it, see [design decisions](../analytics_platform/backend/lazy_computation/README.md#design-decisions).++A user forced refresh treats today's bucket as expired for that read only (#86699): the 4-hour today band otherwise left hourly graphs hours behind after a Reload.+The forced read goes live, but the stored bucket is not rebuilt early: the revalidation it enqueues runs as a background build with the normal TTL, finds the job still fresh, and reuses it.+Later non-forced reads keep serving that bucket until its normal TTL lapses.+Background builds never get this rule, because the same schedule stamps `expires_at` and the revalidation task runs in the forced mode, so it would store buckets that expire after 1 second.+A forced refresh also never gets the stale grace, or repeated Reloads kept serving the stale row they were meant to clear (#73693).### Read path@@ -273,7 +284,7 @@ The runner re-partitions the resulting `(band, path, value)` tuples into the `go### Eligibility gate-`can_use_lazy_precompute` in `products/web_analytics/backend/hogql_queries/web_vitals_paths_lazy_precompute.py` delegates to the shared gate with `require_integer_timezone=False` (see "Bucketing and timezones" above). The shared gate rejects: org feature flag off, explicit per-query opt-out (`useWebAnalyticsPrecompute=False` — an untouched toggle defaults on), conversion goal, sampling enabled, `sessionsV2JoinMode=uuid`, missing date range, and date range over 90 days. Any event/person property-filter shape is accepted (each distinct set becomes its own cache key, bounded by the per-team shape ceiling — see the web overview eligibility gate above); session/cohort filters fall through to live.+`can_use_lazy_precompute` in `products/web_analytics/backend/hogql_queries/web_vitals_paths_lazy_precompute.py` delegates to the shared gate with `require_integer_timezone=False` (see "Bucketing and timezones" above). The shared gate rejects: org feature flag off, explicit per-query opt-out (`useWebAnalyticsPrecompute=False` — an untouched toggle defaults on), conversion goal, sampling enabled, `sessionsV2JoinMode=uuid`, missing date range, and date range over `MAX_PRECOMPUTE_DAYS`. Any event/person property-filter shape is accepted (each distinct set becomes its own cache key, bounded by the per-team shape ceiling — see the web overview eligibility gate above); session/cohort filters fall through to live.### Observability