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): add colocated paths precompute table variant (#64948)

Lucas Ricoy43776bdcb817
diff --git a/posthog/clickhouse/migrations/0278_web_stats_paths_preaggregated_pathkey.py b/posthog/clickhouse/migrations/0278_web_stats_paths_preaggregated_pathkey.py
new file mode 100644
index 000000000000..151ddc85c2e1
--- /dev/null
+++ b/posthog/clickhouse/migrations/0278_web_stats_paths_preaggregated_pathkey.py
@@ -0,0 +1,20 @@
+from posthog.clickhouse.client.connection import NodeRole
+from posthog.clickhouse.client.migration_tools import run_sql_with_exceptions
+from posthog.clickhouse.preaggregation.web_stats_paths_preaggregated_sql import (
+ DISTRIBUTED_WEB_STATS_PATHS_PREAGGREGATED_PATHKEY_TABLE_SQL,
+ SHARDED_WEB_STATS_PATHS_PREAGGREGATED_PATHKEY_TABLE_SQL,
+)
+
+operations = [
+ # Breakdown-key colocation variant of web_stats_paths_preaggregated; same
+ # AUX-sharded + DATA-distributed topology as migration 0260.
+ run_sql_with_exceptions(
+ SHARDED_WEB_STATS_PATHS_PREAGGREGATED_PATHKEY_TABLE_SQL(),
+ node_roles=[NodeRole.AUX],
+ sharded=True,
+ ),
+ run_sql_with_exceptions(
+ DISTRIBUTED_WEB_STATS_PATHS_PREAGGREGATED_PATHKEY_TABLE_SQL(),
+ node_roles=[NodeRole.DATA],
+ ),
+]
diff --git a/posthog/clickhouse/migrations/max_migration.txt b/posthog/clickhouse/migrations/max_migration.txt
index 128b2343c903..b790c6ac2ced 100644
--- a/posthog/clickhouse/migrations/max_migration.txt
+++ b/posthog/clickhouse/migrations/max_migration.txt
@@ -1 +1 @@
-0277_marketing_conversions_preaggregated
+0278_web_stats_paths_preaggregated_pathkey
diff --git a/posthog/clickhouse/preaggregation/web_stats_paths_preaggregated_sql.py b/posthog/clickhouse/preaggregation/web_stats_paths_preaggregated_sql.py
index 1c3664c47103..199398edb62a 100644
--- a/posthog/clickhouse/preaggregation/web_stats_paths_preaggregated_sql.py
+++ b/posthog/clickhouse/preaggregation/web_stats_paths_preaggregated_sql.py
@@ -109,3 +109,60 @@ def DROP_SHARDED_WEB_STATS_PATHS_PREAGGREGATED_TABLE_SQL():
def TRUNCATE_WEB_STATS_PATHS_PREAGGREGATED_TABLE_SQL():
return f"TRUNCATE TABLE IF EXISTS {SHARDED_WEB_STATS_PATHS_PREAGGREGATED_TABLE()}"
+
+
+# Breakdown-key colocation variant of the table above — an A/B experiment for the
+# PATHS tile. Same columns; the breakdown (path) leads both the sort key and the
+# shard key so high-cardinality reads stay shard-local. Rationale and the read-side
+# requirements live in lazy_computation/CONSISTENCY.md and the PR description.
+TABLE_PATHKEY_BASE_NAME = "web_stats_paths_preaggregated_pathkey"
+
+
+def DISTRIBUTED_WEB_STATS_PATHS_PREAGGREGATED_PATHKEY_TABLE():
+ return TABLE_PATHKEY_BASE_NAME
+
+
+def SHARDED_WEB_STATS_PATHS_PREAGGREGATED_PATHKEY_TABLE():
+ return f"sharded_{TABLE_PATHKEY_BASE_NAME}"
+
+
+def SHARDED_WEB_STATS_PATHS_PREAGGREGATED_PATHKEY_TABLE_ENGINE():
+ return ReplacingMergeTree(TABLE_PATHKEY_BASE_NAME, replication_scheme=ReplicationScheme.SHARDED, ver="computed_at")
+
+
+def SHARDED_WEB_STATS_PATHS_PREAGGREGATED_PATHKEY_TABLE_SQL():
+ return (
+ WEB_STATS_PATHS_PREAGGREGATED_TABLE_BASE_SQL
+ + """
+PARTITION BY toYYYYMMDD(expires_at)
+ORDER BY (team_id, time_window_start, breakdown_value, job_id)
+TTL toDateTime(expires_at)
+SETTINGS index_granularity=8192, ttl_only_drop_parts = 1
+"""
+ ).format(
+ table_name=SHARDED_WEB_STATS_PATHS_PREAGGREGATED_PATHKEY_TABLE(),
+ engine=SHARDED_WEB_STATS_PATHS_PREAGGREGATED_PATHKEY_TABLE_ENGINE(),
+ )
+
+
+def DISTRIBUTED_WEB_STATS_PATHS_PREAGGREGATED_PATHKEY_TABLE_SQL():
+ return WEB_STATS_PATHS_PREAGGREGATED_TABLE_BASE_SQL.format(
+ table_name=DISTRIBUTED_WEB_STATS_PATHS_PREAGGREGATED_PATHKEY_TABLE(),
+ engine=Distributed(
+ data_table=SHARDED_WEB_STATS_PATHS_PREAGGREGATED_PATHKEY_TABLE(),
+ sharding_key="sipHash64(breakdown_value)",
+ cluster=settings.CLICKHOUSE_AUX_CLUSTER,
+ ),
+ )
+
+
+def DROP_WEB_STATS_PATHS_PREAGGREGATED_PATHKEY_TABLE_SQL():
+ return f"DROP TABLE IF EXISTS {DISTRIBUTED_WEB_STATS_PATHS_PREAGGREGATED_PATHKEY_TABLE()}"
+
+
+def DROP_SHARDED_WEB_STATS_PATHS_PREAGGREGATED_PATHKEY_TABLE_SQL():
+ return f"DROP TABLE IF EXISTS {SHARDED_WEB_STATS_PATHS_PREAGGREGATED_PATHKEY_TABLE()} SYNC"
+
+
+def TRUNCATE_WEB_STATS_PATHS_PREAGGREGATED_PATHKEY_TABLE_SQL():
+ return f"TRUNCATE TABLE IF EXISTS {SHARDED_WEB_STATS_PATHS_PREAGGREGATED_PATHKEY_TABLE()}"
diff --git a/posthog/settings/web.py b/posthog/settings/web.py
index 214dc22043ee..fe7b39f33ef6 100644
--- a/posthog/settings/web.py
+++ b/posthog/settings/web.py
@@ -989,3 +989,16 @@ WEB_ANALYTICS_LAZY_PRECOMPUTE_UNRESTRICTED_TEAM_IDS: list[int] = [
get_from_env("WEB_ANALYTICS_LAZY_PRECOMPUTE_UNRESTRICTED_TEAM_IDS", _LAZY_PRECOMPUTE_DEFAULT_TEAM_IDS)
)
]
+
+# Teams whose PATHS precompute reads also dual-write into the colocated
+# `web_stats_paths_preaggregated_pathkey` table so its read layout can be
+# A/B-compared (PR #64948). Deliberately narrow — only the named teams pay the
+# extra mirror write — and defaults to the Cloud dogfooding team (project 2)
+# only, same as the precompute lists above. Temporary; removed once the
+# comparison concludes.
+WEB_STATS_PATHS_PREAGG_MIRROR_PATHKEY_TEAM_IDS: list[int] = [
+ int(team_id)
+ for team_id in get_list(
+ get_from_env("WEB_STATS_PATHS_PREAGG_MIRROR_PATHKEY_TEAM_IDS", _LAZY_PRECOMPUTE_DEFAULT_TEAM_IDS)
+ )
+]
diff --git a/products/analytics_platform/backend/lazy_computation/CONSISTENCY.md b/products/analytics_platform/backend/lazy_computation/CONSISTENCY.md
index 7d54da8808b4..4301eeba2357 100644
--- a/products/analytics_platform/backend/lazy_computation/CONSISTENCY.md
+++ b/products/analytics_platform/backend/lazy_computation/CONSISTENCY.md
@@ -280,6 +280,21 @@ The choice of sharding key depends on which consistency approach is used:
**Current recommendation**: keep `sipHash64(job_id)` for now. It's even, simple, and works with all approaches. Revisit if a single job's data becomes large enough that cross-shard parallelism matters.
+### Breakdown-key colocation (trialed for the PATHS tile)
+
+The "revisit" trigger above has been hit. On teams with very high breakdown cardinality (hundreds of thousands of distinct paths), the PATHS tile reads `web_stats_paths_preaggregated` in several seconds, while the equivalent batch pre-agg (`web_pre_aggregated_stats`, which keys `pathname` high in its `ORDER BY`) serves the same row count in ~100ms. With `sipHash64(job_id)` sharding, a single large job's path rows land on one shard and aggregate serially.
+
+**Technique — breakdown-key colocation:** shard by `sipHash64(breakdown_value)` and lead the `ORDER BY` with `(team_id, time_window_start, breakdown_value, …)`. Two effects:
+
+- **Shard-local aggregation.** Each breakdown value lives entirely on one shard, so each shard computes complete per-path aggregates independently and the coordinator only merges the top-N candidates — no per-key cross-shard merge. This is ClickHouse's `optimize_distributed_group_by_sharding_key` pattern.
+- **Read locality.** Leading the sort key with `time_window_start` then `breakdown_value` gives the time-range read a primary-index range-skip and co-locates the `GROUP BY breakdown_value` rows (mirrors v2's layout).
+
+Both effects are query-side — the table layout only makes them _possible_. The read wiring must: (1) filter by `time_window_start` range, **not** `job_id IN (...)`, so the primary index range-skips — `job_id` is last in the sort key now, so keep `job_id IN (...)` only as a freshness post-filter; and (2) `SET optimize_distributed_group_by_sharding_key = 1`, which is what actually enables the shard-local short-circuit (it is not activated by the DDL).
+
+We're A/B-ing this in a parallel table — `web_stats_paths_preaggregated_pathkey` (migration 0278) — against the original: same columns, only the `ORDER BY` and sharding key differ. Goal is to confirm it lands near v2 before committing. Mind the empty-`breakdown_value` hotspotting caveat above (rare for `$pathname`, but worth a guard if this generalizes to other breakdowns).
+
+**Write side (wired).** The PATHS lazy read dual-writes into the pathkey table after each precompute read: `mirror_jobs_to_pathkey` copies the just-computed rows for the read's `job_id`s from the original table into the pathkey table (a row-level copy of already-aggregated states — no event re-scan), and the distributed INSERT reshards them by `sipHash64(breakdown_value)`. It is best-effort (never fails the read), runs at cache-miss frequency, is idempotent (ReplacingMergeTree), and is gated by a team-id allowlist (`WEB_STATS_PATHS_PREAGG_MIRROR_PATHKEY_TEAM_IDS`, default: Cloud project 2 only) so only the teams being compared pay the extra write. The **read** side stays on the original table — the pathkey table is queried ad-hoc to compare latency, applying the two read requirements above by hand.
+
## Other approaches investigated but not applicable
- **`max_replica_delay_for_distributed_queries`**: rejects replicas lagging by N seconds, but the granularity is seconds — too coarse for sub-second read-after-write where replication lag is measured in milliseconds.
diff --git a/products/web_analytics/backend/hogql_queries/test/test_web_stats_paths_lazy_precompute.py b/products/web_analytics/backend/hogql_queries/test/test_web_stats_paths_lazy_precompute.py
index ab89ea6796da..e8ab697c7dcb 100644
--- a/products/web_analytics/backend/hogql_queries/test/test_web_stats_paths_lazy_precompute.py
+++ b/products/web_analytics/backend/hogql_queries/test/test_web_stats_paths_lazy_precompute.py
@@ -606,3 +606,64 @@ class TestWebStatsPathsLazyPrecompute(ClickhouseTestMixin, APIBaseTest):
with override_settings(WEB_ANALYTICS_LAZY_PRECOMPUTE_UNRESTRICTED_TEAM_IDS=[self.team.pk]):
self._run(self._build_query(opt_in_precompute=False))
assert PreaggregationJob.objects.filter(team_id=self.team.pk).count() == 0
+
+ @parameterized.expand([("allowlisted", True), ("not_allowlisted", False)])
+ @freeze_time("2024-01-15T12:00:00Z")
+ def test_pathkey_mirror_runs_only_for_allowlisted_teams(self, _name: str, allowlisted: bool) -> None:
+ import products.web_analytics.backend.hogql_queries.web_stats_paths_lazy_precompute as mod
+
+ job_id = uuid.uuid4()
+ mirror_team_ids = [self.team.pk] if allowlisted else []
+ with (
+ self._enable_lazy(),
+ override_settings(WEB_STATS_PATHS_PREAGG_MIRROR_PATHKEY_TEAM_IDS=mirror_team_ids),
+ patch.object(
+ mod,
+ "ensure_web_stats_paths_precomputed",
+ return_value=LazyComputationResult(ready=True, job_ids=[job_id]),
+ ),
+ patch.object(mod, "execute_read_query", return_value=[]),
+ patch.object(mod, "mirror_jobs_to_pathkey") as mock_mirror,
+ ):
+ runner = WebStatsTableQueryRunner(team=self.team, query=self._build_query())
+ mod.execute_lazy_precomputed_read(runner, sort_column="visitors", sort_direction="DESC", limit=11, offset=0)
+
+ if allowlisted:
+ mock_mirror.assert_called_once_with(team_id=self.team.pk, job_ids=[str(job_id)])
+ else:
+ mock_mirror.assert_not_called()
+
+ def test_mirror_jobs_to_pathkey_copies_rows_between_tables(self) -> None:
+ from products.web_analytics.backend.hogql_queries.web_stats_paths_lazy_precompute import mirror_jobs_to_pathkey
+
+ job_id = uuid.uuid4()
+ with patch(
+ "products.web_analytics.backend.hogql_queries.web_stats_paths_lazy_precompute.sync_execute"
+ ) as mock_exec:
+ mirror_jobs_to_pathkey(team_id=self.team.pk, job_ids=[str(job_id)])
+
+ mock_exec.assert_called_once()
+ sql, params = mock_exec.call_args.args
+ assert "INSERT INTO web_stats_paths_preaggregated_pathkey" in sql
+ assert "FROM web_stats_paths_preaggregated" in sql
+ assert params["team_id"] == self.team.pk
+ assert params["job_ids"] == [job_id] # coerced from str back to UUID
+
+ def test_mirror_jobs_to_pathkey_swallows_errors(self) -> None:
+ from products.web_analytics.backend.hogql_queries.web_stats_paths_lazy_precompute import mirror_jobs_to_pathkey
+
+ with patch(
+ "products.web_analytics.backend.hogql_queries.web_stats_paths_lazy_precompute.sync_execute",
+ side_effect=ValueError("boom"),
+ ):
+ # Must not raise — a failed mirror cannot affect the primary read.
+ mirror_jobs_to_pathkey(team_id=self.team.pk, job_ids=[str(uuid.uuid4())])
+
+ def test_mirror_jobs_to_pathkey_noop_on_empty(self) -> None:
+ from products.web_analytics.backend.hogql_queries.web_stats_paths_lazy_precompute import mirror_jobs_to_pathkey
+
+ with patch(
+ "products.web_analytics.backend.hogql_queries.web_stats_paths_lazy_precompute.sync_execute"
+ ) as mock_exec:
+ mirror_jobs_to_pathkey(team_id=self.team.pk, job_ids=[])
+ mock_exec.assert_not_called()
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 9da65765eb4d..703650fe14d4 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
@@ -11,9 +11,12 @@ attributing bounce to sessions that entered on the path.
"""
import time
+import uuid
from datetime import UTC, datetime
from typing import TYPE_CHECKING, Optional
+from django.conf import settings
+
import structlog
from prometheus_client import Counter, Histogram
@@ -23,7 +26,13 @@ from posthog.hogql import ast
from posthog.hogql.parser import parse_select
from posthog.hogql.query import execute_hogql_query
-from posthog.clickhouse.query_tagging import Feature, Product, tag_queries
+from posthog.clickhouse.client import sync_execute
+from posthog.clickhouse.preaggregation.web_stats_paths_preaggregated_sql import (
+ DISTRIBUTED_WEB_STATS_PATHS_PREAGGREGATED_PATHKEY_TABLE,
+ DISTRIBUTED_WEB_STATS_PATHS_PREAGGREGATED_TABLE,
+)
+from posthog.clickhouse.query_tagging import Feature, Product, tag_queries, tags_context
+from posthog.settings import DEBUG, TEST
from products.analytics_platform.backend.lazy_computation.lazy_computation_executor import (
LazyComputationResult,
@@ -87,6 +96,15 @@ WEB_STATS_PATHS_LAZY_ROWS = Histogram(
buckets=(1, 10, 100, 500, 1000, 2500, 5000, 7500, 10000, float("inf")),
)
+# Best-effort mirror of the precomputed rows into the colocated `_pathkey` table
+# variant (PR #64948) so its read layout can be A/B-compared. Failures here never
+# affect the primary read, so we only count them.
+WEB_STATS_PATHS_PATHKEY_MIRROR_FAILED = Counter(
+ "web_stats_paths_pathkey_mirror_failed_total",
+ "Best-effort copies into web_stats_paths_preaggregated_pathkey that failed, by error class.",
+ ["error_type"],
+)
+
class WrongBreakdown(LazyPrecomputeIneligible):
pass
@@ -303,6 +321,59 @@ def ensure_web_stats_paths_precomputed(
)
+# Columns shared by both tables, in declaration order. The pathkey table mirrors
+# the original schema exactly, so the copy is a straight column-for-column INSERT.
+_PATHKEY_MIRROR_COLUMNS = (
+ "team_id, job_id, time_window_start, breakdown_value, "
+ "uniq_users_state, sum_pageviews_state, avg_bounce_state, computed_at, expires_at"
+)
+
+# Mirror the primary insert's durability settings (quorum + synchronous
+# distribution), disabled on single-node TEST/DEBUG like the executor does.
+_PATHKEY_MIRROR_SETTINGS: dict = {
+ "insert_distributed_sync": 1,
+ "insert_quorum": 0 if TEST or DEBUG else "auto",
+ "load_balancing": "in_order",
+}
+
+
+def mirror_jobs_to_pathkey(*, team_id: int, job_ids: list[str]) -> None:
+ """Best-effort copy of precomputed PATHS rows for `job_ids` into the colocated
+ pathkey table (PR #64948). Idempotent (ReplacingMergeTree) and never raises —
+ a failed mirror must not affect the primary read."""
+ if not job_ids:
+ return
+
+ primary = DISTRIBUTED_WEB_STATS_PATHS_PREAGGREGATED_TABLE()
+ pathkey = DISTRIBUTED_WEB_STATS_PATHS_PREAGGREGATED_PATHKEY_TABLE()
+ sql = f"""
+ INSERT INTO {pathkey} ({_PATHKEY_MIRROR_COLUMNS})
+ SELECT {_PATHKEY_MIRROR_COLUMNS}
+ FROM {primary}
+ WHERE team_id = %(team_id)s AND job_id IN %(job_ids)s
+ """
+ try:
+ with tags_context(
+ team_id=team_id,
+ product=Product.WEB_ANALYTICS,
+ feature=Feature.QUERY,
+ query_type="web_stats_paths_pathkey_mirror_insert",
+ ):
+ sync_execute(
+ sql,
+ {"team_id": team_id, "job_ids": [uuid.UUID(jid) for jid in job_ids]},
+ settings=_PATHKEY_MIRROR_SETTINGS,
+ )
+ except Exception as exc:
+ WEB_STATS_PATHS_PATHKEY_MIRROR_FAILED.labels(error_type=_bucket_error_label(exc)).inc()
+ logger.warning(
+ "web_stats_paths_pathkey_mirror_failed",
+ team_id=team_id,
+ job_count=len(job_ids),
+ error_type=type(exc).__name__,
+ )
+
+
# Returns one row per breakdown_value with (current, previous) period pairs
# plus a fill-fraction column for the bar visualisation:
# breakdown_value, visitors, prev_visitors, views, prev_views, bounce_rate,
@@ -622,6 +693,14 @@ def execute_lazy_precomputed_read(
offset=offset,
)
read_duration_ms = int((time.perf_counter() - read_started) * 1000)
+
+ # Best-effort dual-write: mirror these jobs' rows into the colocated pathkey
+ # table for A/B read comparison. Narrowly scoped to the allowlisted teams
+ # (default: Cloud project 2) so only they pay the extra mirror write. After
+ # the read so it never adds latency to the user's response; swallows errors.
+ if team_id in settings.WEB_STATS_PATHS_PREAGG_MIRROR_PATHKEY_TEAM_IDS:
+ mirror_jobs_to_pathkey(team_id=team_id, job_ids=job_ids)
+
total_duration_ms = int((time.perf_counter() - overall_started) * 1000)
rows_returned = len(rows) if rows else 0