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(clickhouse): buffer query_log_archive writes on OPS cluster (#64550)

Paweł Szczurff3054176103
diff --git a/posthog/clickhouse/migrations/0276_query_log_archive_buffer.py b/posthog/clickhouse/migrations/0276_query_log_archive_buffer.py
new file mode 100644
index 000000000000..937a2efc9e74
--- /dev/null
+++ b/posthog/clickhouse/migrations/0276_query_log_archive_buffer.py
@@ -0,0 +1,45 @@
+from posthog import settings
+from posthog.clickhouse.client.connection import NodeRole
+from posthog.clickhouse.client.migration_tools import run_sql_with_exceptions
+from posthog.clickhouse.query_log_archive import (
+ QUERY_LOG_ARCHIVE_BUFFER_OPS_TABLE_SQL,
+ WRITABLE_QUERY_LOG_ARCHIVE_OPS_TABLE_SQL,
+ WRITABLE_QUERY_LOG_ARCHIVE_TABLE,
+)
+
+# Insert a Buffer table (query_log_archive_buffer) in front of sharded_query_log_archive on the
+# OPS cluster and route writable_query_log_archive through it, so the many small per-cluster MV
+# inserts are batched in memory before flushing to the ReplicatedMergeTree, reducing part churn.
+#
+# In the cloud, writable_query_log_archive and ops_query_log_archive_mv are config-managed by
+# posthog-cloud-infra (ansible managed_schemas), which repoints the writable at the buffer. This
+# migration must NOT touch those objects in the cloud or it would fight that config. So in the
+# cloud it only creates the buffer (which infra does not manage); the writable repoint happens
+# locally only, where posthog-cloud-infra does not run, to keep dev parity.
+
+ALL_ROLES = [
+ NodeRole.DATA,
+ NodeRole.ENDPOINTS,
+ NodeRole.AUX,
+ NodeRole.AI_EVENTS,
+ NodeRole.SESSIONS,
+ NodeRole.OPS,
+]
+
+_IS_CLOUD = settings.CLOUD_DEPLOYMENT in ("US", "EU", "DEV")
+
+operations = [
+ # Buffer table on OPS, flushing to sharded_query_log_archive. Owned by this migration
+ # (not posthog-cloud-infra), so created everywhere — cloud and local.
+ run_sql_with_exceptions(QUERY_LOG_ARCHIVE_BUFFER_OPS_TABLE_SQL(), node_roles=[NodeRole.OPS]),
+ # Repoint the writable Distributed at the buffer — local only. In the cloud this is done by
+ # posthog-cloud-infra. Drop + recreate is safe (Distributed holds no data, not replicated).
+ *(
+ []
+ if _IS_CLOUD
+ else [
+ run_sql_with_exceptions(f"DROP TABLE IF EXISTS {WRITABLE_QUERY_LOG_ARCHIVE_TABLE}", node_roles=ALL_ROLES),
+ run_sql_with_exceptions(WRITABLE_QUERY_LOG_ARCHIVE_OPS_TABLE_SQL(), node_roles=ALL_ROLES),
+ ]
+ ),
+]
diff --git a/posthog/clickhouse/migrations/max_migration.txt b/posthog/clickhouse/migrations/max_migration.txt
index b9de44507bfa..a2361a702c7b 100644
--- a/posthog/clickhouse/migrations/max_migration.txt
+++ b/posthog/clickhouse/migrations/max_migration.txt
@@ -1 +1 @@
-0275_add_web_bot_definition_dict
+0276_query_log_archive_buffer
diff --git a/posthog/clickhouse/query_log_archive.py b/posthog/clickhouse/query_log_archive.py
index e73376a363f9..eb9ff883dd60 100644
--- a/posthog/clickhouse/query_log_archive.py
+++ b/posthog/clickhouse/query_log_archive.py
@@ -1,6 +1,6 @@
from django.conf import settings
-from posthog.clickhouse.table_engines import Distributed, MergeTreeEngine, ReplicationScheme
+from posthog.clickhouse.table_engines import Buffer, Distributed, MergeTreeEngine, ReplicationScheme
QUERY_LOG_ARCHIVE_DATA_TABLE = "query_log_archive"
QUERY_LOG_ARCHIVE_MV = "query_log_archive_mv"
@@ -505,6 +505,7 @@ def QUERY_LOG_ARCHIVE_UPDATE_MV_SQL(mv_name=QUERY_LOG_ARCHIVE_MV):
# ============================================================================
WRITABLE_QUERY_LOG_ARCHIVE_TABLE = "writable_query_log_archive"
+QUERY_LOG_ARCHIVE_BUFFER_TABLE = "query_log_archive_buffer" # Buffer in front of sharded_query_log_archive, on OPS
QUERY_LOG_ARCHIVE_OPS_MV = "ops_query_log_archive_mv" # slim MV -> writable_query_log_archive, on every cluster
# Curated JSON subset of log_comment. Keys not hinted here are still kept as
@@ -737,12 +738,39 @@ def DISTRIBUTED_QUERY_LOG_ARCHIVE_OPS_TABLE_SQL(cluster=None):
)
+def QUERY_LOG_ARCHIVE_BUFFER_OPS_TABLE_SQL():
+ """Buffer table on OPS, sitting in front of sharded_query_log_archive.
+
+ Every cluster's writable Distributed routes inserts here; the Buffer batches the
+ many small per-cluster MV inserts in memory and flushes them to the underlying
+ ReplicatedMergeTree, cutting part churn. Physical (insertable) columns only — the
+ structure must match the destination's real columns, and the lc_* / ProfileEvents_*
+ aliases are read-time only. Rows still buffered are not yet visible through the
+ read path (query_log_archive -> sharded_query_log_archive).
+ """
+ return QUERY_LOG_ARCHIVE_OPS_TABLE_SQL(
+ table_name=QUERY_LOG_ARCHIVE_BUFFER_TABLE,
+ engine=Buffer(
+ destination_table=SHARDED_QUERY_LOG_ARCHIVE_TABLE,
+ num_layers=16,
+ min_time=10,
+ max_time=60,
+ min_rows=10_000,
+ max_rows=1_000_000,
+ min_bytes=10_000_000,
+ max_bytes=100_000_000,
+ ),
+ include_aliases=False,
+ include_table_clauses=False,
+ )
+
+
def WRITABLE_QUERY_LOG_ARCHIVE_OPS_TABLE_SQL(cluster=None):
- """Distributed write table carrying physical columns only, pointing at OPS."""
+ """Distributed write table carrying physical columns only, pointing at the OPS Buffer."""
return QUERY_LOG_ARCHIVE_OPS_TABLE_SQL(
table_name=WRITABLE_QUERY_LOG_ARCHIVE_TABLE,
engine=Distributed(
- data_table=SHARDED_QUERY_LOG_ARCHIVE_TABLE,
+ data_table=QUERY_LOG_ARCHIVE_BUFFER_TABLE,
cluster=cluster or settings.CLICKHOUSE_OPS_CLUSTER,
),
include_aliases=False,
diff --git a/posthog/clickhouse/schema.py b/posthog/clickhouse/schema.py
index c910bc867954..6a3cc6d5191c 100644
--- a/posthog/clickhouse/schema.py
+++ b/posthog/clickhouse/schema.py
@@ -86,6 +86,7 @@ from posthog.clickhouse.property_values import (
from posthog.clickhouse.query_log_archive import (
DAILY_AGGREGATED_QUERY_LOG_ARCHIVE_VIEW_SQL,
DISTRIBUTED_QUERY_LOG_ARCHIVE_OPS_TABLE_SQL,
+ QUERY_LOG_ARCHIVE_BUFFER_OPS_TABLE_SQL,
QUERY_LOG_ARCHIVE_OPS_MV,
QUERY_LOG_ARCHIVE_OPS_MV_SQL,
SHARDED_QUERY_LOG_ARCHIVE_OPS_TABLE_SQL,
@@ -325,6 +326,7 @@ CREATE_MERGETREE_TABLE_QUERIES = (
WEB_STATS_SQL,
WEB_BOUNCES_SQL,
SHARDED_QUERY_LOG_ARCHIVE_OPS_TABLE_SQL,
+ QUERY_LOG_ARCHIVE_BUFFER_OPS_TABLE_SQL,
COHORT_MEMBERSHIP_TABLE_SQL,
PRECALCULATED_EVENTS_SHARDED_TABLE_SQL,
SHARDED_PREAGGREGATION_RESULTS_TABLE_SQL,
diff --git a/posthog/clickhouse/table_engines.py b/posthog/clickhouse/table_engines.py
index c181941ec983..fac05b3bd2d5 100644
--- a/posthog/clickhouse/table_engines.py
+++ b/posthog/clickhouse/table_engines.py
@@ -99,3 +99,42 @@ class Distributed:
return f"Distributed('{cluster}', '{database}', '{self.data_table}')"
return f"Distributed('{cluster}', '{database}', '{self.data_table}', {self.sharding_key})"
+
+
+class Buffer:
+ """Buffer engine: accumulates inserts in memory and flushes them to a destination
+ table in batches. Flushes when any of the max_* thresholds is exceeded, or once
+ all of the min_* thresholds are met. See
+ https://clickhouse.com/docs/en/engines/table-engines/special/buffer.
+ """
+
+ def __init__(
+ self,
+ destination_table: str,
+ num_layers: int,
+ min_time: int,
+ max_time: int,
+ min_rows: int,
+ max_rows: int,
+ min_bytes: int,
+ max_bytes: int,
+ database: str | None = None,
+ ):
+ self.destination_table = destination_table
+ self.num_layers = num_layers
+ self.min_time = min_time
+ self.max_time = max_time
+ self.min_rows = min_rows
+ self.max_rows = max_rows
+ self.min_bytes = min_bytes
+ self.max_bytes = max_bytes
+ self.database = database
+
+ def __str__(self):
+ # Evaluate database at call time, not at module import time (mirrors Distributed).
+ database = self.database if self.database is not None else settings.CLICKHOUSE_DATABASE
+ return (
+ f"Buffer('{database}', '{self.destination_table}', "
+ f"{self.num_layers}, {self.min_time}, {self.max_time}, "
+ f"{self.min_rows}, {self.max_rows}, {self.min_bytes}, {self.max_bytes})"
+ )
diff --git a/posthog/clickhouse/test/__snapshots__/test_schema.ambr b/posthog/clickhouse/test/__snapshots__/test_schema.ambr
index 9a6d2a3d747d..3d0ba81b7e74 100644
--- a/posthog/clickhouse/test/__snapshots__/test_schema.ambr
+++ b/posthog/clickhouse/test/__snapshots__/test_schema.ambr
@@ -3997,6 +3997,101 @@
) ENGINE = Distributed('ops', 'posthog_test', 'sharded_query_log_archive')
'''
# ---
+# name: test_create_table_query[query_log_archive_buffer]
+ '''
+ CREATE TABLE IF NOT EXISTS query_log_archive_buffer (
+
+ hostname LowCardinality(String),
+ user LowCardinality(String),
+ query_id String,
+ initial_query_id String,
+ is_initial_query UInt8,
+ type Enum8('QueryStart' = 1, 'QueryFinish' = 2, 'ExceptionBeforeStart' = 3, 'ExceptionWhileProcessing' = 4),
+
+ event_date Date,
+ event_time DateTime,
+ event_time_microseconds DateTime64(6),
+ query_start_time DateTime,
+ query_start_time_microseconds DateTime64(6),
+ query_duration_ms UInt64,
+
+ read_rows UInt64,
+ read_bytes UInt64,
+ written_rows UInt64,
+ written_bytes UInt64,
+ result_rows UInt64,
+ result_bytes UInt64,
+ memory_usage UInt64,
+ peak_threads_usage UInt64,
+
+ current_database LowCardinality(String),
+ query String,
+ formatted_query String,
+ normalized_query_hash UInt64,
+ query_kind LowCardinality(String),
+
+ exception_code Int32,
+ exception String,
+ stack_trace String,
+
+ team_id Int64,
+ log_comment JSON(
+ max_dynamic_paths = 256,
+ team_id Int64,
+ user_id Int64,
+ org_id String,
+ session_id String,
+ access_method LowCardinality(String),
+ api_key_label String,
+ api_key_mask String,
+ workflow LowCardinality(String),
+ kind LowCardinality(String),
+ id String,
+ route_id String,
+ query_type LowCardinality(String),
+ product LowCardinality(String),
+ chargeable Bool,
+ name String,
+ request_name String,
+ client_query_id String,
+ is_impersonated Bool,
+ dashboard_id Int64,
+ insight_id Int64,
+ cohort_id Int64,
+ batch_export_id String,
+ experiment_id Int64,
+ experiment_feature_flag_key String,
+ alert_config_id String,
+ feature LowCardinality(String),
+ table_id String,
+ warehouse_query Bool,
+ person_on_events_mode LowCardinality(String),
+ service_name String,
+ workload LowCardinality(String),
+ `temporal.workflow_namespace` String,
+ `temporal.workflow_type` String,
+ `temporal.workflow_id` String,
+ `temporal.workflow_run_id` String,
+ `temporal.activity_type` String,
+ `temporal.activity_id` String,
+ `temporal.attempt` Int64,
+ `dagster.job_name` String,
+ `dagster.run_id` String,
+ `dagster.tags.owner` String,
+ SKIP user_email,
+ SKIP query_settings,
+ SKIP timings,
+ SKIP `filter`,
+ SKIP hogql_features,
+ SKIP http_referer,
+ SKIP http_user_agent,
+ SKIP http_request_id,
+ SKIP cache_key
+ ),
+ ProfileEvents Map(String, UInt64)
+ ) ENGINE = Buffer('posthog_test', 'sharded_query_log_archive', 16, 10, 60, 10000, 1000000, 10000000, 100000000)
+ '''
+# ---
# name: test_create_table_query[raw_error_tracking_fingerprint_issue_state]
'''
@@ -7758,7 +7853,7 @@
SKIP cache_key
),
ProfileEvents Map(String, UInt64)
- ) ENGINE = Distributed('ops', 'posthog_test', 'sharded_query_log_archive')
+ ) ENGINE = Distributed('ops', 'posthog_test', 'query_log_archive_buffer')
'''
# ---
# name: test_create_table_query[writable_raw_sessions]
@@ -9002,6 +9097,101 @@
'''
# ---
+# name: test_create_table_query_replicated_and_storage[query_log_archive_buffer]
+ '''
+ CREATE TABLE IF NOT EXISTS query_log_archive_buffer (
+
+ hostname LowCardinality(String),
+ user LowCardinality(String),
+ query_id String,
+ initial_query_id String,
+ is_initial_query UInt8,
+ type Enum8('QueryStart' = 1, 'QueryFinish' = 2, 'ExceptionBeforeStart' = 3, 'ExceptionWhileProcessing' = 4),
+
+ event_date Date,
+ event_time DateTime,
+ event_time_microseconds DateTime64(6),
+ query_start_time DateTime,
+ query_start_time_microseconds DateTime64(6),
+ query_duration_ms UInt64,
+
+ read_rows UInt64,
+ read_bytes UInt64,
+ written_rows UInt64,
+ written_bytes UInt64,
+ result_rows UInt64,
+ result_bytes UInt64,
+ memory_usage UInt64,
+ peak_threads_usage UInt64,
+
+ current_database LowCardinality(String),
+ query String,
+ formatted_query String,
+ normalized_query_hash UInt64,
+ query_kind LowCardinality(String),
+
+ exception_code Int32,
+ exception String,
+ stack_trace String,
+
+ team_id Int64,
+ log_comment JSON(
+ max_dynamic_paths = 256,
+ team_id Int64,
+ user_id Int64,
+ org_id String,
+ session_id String,
+ access_method LowCardinality(String),
+ api_key_label String,
+ api_key_mask String,
+ workflow LowCardinality(String),
+ kind LowCardinality(String),
+ id String,
+ route_id String,
+ query_type LowCardinality(String),
+ product LowCardinality(String),
+ chargeable Bool,
+ name String,
+ request_name String,
+ client_query_id String,
+ is_impersonated Bool,
+ dashboard_id Int64,
+ insight_id Int64,
+ cohort_id Int64,
+ batch_export_id String,
+ experiment_id Int64,
+ experiment_feature_flag_key String,
+ alert_config_id String,
+ feature LowCardinality(String),
+ table_id String,
+ warehouse_query Bool,
+ person_on_events_mode LowCardinality(String),
+ service_name String,
+ workload LowCardinality(String),
+ `temporal.workflow_namespace` String,
+ `temporal.workflow_type` String,
+ `temporal.workflow_id` String,
+ `temporal.workflow_run_id` String,
+ `temporal.activity_type` String,
+ `temporal.activity_id` String,
+ `temporal.attempt` Int64,
+ `dagster.job_name` String,
+ `dagster.run_id` String,
+ `dagster.tags.owner` String,
+ SKIP user_email,
+ SKIP query_settings,
+ SKIP timings,
+ SKIP `filter`,
+ SKIP hogql_features,
+ SKIP http_referer,
+ SKIP http_user_agent,
+ SKIP http_request_id,
+ SKIP cache_key
+ ),
+ ProfileEvents Map(String, UInt64)
+ ) ENGINE = Buffer('posthog_test', 'sharded_query_log_archive', 16, 10, 60, 10000, 1000000, 10000000, 100000000)
+ '''
+# ---
# name: test_create_table_query_replicated_and_storage[raw_error_tracking_fingerprint_issue_state]
'''