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 no-session-join fast paths for web overview and paths tile (#70746)

Lucas Ricoy49fd24fd1452
diff --git a/posthog/settings/web.py b/posthog/settings/web.py
index e5a142d3205a..456513dd9eed 100644
--- a/posthog/settings/web.py
+++ b/posthog/settings/web.py
@@ -1142,3 +1142,15 @@ 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 web analytics queries (overview, paths tile) skip the events↔sessions join
+# when nothing in the query (property filters, conversion goal, test-account filters,
+# sampling) constrains which sessions qualify. In that shape the join only multiplies
+# cost: the sessions-side subquery is re-executed per shard of the events cluster. Trial
+# rollout is per-team via comma-separated env var; defaults to the Cloud dogfooding team
+# (project 2, same default as the lazy precompute lists) so the fast paths activate there
+# on deploy, and to empty on self-hosted where project id 2 is an arbitrary customer.
+WEB_ANALYTICS_NO_JOIN_TEAM_IDS: list[int] = [
+ int(team_id)
+ for team_id in get_list(get_from_env("WEB_ANALYTICS_NO_JOIN_TEAM_IDS", _LAZY_PRECOMPUTE_DEFAULT_TEAM_IDS))
+]
diff --git a/products/web_analytics/backend/hogql_queries/query_constants/stats_table_queries.py b/products/web_analytics/backend/hogql_queries/query_constants/stats_table_queries.py
index 7961de044ab6..a8d555d92d3e 100644
--- a/products/web_analytics/backend/hogql_queries/query_constants/stats_table_queries.py
+++ b/products/web_analytics/backend/hogql_queries/query_constants/stats_table_queries.py
@@ -181,3 +181,116 @@ FROM events
WHERE and({inside_periods}, {event_where}, {all_properties})
GROUP BY session_id, breakdown_value
"""
+
+# No-join variants of the PAGE-breakdown queries: counts come straight from events
+# (bucketed by event timestamp) and bounce comes straight from the sessions table
+# (bucketed by session start), instead of routing both through the events↔sessions
+# lazy join. The join shape re-executes the sessions subquery on every shard of the
+# events cluster, so for unfiltered queries these variants read ~10× fewer rows.
+NO_JOIN_PATH_BOUNCE_QUERY = """
+SELECT
+ counts.breakdown_value AS "context.columns.breakdown_value",
+ tuple(counts.visitors, counts.previous_visitors) AS "context.columns.visitors",
+ tuple(counts.views, counts.previous_views) AS "context.columns.views",
+ tuple(bounce.bounce_rate, bounce.previous_bounce_rate) AS "context.columns.bounce_rate",
+FROM (
+ SELECT
+ {breakdown_value} AS breakdown_value,
+ uniqIf(events.person_id, {current_timestamp_period}) AS visitors,
+ uniqIf(events.person_id, {previous_timestamp_period}) AS previous_visitors,
+ countIf({current_timestamp_period}) AS views,
+ countIf({previous_timestamp_period}) AS previous_views
+ FROM events
+ WHERE and(
+ {events_session_id_present},
+ or(events.event == '$pageview', events.event == '$screen'),
+ {inside_timestamp_periods},
+ )
+ GROUP BY breakdown_value
+) AS counts
+LEFT JOIN (
+ SELECT
+ {bounce_breakdown_value} AS breakdown_value,
+ avgIf(sessions.$is_bounce, {current_session_period}) AS bounce_rate,
+ avgIf(sessions.$is_bounce, {previous_session_period}) AS previous_bounce_rate
+ FROM sessions
+ WHERE and(
+ {inside_session_periods},
+ or(sessions.$pageview_count > 0, sessions.$screen_count > 0),
+ )
+ GROUP BY breakdown_value
+) AS bounce
+ON counts.breakdown_value = bounce.breakdown_value
+WHERE counts.breakdown_value IS NOT NULL
+"""
+
+NO_JOIN_PATH_BOUNCE_AND_AVG_TIME_QUERY = """
+SELECT
+ counts.breakdown_value AS "context.columns.breakdown_value",
+
+ tuple(counts.visitors, counts.previous_visitors) AS "context.columns.visitors",
+ tuple(counts.views, counts.previous_views) AS "context.columns.views",
+
+ tuple(
+ coalesce(time_on_page.avg_time_on_page, 0),
+ coalesce(time_on_page.previous_avg_time_on_page, 0)
+ ) AS "context.columns.avg_time_on_page",
+
+ tuple(
+ coalesce(bounce.bounce_rate, 0),
+ coalesce(bounce.previous_bounce_rate, 0)
+ ) AS "context.columns.bounce_rate"
+
+FROM (
+ SELECT
+ {breakdown_value} AS breakdown_value,
+ uniqIf(events.person_id, {current_timestamp_period}) AS visitors,
+ uniqIf(events.person_id, {previous_timestamp_period}) AS previous_visitors,
+ countIf({current_timestamp_period}) AS views,
+ countIf({previous_timestamp_period}) AS previous_views
+ FROM events
+ WHERE and(
+ {events_session_id_present},
+ or(events.event == '$pageview', events.event == '$screen'),
+ {inside_timestamp_periods},
+ )
+ GROUP BY breakdown_value
+) AS counts
+
+LEFT JOIN (
+ SELECT
+ {time_on_page_breakdown_value} AS breakdown_value,
+ quantileIf(0.90)(
+ least(toFloat(events.properties.`$prev_pageview_duration`), 86400),
+ {current_timestamp_period}
+ ) AS avg_time_on_page,
+ quantileIf(0.90)(
+ least(toFloat(events.properties.`$prev_pageview_duration`), 86400),
+ {previous_timestamp_period}
+ ) AS previous_avg_time_on_page
+ FROM events
+ WHERE and(
+ or(events.event = '$pageview', events.event = '$pageleave', events.event = '$screen'),
+ {time_on_page_breakdown_value} IS NOT NULL,
+ events.properties.`$prev_pageview_duration` IS NOT NULL,
+ {inside_timestamp_periods},
+ )
+ GROUP BY breakdown_value
+) AS time_on_page
+ON counts.breakdown_value = time_on_page.breakdown_value
+
+LEFT JOIN (
+ SELECT
+ {bounce_breakdown_value} AS breakdown_value,
+ avgIf(sessions.$is_bounce, {current_session_period}) AS bounce_rate,
+ avgIf(sessions.$is_bounce, {previous_session_period}) AS previous_bounce_rate
+ FROM sessions
+ WHERE and(
+ {inside_session_periods},
+ or(sessions.$pageview_count > 0, sessions.$screen_count > 0),
+ )
+ GROUP BY breakdown_value
+) AS bounce
+ON counts.breakdown_value = bounce.breakdown_value
+WHERE counts.breakdown_value IS NOT NULL
+"""
diff --git a/products/web_analytics/backend/hogql_queries/stats_table.py b/products/web_analytics/backend/hogql_queries/stats_table.py
index ec54f664b8ca..40858acd57be 100644
--- a/products/web_analytics/backend/hogql_queries/stats_table.py
+++ b/products/web_analytics/backend/hogql_queries/stats_table.py
@@ -36,6 +36,8 @@ from products.web_analytics.backend.hogql_queries.stats_table_pre_aggregated imp
from products.web_analytics.backend.hogql_queries.stats_table_strategies import (
ChannelTypeStrategy,
FrustrationMetricsStrategy,
+ NoJoinPathBounceAvgTimeStrategy,
+ NoJoinPathBounceStrategy,
PathBounceAvgTimeStrategy,
PathBounceStrategy,
SimpleBreakdownStrategy,
@@ -156,6 +158,11 @@ class WebStatsTableQueryRunner(WebAnalyticsQueryRunner[WebStatsTableQueryRespons
def _strategy_name(self, strategy: StatsTableQueryStrategy) -> str:
if isinstance(strategy, FrustrationMetricsStrategy):
return "stats_table_frustration_metrics"
+ # No-join variants first: they don't subclass the join strategies.
+ if isinstance(strategy, NoJoinPathBounceAvgTimeStrategy):
+ return "stats_table_no_join_path_bounce_and_avg_time"
+ if isinstance(strategy, NoJoinPathBounceStrategy):
+ return "stats_table_no_join_path_bounce"
if isinstance(strategy, PathBounceAvgTimeStrategy):
return "stats_table_path_bounce_and_avg_time"
if isinstance(strategy, PathBounceStrategy):
@@ -181,8 +188,12 @@ class WebStatsTableQueryRunner(WebAnalyticsQueryRunner[WebStatsTableQueryRespons
if self.query.conversionGoal:
return SimpleBreakdownStrategy(self)
if self.query.includeAvgTimeOnPage:
+ if self.should_skip_session_join:
+ return NoJoinPathBounceAvgTimeStrategy(self)
return PathBounceAvgTimeStrategy(self)
if self.query.includeBounceRate:
+ if self.should_skip_session_join:
+ return NoJoinPathBounceStrategy(self)
return PathBounceStrategy(self)
if self.query.breakdownBy == WebStatsBreakdown.INITIAL_PAGE and self.query.includeBounceRate:
@@ -900,6 +911,14 @@ class WebStatsTableQueryRunner(WebAnalyticsQueryRunner[WebStatsTableQueryRespons
return self._prepend_host(ast.Field(chain=["events", "properties", "$host"]), path)
return path
+ def _bounce_entry_pathname_breakdown_sessions(self):
+ """Same as `_bounce_entry_pathname_breakdown`, but with field chains resolving
+ against the sessions table directly (no-join strategies query FROM sessions)."""
+ path = self._apply_path_cleaning(ast.Field(chain=["$entry_pathname"]))
+ if self.query.includeHost:
+ return self._prepend_host(ast.Field(chain=["$entry_hostname"]), path)
+ return path
+
def _bounce_entry_pathname_breakdown(self):
path = self._apply_path_cleaning(ast.Field(chain=["session", "$entry_pathname"]))
if self.query.includeHost:
diff --git a/products/web_analytics/backend/hogql_queries/stats_table_strategies.py b/products/web_analytics/backend/hogql_queries/stats_table_strategies.py
index 21c0fb5d5b0a..4bd39380c403 100644
--- a/products/web_analytics/backend/hogql_queries/stats_table_strategies.py
+++ b/products/web_analytics/backend/hogql_queries/stats_table_strategies.py
@@ -9,9 +9,12 @@ from posthog.hogql.parser import parse_expr, parse_select
from products.web_analytics.backend.hogql_queries.query_constants.stats_table_queries import (
FRUSTRATION_METRICS_INNER_QUERY,
MAIN_INNER_QUERY,
+ NO_JOIN_PATH_BOUNCE_AND_AVG_TIME_QUERY,
+ NO_JOIN_PATH_BOUNCE_QUERY,
PATH_BOUNCE_AND_AVG_TIME_QUERY,
PATH_BOUNCE_QUERY,
)
+from products.web_analytics.backend.hogql_queries.web_analytics_query_runner import WEB_ANALYTICS_NO_JOIN_SERVED
if TYPE_CHECKING:
from products.web_analytics.backend.hogql_queries.stats_table import WebStatsTableQueryRunner
@@ -210,6 +213,62 @@ class PathBounceAvgTimeStrategy(StatsTableQueryStrategy):
return self._finalize_query(query)
+class NoJoinPathBounceStrategy(StatsTableQueryStrategy):
+ """PAGE breakdown with bounce rate, without the events↔sessions join.
+
+ Only selected when the runner's ``should_skip_session_join`` gate holds, so
+ nothing in the query constrains which sessions qualify: counts come straight
+ from events (bucketed by event timestamp instead of session start) and bounce
+ comes straight from the sessions table (bucketed by session start). Semantics
+ shift only at range boundaries; measured drift on team 2 over 30d was ≤0.8%
+ on visitors/views and ≤0.001 on bounce rate.
+ """
+
+ QUERY = NO_JOIN_PATH_BOUNCE_QUERY
+ TIMING_KEY = "stats_table_no_join_path_bounce"
+
+ def build_query(self) -> ast.SelectQuery:
+ WEB_ANALYTICS_NO_JOIN_SERVED.labels(family="stats_table_paths").inc()
+ with self.runner.timings.measure(self.TIMING_KEY):
+ query = parse_select(
+ self.QUERY,
+ timings=self.runner.timings,
+ placeholders=self._placeholders(),
+ )
+ assert isinstance(query, ast.SelectQuery)
+ return self._finalize_query(query)
+
+ def _placeholders(self) -> dict[str, ast.Expr]:
+ return {
+ "breakdown_value": self.runner._counts_breakdown_value(),
+ "events_session_id_present": self.runner.events_session_id_present,
+ "bounce_breakdown_value": self.runner._bounce_entry_pathname_breakdown_sessions(),
+ "current_timestamp_period": self.runner._current_period_expression("timestamp"),
+ "previous_timestamp_period": self.runner._previous_period_expression("timestamp"),
+ "inside_timestamp_periods": self.runner._periods_expression("timestamp"),
+ "current_session_period": self.runner._current_period_expression("$start_timestamp"),
+ "previous_session_period": self.runner._previous_period_expression("$start_timestamp"),
+ "inside_session_periods": self.runner._periods_expression("$start_timestamp"),
+ }
+
+
+class NoJoinPathBounceAvgTimeStrategy(NoJoinPathBounceStrategy):
+ """PAGE breakdown with average time on page and bounce rate, join-free.
+
+ The time-on-page subquery was already events-only in the join shape; it is
+ carried over unchanged.
+ """
+
+ QUERY = NO_JOIN_PATH_BOUNCE_AND_AVG_TIME_QUERY
+ TIMING_KEY = "stats_table_no_join_path_bounce_and_avg_time"
+
+ def _placeholders(self) -> dict[str, ast.Expr]:
+ return {
+ **super()._placeholders(),
+ "time_on_page_breakdown_value": self.runner._scroll_prev_pathname_breakdown(),
+ }
+
+
class FrustrationMetricsStrategy(StatsTableQueryStrategy):
"""FRUSTRATION_METRICS breakdown: rage clicks, dead clicks, errors."""
diff --git a/products/web_analytics/backend/hogql_queries/test/test_web_overview.py b/products/web_analytics/backend/hogql_queries/test/test_web_overview.py
index 51d7e5922ce8..33595c7265db 100644
--- a/products/web_analytics/backend/hogql_queries/test/test_web_overview.py
+++ b/products/web_analytics/backend/hogql_queries/test/test_web_overview.py
@@ -12,6 +12,8 @@ from posthog.test.base import (
)
from unittest.mock import MagicMock, patch
+from django.test import override_settings
+
from parameterized import parameterized
from posthog.schema import (
@@ -20,10 +22,13 @@ from posthog.schema import (
CompareFilter,
CustomEventConversionGoal,
DateRange,
+ EventPropertyFilter,
HogQLQueryModifiers,
IntervalType,
+ PropertyOperator,
SessionPropertyFilter,
SessionTableVersion,
+ WebAnalyticsSampling,
WebOverviewQuery,
WebOverviewQueryResponse,
)
@@ -1036,3 +1041,92 @@ class TestWebOverviewQueryRunner(ClickhouseTestMixin, APIBaseTest):
builder = WebOverviewPreAggregatedQueryBuilder(runner)
self.assertFalse(builder.can_use_preaggregated_tables())
+
+
+class TestWebOverviewNoJoinFastPath(ClickhouseTestMixin, APIBaseTest):
+ QUERY_TIMESTAMP = "2025-01-29"
+
+ def _create_pageviews(self):
+ s1, s2, s3 = str(uuid7("2025-01-10")), str(uuid7("2025-01-11")), str(uuid7("2025-01-12"))
+ for distinct_id, session_id, timestamps in [
+ ("user_a", s1, ["2025-01-10T10:00:00Z", "2025-01-10T10:05:00Z", "2025-01-10T10:20:00Z"]),
+ ("user_a", s2, ["2025-01-11T09:00:00Z"]),
+ ("user_b", s3, ["2025-01-12T12:00:00Z", "2025-01-12T12:00:30Z"]),
+ ]:
+ with freeze_time(timestamps[0]):
+ _create_person(team_id=self.team.pk, distinct_ids=[distinct_id])
+ for ts in timestamps:
+ _create_event(
+ team=self.team,
+ event="$pageview",
+ distinct_id=distinct_id,
+ timestamp=ts,
+ properties={"$session_id": session_id, "$current_url": "https://example.com/"},
+ )
+ # Sessionless (server-side) pageview: the join path drops it via the session
+ # start HAVING, so the no-join events side must exclude it explicitly.
+ _create_event(
+ team=self.team,
+ event="$pageview",
+ distinct_id="user_b",
+ timestamp="2025-01-12T13:00:00Z",
+ properties={"$current_url": "https://example.com/"},
+ )
+
+ def _make_runner(self, **query_kwargs) -> WebOverviewQueryRunner:
+ query = WebOverviewQuery(
+ dateRange=DateRange(date_from="2025-01-08", date_to="2025-01-15"),
+ properties=query_kwargs.pop("properties", []),
+ **query_kwargs,
+ )
+ return WebOverviewQueryRunner(team=self.team, query=query)
+
+ @parameterized.expand([(True,), (False,)])
+ def test_no_join_results_match_join_path(self, compare: bool):
+ self._create_pageviews()
+
+ kwargs = {"compareFilter": CompareFilter(compare=True)} if compare else {}
+ with freeze_time(self.QUERY_TIMESTAMP):
+ with override_settings(WEB_ANALYTICS_NO_JOIN_TEAM_IDS=[self.team.pk]):
+ fast_runner = self._make_runner(**kwargs)
+ assert fast_runner.should_skip_session_join
+ fast_results = fast_runner.calculate().results
+
+ join_runner = self._make_runner(**kwargs)
+ assert not join_runner.should_skip_session_join
+ join_results = join_runner.calculate().results
+
+ assert [item.key for item in fast_results] == [item.key for item in join_results]
+ for fast, join in zip(fast_results, join_results):
+ assert fast.value == join.value, f"{fast.key}: {fast.value} != {join.value}"
+ assert fast.previous == join.previous, f"{fast.key} previous: {fast.previous} != {join.previous}"
+
+ @parameterized.expand(
+ [
+ ("clean_query", {}, True),
+ (
+ "event_property_filter",
+ {"properties": [EventPropertyFilter(key="$pathname", operator=PropertyOperator.EXACT, value="/")]},
+ False,
+ ),
+ ("conversion_goal", {"conversionGoal": CustomEventConversionGoal(customEventName="purchase")}, False),
+ ("sampling_enabled", {"sampling": WebAnalyticsSampling(enabled=True)}, False),
+ ("sampling_factor", {"samplingFactor": 0.1}, False),
+ ]
+ )
+ def test_no_join_eligibility(self, _name: str, query_kwargs: dict, expected: bool):
+ with override_settings(WEB_ANALYTICS_NO_JOIN_TEAM_IDS=[self.team.pk]):
+ runner = self._make_runner(**query_kwargs)
+ assert runner.should_skip_session_join == expected
+
+ def test_no_join_ineligible_when_team_not_allowlisted_or_test_filters_apply(self):
+ runner = self._make_runner()
+ assert not runner.should_skip_session_join
+
+ self.team.test_account_filters = [
+ {"key": "email", "value": "@posthog.com", "operator": "not_icontains", "type": "person"}
+ ]
+ self.team.save()
+ with override_settings(WEB_ANALYTICS_NO_JOIN_TEAM_IDS=[self.team.pk]):
+ runner = self._make_runner(filterTestAccounts=True)
+ assert not runner.should_skip_session_join
diff --git a/products/web_analytics/backend/hogql_queries/test/test_web_stats_table.py b/products/web_analytics/backend/hogql_queries/test/test_web_stats_table.py
index c364d9997ef5..7b36a18371a2 100644
--- a/products/web_analytics/backend/hogql_queries/test/test_web_stats_table.py
+++ b/products/web_analytics/backend/hogql_queries/test/test_web_stats_table.py
@@ -14,6 +14,8 @@ from posthog.test.base import (
)
from unittest.mock import patch
+from django.test import override_settings
+
import numpy as np
from parameterized import parameterized
from pydantic.dataclasses import dataclass
@@ -2509,3 +2511,91 @@ class TestWebStatsTableQueryRunner(ClickhouseTestMixin, APIBaseTest, FloatAwareT
assert results_dict["example.com/features"][0] == 2
assert results_dict["subdomain.example.com/features"][0] == 1
+
+
+class TestWebStatsTableNoJoinFastPath(ClickhouseTestMixin, APIBaseTest):
+ QUERY_TIMESTAMP = "2025-01-29"
+
+ def _create_pageviews(self):
+ s1, s2, s3 = str(uuid7("2025-01-10")), str(uuid7("2025-01-11")), str(uuid7("2025-01-12"))
+ for distinct_id, session_id, path_timestamps in [
+ ("user_a", s1, [("/", "2025-01-10T10:00:00Z"), ("/pricing", "2025-01-10T10:05:00Z")]),
+ ("user_a", s2, [("/pricing", "2025-01-11T09:00:00Z")]),
+ ("user_b", s3, [("/", "2025-01-12T12:00:00Z"), ("/", "2025-01-12T12:00:30Z")]),
+ ]:
+ with freeze_time(path_timestamps[0][1]):
+ _create_person(team_id=self.team.pk, distinct_ids=[distinct_id])
+ for pathname, ts in path_timestamps:
+ _create_event(
+ team=self.team,
+ event="$pageview",
+ distinct_id=distinct_id,
+ timestamp=ts,
+ properties={
+ "$session_id": session_id,
+ "$pathname": pathname,
+ "$current_url": f"https://example.com{pathname}",
+ },
+ )
+ # A server-side pageview with no session: the join path drops it (NULL session
+ # start), so the no-join counts side must exclude it too.
+ _create_event(
+ team=self.team,
+ event="$pageview",
+ distinct_id="user_b",
+ timestamp="2025-01-12T13:00:00Z",
+ properties={"$pathname": "/", "$current_url": "https://example.com/"},
+ )
+ flush_persons_and_events()
+
+ def _make_runner(self, **query_kwargs) -> WebStatsTableQueryRunner:
+ query = WebStatsTableQuery(
+ dateRange=DateRange(date_from="2025-01-08", date_to="2025-01-15"),
+ breakdownBy=query_kwargs.pop("breakdownBy", WebStatsBreakdown.PAGE),
+ includeBounceRate=query_kwargs.pop("includeBounceRate", True),
+ properties=query_kwargs.pop("properties", []),
+ **query_kwargs,
+ )
+ return WebStatsTableQueryRunner(team=self.team, query=query)
+
+ @parameterized.expand([(False,), (True,)])
+ def test_no_join_paths_results_match_join_path(self, include_avg_time: bool):
+ self._create_pageviews()
+
+ with freeze_time(self.QUERY_TIMESTAMP):
+ with override_settings(WEB_ANALYTICS_NO_JOIN_TEAM_IDS=[self.team.pk]):
+ fast_runner = self._make_runner(includeAvgTimeOnPage=include_avg_time)
+ assert fast_runner.query_strategy().startswith("stats_table_no_join_path_bounce")
+ fast_results = fast_runner.calculate().results
+
+ join_runner = self._make_runner(includeAvgTimeOnPage=include_avg_time)
+ assert not join_runner.query_strategy().startswith("stats_table_no_join")
+ join_results = join_runner.calculate().results
+
+ assert sorted(r[0] for r in fast_results) == sorted(r[0] for r in join_results)
+ fast_by_path = {r[0]: r[1:] for r in fast_results}
+ join_by_path = {r[0]: r[1:] for r in join_results}
+ for path, join_row in join_by_path.items():
+ assert fast_by_path[path] == join_row, f"{path}: {fast_by_path[path]} != {join_row}"
+
+ @parameterized.expand(
+ [
+ ("clean_page_query", {}, True),
+ (
+ "event_property_filter",
+ {"properties": [EventPropertyFilter(key="$host", operator=PropertyOperator.EXACT, value="a.com")]},
+ False,
+ ),
+ ("conversion_goal", {"conversionGoal": CustomEventConversionGoal(customEventName="purchase")}, False),
+ ("non_page_breakdown", {"breakdownBy": WebStatsBreakdown.INITIAL_CHANNEL_TYPE}, False),
+ ("no_bounce_rate", {"includeBounceRate": False}, False),
+ ]
+ )
+ def test_no_join_paths_strategy_selection(self, _name: str, query_kwargs: dict, expect_no_join: bool):
+ with override_settings(WEB_ANALYTICS_NO_JOIN_TEAM_IDS=[self.team.pk]):
+ runner = self._make_runner(**query_kwargs)
+ assert runner.query_strategy().startswith("stats_table_no_join") == expect_no_join
+
+ def test_no_join_paths_requires_team_allowlist(self):
+ runner = self._make_runner()
+ assert not runner.query_strategy().startswith("stats_table_no_join")
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 96a45ccab4f3..93d422b50aff 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
@@ -10,6 +10,7 @@ from django.conf import settings
from django.core.cache import cache
import structlog
+from prometheus_client import Counter
from structlog.contextvars import bound_contextvars
from posthog.schema import (
@@ -57,6 +58,14 @@ from products.web_analytics.backend.hogql_queries.web_lazy_precompute_common imp
logger = structlog.get_logger(__name__)
+# Tracks how often a web analytics query is served without the events↔sessions join,
+# so the trial rollout can be monitored per query family against the join path.
+WEB_ANALYTICS_NO_JOIN_SERVED = Counter(
+ "web_analytics_no_join_served_total",
+ "Web analytics queries served by a no-session-join fast path.",
+ ["family"],
+)
+
WebQueryNode = Union[
WebOverviewQuery,
WebStatsTableQuery,
@@ -198,6 +207,39 @@ class WebAnalyticsQueryRunner(AnalyticsQueryRunner[WAR], ABC):
sampling_enabled=sampling.enabled if sampling else False,
)
+ @cached_property
+ def should_skip_session_join(self) -> bool:
+ """Whether this query can be served by independent events/sessions scans.
+
+ The events↔sessions join exists so filters on events can constrain which
+ sessions contribute to session-level metrics (duration, bounce rate). When
+ nothing in the query constrains session membership, both sides can be
+ aggregated independently — the join only multiplies cost, because the
+ sessions-side subquery is re-executed on every shard of the events cluster
+ (10× read amplification on US prod; measured 5.5-14.7× latency and 8-25×
+ memory vs the two-scan variants).
+
+ Runners that support a no-join query shape check this gate; anything not
+ covered falls through to the join path untouched.
+ """
+ if self.team.pk not in settings.WEB_ANALYTICS_NO_JOIN_TEAM_IDS:
+ return False
+ if getattr(self.query, "conversionGoal", None):
+ return False
+ if getattr(self.query, "properties", None):
+ return False
+ # Test-account filters are event/person property filters, so they constrain
+ # session membership the same way user filters do.
+ if self._test_account_filters:
+ return False
+ sampling_factor = getattr(self.query, "samplingFactor", None)
+ if sampling_factor and sampling_factor != 1:
+ return False
+ sampling = getattr(self.query, "sampling", None)
+ if sampling and (sampling.enabled or sampling.forceSamplingRate):
+ return False
+ return True
+
@cached_property
def filters_eligibility_hash(self) -> Optional[str]:
"""Stable hash of the user-facing query inputs that would fragment a
@@ -655,6 +697,19 @@ WHERE
else:
return parse_expr("events.$session_id")
+ @cached_property
+ def events_session_id_present(self) -> ast.Expr:
+ """True when the event carries a usable session id.
+
+ A missing `$session_id` materializes as an empty string, not NULL, so an
+ `IS NOT NULL` check alone lets sessionless (server-side) events through.
+ The join path excludes them implicitly (NULL session start fails the
+ period HAVING); the no-join query shapes need this explicit guard.
+ """
+ if self.query.modifiers and self.query.modifiers.sessionsV2JoinMode == "uuid":
+ return parse_expr("events.$session_id_uuid IS NOT NULL")
+ return parse_expr("events.$session_id IS NOT NULL AND events.$session_id != ''")
+
def _sample_rate_from_count(count: int) -> SamplingRate:
# Change the sample rate so that the query will sample about 100_000 to 1_000_000 events, but use defined steps of
diff --git a/products/web_analytics/backend/hogql_queries/web_overview.py b/products/web_analytics/backend/hogql_queries/web_overview.py
index db87b14d4169..9b55e065b8db 100644
--- a/products/web_analytics/backend/hogql_queries/web_overview.py
+++ b/products/web_analytics/backend/hogql_queries/web_overview.py
@@ -12,13 +12,16 @@ from posthog.schema import (
)
from posthog.hogql import ast
-from posthog.hogql.parser import parse_select
+from posthog.hogql.parser import parse_expr, parse_select
from posthog.hogql.property import property_to_expr
from posthog.hogql.query import execute_hogql_query
from posthog.models.filters.mixins.utils import cached_property
-from products.web_analytics.backend.hogql_queries.web_analytics_query_runner import WebAnalyticsQueryRunner
+from products.web_analytics.backend.hogql_queries.web_analytics_query_runner import (
+ WEB_ANALYTICS_NO_JOIN_SERVED,
+ WebAnalyticsQueryRunner,
+)
from products.web_analytics.backend.hogql_queries.web_overview_lazy_precompute import (
can_use_lazy_precompute,
execute_lazy_precomputed_read,
@@ -43,8 +46,129 @@ class WebOverviewQueryRunner(WebAnalyticsQueryRunner[WebOverviewQueryResponse]):
self.preaggregated_query_builder = WebOverviewPreAggregatedQueryBuilder(self)
def to_query(self) -> ast.SelectQuery:
+ if self.should_skip_session_join:
+ WEB_ANALYTICS_NO_JOIN_SERVED.labels(family="overview").inc()
+ return self.no_join_select
return self.outer_select
+ @cached_property
+ def no_join_select(self) -> ast.SelectQuery:
+ """Overview metrics from two independent scans, no events↔sessions join.
+
+ Column order must match ``outer_select`` — ``_calculate`` indexes rows
+ positionally. Semantics differ from the join path only at range boundaries:
+ sessions are bucketed by their own start timestamp here, while the join path
+ keeps sessions that had a matching event in range AND started in range; the
+ drift measured on team 2 over 30d is ≤0.15% on sessions and ~0 on
+ bounce/duration.
+ """
+ has_comparison = bool(self.query_compare_to_date_range)
+
+ events_agg = parse_select(
+ """
+SELECT
+ uniqIf(events.person_id, {current_users}) AS unique_users,
+ {previous_users} AS previous_unique_users,
+ countIf({current_views}) AS total_filtered_pageview_count,
+ {previous_views} AS previous_total_filtered_pageview_count
+FROM events
+WHERE and(
+ {events_session_id_present},
+ {event_type_expr},
+ {inside_timestamp_period},
+)
+ """,
+ placeholders={
+ "events_session_id_present": self.events_session_id_present,
+ "event_type_expr": self.event_type_expr,
+ "inside_timestamp_period": self._periods_expression("timestamp"),
+ "current_users": self._current_period_expression("timestamp"),
+ "previous_users": (
+ parse_expr(
+ "uniqIf(events.person_id, {previous_period})",
+ placeholders={"previous_period": self._previous_period_expression("timestamp")},
+ )
+ if has_comparison
+ else ast.Constant(value=None)
+ ),
+ "current_views": self._current_period_expression("timestamp"),
+ "previous_views": (
+ parse_expr(
+ "countIf({previous_period})",
+ placeholders={"previous_period": self._previous_period_expression("timestamp")},
+ )
+ if has_comparison
+ else ast.Constant(value=None)
+ ),
+ },
+ )
+
+ sessions_agg = parse_select(
+ """
+SELECT
+ uniqIf(sessions.session_id, {current_period}) AS unique_sessions,
+ {previous_sessions} AS previous_unique_sessions,
+ avgIf(sessions.$session_duration, {current_period}) AS avg_duration_s,
+ {previous_duration} AS previous_avg_duration_s,
+ avgIf(sessions.$is_bounce, {current_period}) AS bounce_rate,
+ {previous_bounce} AS previous_bounce_rate
+FROM sessions
+WHERE and(
+ {inside_start_timestamp_period},
+ or(sessions.$pageview_count > 0, sessions.$screen_count > 0),
+)
+ """,
+ placeholders={
+ "inside_start_timestamp_period": self._periods_expression("$start_timestamp"),
+ "current_period": self._current_period_expression("$start_timestamp"),
+ "previous_sessions": (
+ parse_expr(
+ "uniqIf(sessions.session_id, {previous_period})",
+ placeholders={"previous_period": self._previous_period_expression("$start_timestamp")},
+ )
+ if has_comparison
+ else ast.Constant(value=None)
+ ),
+ "previous_duration": (
+ parse_expr(
+ "avgIf(sessions.$session_duration, {previous_period})",
+ placeholders={"previous_period": self._previous_period_expression("$start_timestamp")},
+ )
+ if has_comparison
+ else ast.Constant(value=None)
+ ),
+ "previous_bounce": (
+ parse_expr(
+ "avgIf(sessions.$is_bounce, {previous_period})",
+ placeholders={"previous_period": self._previous_period_expression("$start_timestamp")},
+ )
+ if has_comparison
+ else ast.Constant(value=None)
+ ),
+ },
+ )
+
+ combined = parse_select(
+ """
+SELECT
+ events_agg.unique_users AS unique_users,
+ events_agg.previous_unique_users AS previous_unique_users,
+ events_agg.total_filtered_pageview_count AS total_filtered_pageview_count,
+ events_agg.previous_total_filtered_pageview_count AS previous_total_filtered_pageview_count,
+ sessions_agg.unique_sessions AS unique_sessions,
+ sessions_agg.previous_unique_sessions AS previous_unique_sessions,
+ sessions_agg.avg_duration_s AS avg_duration_s,
+ sessions_agg.previous_avg_duration_s AS previous_avg_duration_s,
+ sessions_agg.bounce_rate AS bounce_rate,
+ sessions_agg.previous_bounce_rate AS previous_bounce_rate
+FROM {events_agg} AS events_agg
+CROSS JOIN {sessions_agg} AS sessions_agg
+ """,
+ placeholders={"events_agg": events_agg, "sessions_agg": sessions_agg},
+ )
+ assert isinstance(combined, ast.SelectQuery)
+ return combined
+
def get_pre_aggregated_response(self):
should_use_preaggregated = (
self.modifiers