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.

fix(analytics-platform): sync distributed inserts in lazy computation (#62854)

Juraj Majerik37adf63a3a82
diff --git a/products/analytics_platform/backend/lazy_computation/CONSISTENCY.md b/products/analytics_platform/backend/lazy_computation/CONSISTENCY.md
index 80a00b6fc420..17089e89cc66 100644
--- a/products/analytics_platform/backend/lazy_computation/CONSISTENCY.md
+++ b/products/analytics_platform/backend/lazy_computation/CONSISTENCY.md
@@ -27,7 +27,14 @@ Controls whether INSERTs into a Distributed table are synchronous or asynchronou
Previously named `insert_distributed_sync`.
-**Already enabled globally**: PostHog's ClickHouse config sets `insert_distributed_sync=1` in `docker/clickhouse/users.xml`. This means layer 1 (distributed table routing) is already solved for all queries. The `posthog/dags/sessions.py` DAG explicitly overrides this to `0` for large INSERTs to avoid OOM, confirming the global default is `1`.
+**Set per-query by the executor** (`_get_insert_settings`), under the legacy `insert_distributed_sync` name for ClickHouse-version compatibility. Do not rely on server profiles for this guarantee:
+
+- Dev's `docker/clickhouse/users.xml` sets `insert_distributed_sync=1` on the `default` profile, so dev and CI always behave synchronously — which also makes the async failure mode invisible in every test environment.
+- Production profiles are not the dev config. At least one production cluster explicitly sets `distributed_foreground_insert=0` (async) on the `default` profile used for writes, while carrying the legacy `insert_distributed_sync=1` only on the `readonly` profile — where it is inert, since readonly users cannot INSERT.
+- An earlier revision of this document concluded the setting was "already enabled globally", citing the dev config and the `posthog/dags/sessions.py` override comment. Both observe intent, not production behavior, and the conclusion was wrong: with async forwarding, INSERTs returned after merely enqueueing to the initiator's distribution queue, jobs were marked READY immediately, and rows became visible to readers only over the following minutes — producing badly undercounted funnel results right after every window recompute.
+- To verify actual behavior, check `Settings['insert_distributed_sync']` on real INSERT rows in `system.query_log`, or per-host profile contents in `system.settings_profile_elements`. Unit tests on `_get_insert_settings` pin our side; only production telemetry pins the environment's.
+
+Large synchronous distributed inserts buffer per-shard splits on the initiator — the reason `posthog/dags/sessions.py` sets `0` for its bulk INSERTs. Lazy computation inserts are bounded by daily windows; if a very large recompute ever hits memory limits, chunk the windows instead of reverting to async.
Sources:
@@ -240,7 +247,7 @@ Write to `sharded_preaggregation_results` directly on a specific node, run the S
### Approach E: Deterministic replica routing (Sentry's approach)
```text
-INSERT: (distributed_foreground_insert=1 is already global)
+INSERT: distributed_foreground_insert=1 (set per-query by the executor — see above)
SELECT: optimize_skip_unused_shards=1, load_balancing='in_order'
```
@@ -248,7 +255,7 @@ Sentry [rejected `select_sequential_consistency`](https://blog.sentry.io/how-to-
**Pros**: zero ZK overhead on reads, no per-table serialization, per-query settings only
**Cons**: not formally guaranteed — if the preferred replica goes down between INSERT and SELECT, the fallback replica may be stale (see quorum hardening below). Concentrates lazy computation read/write load on one replica per shard — with 3 replicas, other queries using `random` load balancing distribute evenly across all 3 (including replica 1), so replica 1 gets a disproportionate share of total load. Acceptable when lazy computation is a small fraction of total query volume, but worth monitoring as it grows.
-**INSERT latency**: none extra (already global)
+**INSERT latency**: the synchronous forward to the target shard (previously assumed free via a global server setting)
**SELECT latency**: none extra (may be slightly faster with shard pruning)
**Optional hardening: add quorum writes.** Adding `insert_quorum='auto'` ensures the INSERT is acknowledged by a majority of replicas before returning. This covers the failover edge case: if replica 1 goes down between INSERT and SELECT, `in_order` falls back to replica 2, which has the data thanks to quorum. Importantly, since we're using `load_balancing='in_order'` instead of `select_sequential_consistency`, we do NOT need `insert_quorum_parallel=0` — parallel quorum (the default) works fine, so there's no per-table lock and no throughput limit. The cost is +20-100ms INSERT latency for the quorum wait.
@@ -276,7 +283,7 @@ The choice of sharding key depends on which consistency approach is used:
## 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.
-- **`SYSTEM FLUSH DISTRIBUTED`**: forces async distributed sends to complete, but `distributed_foreground_insert=1` already solves this and is already enabled globally.
+- **`SYSTEM FLUSH DISTRIBUTED`**: forces async distributed sends to complete, but the executor sets `distributed_foreground_insert=1` per-query, which solves this directly. (Also, with pooled connections there is no guarantee the FLUSH would run on the node holding the queue.)
- **`distributed_group_by_no_merge`**: performance optimization that skips coordinator-level re-aggregation for single-shard queries — not a consistency mechanism.
- **Kafka coordination layer**: Sentry also built a `SynchronizedConsumer` that uses Kafka commit log topics as a write confirmation barrier. Not applicable to the lazy computation system's `INSERT...SELECT` workload.
- **ClickHouse transactions**: experimental `BEGIN TRANSACTION` / `COMMIT` support exists but is limited to single-table operations on ReplicatedMergeTree, not production-ready, and doesn't directly address read-after-write consistency.
@@ -296,7 +303,7 @@ Not applicable to PostHog (fully self-hosted), but for reference:
| Setting | Scope | ZK ops added | Latency | Contention | Impact on other queries |
| --------------------------------- | ----------------------------- | ------------ | ---------------- | ------------------------ | ----------------------------------------------------- |
-| `distributed_foreground_insert=1` | Global (already set) | None | +1-10ms | None | None |
+| `distributed_foreground_insert=1` | Per-query (set by executor) | None | +1-10ms | None | None |
| `insert_quorum='auto'` | Per-query | 2-3 writes | +20-100ms | None | None |
| `insert_quorum_parallel=0` | Per-query (lock is per-table) | None extra | None extra | ~100ms window per INSERT | None (lock only affects quorum INSERTs to same table) |
| `select_sequential_consistency=1` | Per-query | 1 read | +1-10ms | None | None |
diff --git a/products/analytics_platform/backend/lazy_computation/lazy_computation_executor.py b/products/analytics_platform/backend/lazy_computation/lazy_computation_executor.py
index e0ad044f1251..7108cb431c8b 100644
--- a/products/analytics_platform/backend/lazy_computation/lazy_computation_executor.py
+++ b/products/analytics_platform/backend/lazy_computation/lazy_computation_executor.py
@@ -139,6 +139,12 @@ def _get_insert_settings(team_id: int) -> dict:
{
"max_execution_time": HOGQL_INCREASED_MAX_EXECUTION_TIME,
"insert_quorum": PREAGGREGATION_INSERT_QUORUM,
+ # The executor marks a job READY as soon as the INSERT returns, so rows must be on the
+ # shards by then — not sitting in the initiator's async distribution queue, where they
+ # become visible to readers only minutes later. Production profiles default this to 0
+ # (async); never rely on server config for this guarantee. Uses the legacy name of
+ # `distributed_foreground_insert` (renamed in ClickHouse 23.x) for version compatibility.
+ "insert_distributed_sync": 1,
**HogQLQuerySettings(load_balancing="in_order").model_dump(exclude_none=True),
}
)
diff --git a/products/analytics_platform/backend/lazy_computation/tests/test_lazy_computation_executor.py b/products/analytics_platform/backend/lazy_computation/tests/test_lazy_computation_executor.py
index c01b97ece685..1ed530139db8 100644
--- a/products/analytics_platform/backend/lazy_computation/tests/test_lazy_computation_executor.py
+++ b/products/analytics_platform/backend/lazy_computation/tests/test_lazy_computation_executor.py
@@ -20,6 +20,7 @@ from posthog.hogql.query import execute_hogql_query
from posthog.clickhouse.client import sync_execute
from posthog.clickhouse.preaggregation.sql import DISTRIBUTED_PREAGGREGATION_RESULTS_TABLE
from posthog.hogql_queries.insights.trends.trends_query_runner import TrendsQueryRunner
+from posthog.settings import HOGQL_INCREASED_MAX_EXECUTION_TIME
from products.analytics_platform.backend.lazy_computation.computation_notifications import (
job_channel,
@@ -31,12 +32,14 @@ from products.analytics_platform.backend.lazy_computation.lazy_computation_execu
DEFAULT_TTL_SCHEDULE,
DEFAULT_WAIT_TIMEOUT_SECONDS,
NON_RETRYABLE_CLICKHOUSE_ERROR_CODES,
+ PREAGGREGATION_INSERT_QUORUM,
LazyComputationExecutor,
LazyComputationResult,
LazyComputationTable,
QueryInfo,
TtlSchedule,
_build_manual_insert_sql,
+ _get_insert_settings,
build_lazy_computation_insert_sql,
compute_query_hash,
create_lazy_computation_job,
@@ -45,6 +48,7 @@ from products.analytics_platform.backend.lazy_computation.lazy_computation_execu
find_missing_contiguous_windows,
is_non_retryable_error,
parse_ttl_schedule,
+ run_lazy_computation_insert,
split_ranges_by_ttl,
)
from products.analytics_platform.backend.models import PreaggregationJob
@@ -2672,3 +2676,76 @@ class TestIsNonRetryableError(BaseTest):
def test_generic_exception_is_retryable(self):
error = Exception("Something went wrong")
assert is_non_retryable_error(error) is False
+
+
+class TestInsertSettings(BaseTest):
+ def test_insert_settings_guarantee_read_your_writes(self):
+ settings = _get_insert_settings(self.team.pk)
+
+ # The executor marks jobs READY the moment the INSERT returns, which is only sound if
+ # the distributed write is synchronous. Production profiles default to async, so this
+ # must be set per-query — a missing value here means readers race the distribution queue.
+ assert settings["insert_distributed_sync"] == 1
+ assert settings["insert_quorum"] == PREAGGREGATION_INSERT_QUORUM
+ assert settings["load_balancing"] == "in_order"
+ assert settings["max_execution_time"] == HOGQL_INCREASED_MAX_EXECUTION_TIME
+ assert "readonly" not in settings
+
+
+class TestInsertSettingsAppliedToInserts(BaseTest):
+ INSERT_QUERY = """
+ SELECT
+ toStartOfDay(timestamp) as time_window_start,
+ [] as breakdown_value,
+ uniqExactState(person_id) as uniq_exact_state
+ FROM events
+ WHERE event = '$pageview'
+ AND timestamp >= {time_window_min}
+ AND timestamp < {time_window_max}
+ GROUP BY time_window_start
+ """
+
+ def test_manual_insert_path_passes_insert_settings_to_clickhouse(self):
+ with patch(
+ "products.analytics_platform.backend.lazy_computation.lazy_computation_executor.sync_execute"
+ ) as mock_execute:
+ result = ensure_precomputed(
+ team=self.team,
+ insert_query=self.INSERT_QUERY,
+ time_range_start=datetime(2024, 1, 1, tzinfo=UTC),
+ time_range_end=datetime(2024, 1, 2, tzinfo=UTC),
+ )
+
+ assert result.ready is True
+ # Bind the assertion to the INSERT specifically, so the test doesn't break (or silently
+ # check the wrong call) if the executor flow ever issues other queries around the insert.
+ insert_calls = [c for c in mock_execute.call_args_list if c.args[0].lstrip().startswith("INSERT")]
+ assert len(insert_calls) == 1 # one missing range -> one INSERT
+ assert insert_calls[0].kwargs["settings"] == _get_insert_settings(self.team.pk)
+
+ def test_ast_insert_path_passes_insert_settings_to_clickhouse(self):
+ job = PreaggregationJob.objects.create(
+ team=self.team,
+ query_hash="test_hash",
+ time_range_start=datetime(2024, 1, 1, tzinfo=UTC),
+ time_range_end=datetime(2024, 1, 2, tzinfo=UTC),
+ status=PreaggregationJob.Status.PENDING,
+ expires_at=django_timezone.now() + timedelta(days=7),
+ )
+ query = parse_select(
+ self.INSERT_QUERY,
+ placeholders={
+ "time_window_min": ast.Constant(value=datetime(2024, 1, 1, tzinfo=UTC)),
+ "time_window_max": ast.Constant(value=datetime(2024, 1, 2, tzinfo=UTC)),
+ },
+ )
+ assert isinstance(query, ast.SelectQuery)
+ query_info = QueryInfo(query=query, table=LazyComputationTable.PREAGGREGATION_RESULTS)
+
+ with patch(
+ "products.analytics_platform.backend.lazy_computation.lazy_computation_executor.sync_execute"
+ ) as mock_execute:
+ run_lazy_computation_insert(self.team, job, query_info)
+
+ assert mock_execute.call_count == 1
+ assert mock_execute.call_args.kwargs["settings"] == _get_insert_settings(self.team.pk)
diff --git a/products/web_analytics/backend/hogql_queries/web_overview_lazy_precompute.py b/products/web_analytics/backend/hogql_queries/web_overview_lazy_precompute.py
index d73a5dd072bb..ac3a4a38d9e8 100644
--- a/products/web_analytics/backend/hogql_queries/web_overview_lazy_precompute.py
+++ b/products/web_analytics/backend/hogql_queries/web_overview_lazy_precompute.py
@@ -148,8 +148,9 @@ WHERE team_id = %(team_id)s AND job_id IN %(job_ids)s
_READ_SETTINGS = {
# Approach E from `products/analytics_platform/backend/lazy_computation/CONSISTENCY.md`:
# both INSERT (via `_get_insert_settings`) and SELECT use `in_order` so they
- # deterministically prefer the same replica. Combined with the global
- # `distributed_foreground_insert=1`, the SELECT sees data the INSERT just wrote.
+ # deterministically prefer the same replica. Combined with the synchronous distributed
+ # insert (`insert_distributed_sync=1`, also set in `_get_insert_settings` — production
+ # profiles default to async), the SELECT sees data the INSERT just wrote.
#
# `select_sequential_consistency=1` was tried here and is documented broken in
# CONSISTENCY.md when combined with `insert_quorum_parallel=1` (the default).