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(metrics): add metric_events ClickHouse table (#66163)

Daniel Viscaa0659d5e7b8f
diff --git a/posthog/clickhouse/metrics/__init__.py b/posthog/clickhouse/metrics/__init__.py
index 5df721690eea..feede7a604cf 100644
--- a/posthog/clickhouse/metrics/__init__.py
+++ b/posthog/clickhouse/metrics/__init__.py
@@ -1,4 +1,10 @@
from .metric_attributes import METRIC_ATTRIBUTES_TABLE_SQL
+from .metric_events import (
+ METRIC_SAMPLES_DISTRIBUTED_TABLE_SQL,
+ METRIC_SAMPLES_TABLE_SQL,
+ METRIC_SERIES_DISTRIBUTED_TABLE_SQL,
+ METRIC_SERIES_TABLE_SQL,
+)
from .metrics1 import (
METRIC_ATTRIBUTES_MV,
METRIC_RESOURCE_ATTRIBUTES_MV,
@@ -12,4 +18,8 @@ __all__ = [
"METRIC_ATTRIBUTES_MV",
"METRIC_RESOURCE_ATTRIBUTES_MV",
"METRIC_ATTRIBUTES_TABLE_SQL",
+ "METRIC_SERIES_TABLE_SQL",
+ "METRIC_SERIES_DISTRIBUTED_TABLE_SQL",
+ "METRIC_SAMPLES_TABLE_SQL",
+ "METRIC_SAMPLES_DISTRIBUTED_TABLE_SQL",
]
diff --git a/posthog/clickhouse/metrics/metric_events.py b/posthog/clickhouse/metrics/metric_events.py
new file mode 100644
index 000000000000..d6ec2589e6f7
--- /dev/null
+++ b/posthog/clickhouse/metrics/metric_events.py
@@ -0,0 +1,89 @@
+from django.conf import settings
+
+from posthog.clickhouse.table_engines import Distributed, MergeTreeEngine, ReplacingMergeTree, ReplicationScheme
+
+# Raw, un-aggregated metrics stored as a TSDB series/samples split (not the
+# fat one-row-per-event shape logs/traces use — a metric sample is a single
+# number, so inlining the label maps on every row would dwarf the data ~100x).
+#
+# - metric_series: one row per unique (metric, label-set), labels stored ONCE,
+# keyed by a fingerprint. Deduped via ReplacingMergeTree.
+# - metric_samples: the hot table — tiny rows (fingerprint + timestamp + value),
+# plus an inline trace_id so a spike can still pivot to its trace (empty for
+# most points, so it compresses to ~nothing). Joined to metric_series on the
+# fingerprint at query time.
+#
+# Distinct from `metrics1` (pre-aggregated rollups for dashboards/alerts): this
+# keeps every raw sample, for exact quantiles, per-emission drill-down, and the
+# metric->trace pivot. Lives on the logs ClickHouse cluster next to logs/traces.
+#
+# The fingerprint must be computed identically wherever samples/series are
+# written (see the ingest MV); keep this expression and that MV in sync.
+SERIES_FINGERPRINT_SQL = "cityHash64(metric_name, service_name, mapSort(resource_attributes), mapSort(attributes))"
+
+SAMPLES_TABLE_NAME = "metric_samples1"
+SAMPLES_DISTRIBUTED_TABLE_NAME = "metric_samples"
+SERIES_TABLE_NAME = "metric_series1"
+SERIES_DISTRIBUTED_TABLE_NAME = "metric_series"
+
+
+def METRIC_SERIES_TABLE_SQL():
+ return f"""
+CREATE TABLE IF NOT EXISTS {settings.CLICKHOUSE_LOGS_CLUSTER_DATABASE}.{SERIES_TABLE_NAME}
+(
+ `team_id` Int32,
+ `metric_name` LowCardinality(String),
+ `series_fingerprint` UInt64 CODEC(DoubleDelta),
+ `metric_type` LowCardinality(String),
+ `unit` LowCardinality(String),
+ `service_name` LowCardinality(String),
+ `resource_attributes` Map(LowCardinality(String), String),
+ `attributes` Map(LowCardinality(String), String),
+ `last_seen` DateTime64(6) CODEC(DoubleDelta),
+ INDEX idx_service_set service_name TYPE set(1000) GRANULARITY 1,
+ INDEX idx_attr_keys mapKeys(attributes) TYPE bloom_filter(0.01) GRANULARITY 1,
+ INDEX idx_attr_values mapValues(attributes) TYPE bloom_filter(0.01) GRANULARITY 1
+)
+ENGINE = {ReplacingMergeTree(SERIES_TABLE_NAME, replication_scheme=ReplicationScheme.REPLICATED, ver="last_seen")}
+ORDER BY (team_id, metric_name, series_fingerprint)
+SETTINGS index_granularity = 8192
+"""
+
+
+def METRIC_SAMPLES_TABLE_SQL():
+ return f"""
+CREATE TABLE IF NOT EXISTS {settings.CLICKHOUSE_LOGS_CLUSTER_DATABASE}.{SAMPLES_TABLE_NAME}
+(
+ `team_id` Int32,
+ `metric_name` LowCardinality(String),
+ `series_fingerprint` UInt64 CODEC(DoubleDelta),
+ `timestamp` DateTime64(6) CODEC(DoubleDelta),
+ `value` Float64 CODEC(Gorilla),
+ `trace_id` String,
+ `span_id` String,
+ `trace_flags` Int32,
+ INDEX idx_trace_id_bf trace_id TYPE bloom_filter(0.01) GRANULARITY 1
+)
+ENGINE = {MergeTreeEngine(SAMPLES_TABLE_NAME, replication_scheme=ReplicationScheme.REPLICATED)}
+PARTITION BY toDate(timestamp)
+ORDER BY (team_id, metric_name, series_fingerprint, timestamp)
+TTL toDateTime(timestamp) + INTERVAL 30 DAY
+SETTINGS index_granularity = 8192, ttl_only_drop_parts = 1
+"""
+
+
+def _distributed_sql(distributed_name: str, data_table: str) -> str:
+ return "CREATE TABLE IF NOT EXISTS {database}.{distributed} AS {database}.{table_name} ENGINE = {engine}".format(
+ distributed=distributed_name,
+ table_name=data_table,
+ engine=Distributed(data_table=data_table, cluster=settings.CLICKHOUSE_LOGS_CLUSTER),
+ database=settings.CLICKHOUSE_LOGS_CLUSTER_DATABASE,
+ )
+
+
+def METRIC_SERIES_DISTRIBUTED_TABLE_SQL():
+ return _distributed_sql(SERIES_DISTRIBUTED_TABLE_NAME, SERIES_TABLE_NAME)
+
+
+def METRIC_SAMPLES_DISTRIBUTED_TABLE_SQL():
+ return _distributed_sql(SAMPLES_DISTRIBUTED_TABLE_NAME, SAMPLES_TABLE_NAME)
diff --git a/posthog/clickhouse/migrations/0283_metric_events.py b/posthog/clickhouse/migrations/0283_metric_events.py
new file mode 100644
index 000000000000..f5689b00c61f
--- /dev/null
+++ b/posthog/clickhouse/migrations/0283_metric_events.py
@@ -0,0 +1,15 @@
+from posthog.clickhouse.client.connection import NodeRole
+from posthog.clickhouse.client.migration_tools import run_sql_with_exceptions
+from posthog.clickhouse.metrics.metric_events import (
+ METRIC_SAMPLES_DISTRIBUTED_TABLE_SQL,
+ METRIC_SAMPLES_TABLE_SQL,
+ METRIC_SERIES_DISTRIBUTED_TABLE_SQL,
+ METRIC_SERIES_TABLE_SQL,
+)
+
+operations = [
+ run_sql_with_exceptions(METRIC_SERIES_TABLE_SQL(), node_roles=[NodeRole.LOGS]),
+ run_sql_with_exceptions(METRIC_SAMPLES_TABLE_SQL(), node_roles=[NodeRole.LOGS]),
+ run_sql_with_exceptions(METRIC_SERIES_DISTRIBUTED_TABLE_SQL(), node_roles=[NodeRole.LOGS]),
+ run_sql_with_exceptions(METRIC_SAMPLES_DISTRIBUTED_TABLE_SQL(), node_roles=[NodeRole.LOGS]),
+]
diff --git a/posthog/clickhouse/migrations/max_migration.txt b/posthog/clickhouse/migrations/max_migration.txt
index cba2044f87a1..02a067a552cb 100644
--- a/posthog/clickhouse/migrations/max_migration.txt
+++ b/posthog/clickhouse/migrations/max_migration.txt
@@ -1 +1 @@
-0282_log_attributes_severity
+0283_metric_events
diff --git a/posthog/clickhouse/schema.py b/posthog/clickhouse/schema.py
index c1625173826e..948e4d08e551 100644
--- a/posthog/clickhouse/schema.py
+++ b/posthog/clickhouse/schema.py
@@ -33,6 +33,10 @@ from posthog.clickhouse.metrics import (
METRIC_ATTRIBUTES_MV,
METRIC_ATTRIBUTES_TABLE_SQL,
METRIC_RESOURCE_ATTRIBUTES_MV,
+ METRIC_SAMPLES_DISTRIBUTED_TABLE_SQL,
+ METRIC_SAMPLES_TABLE_SQL,
+ METRIC_SERIES_DISTRIBUTED_TABLE_SQL,
+ METRIC_SERIES_TABLE_SQL,
METRICS1_TABLE_SQL,
METRICS_DISTRIBUTED_TABLE_SQL,
)
@@ -369,6 +373,8 @@ CREATE_MERGETREE_TABLE_QUERIES = (
LOG_ATTRIBUTES3_TABLE_SQL,
LOGS_BILLING_METRICS_TABLE_SQL,
METRICS1_TABLE_SQL,
+ METRIC_SERIES_TABLE_SQL,
+ METRIC_SAMPLES_TABLE_SQL,
METRIC_ATTRIBUTES_TABLE_SQL,
TOPHOG_DATA_TABLE_SQL,
AI_EVENTS_DATA_TABLE_SQL,
@@ -441,6 +447,8 @@ CREATE_DISTRIBUTED_TABLE_QUERIES = (
LOGS_KAFKA_METRICS_DISTRIBUTED_TABLE_SQL,
LOGS_BILLING_METRICS_DISTRIBUTED_TABLE_SQL,
METRICS_DISTRIBUTED_TABLE_SQL,
+ METRIC_SERIES_DISTRIBUTED_TABLE_SQL,
+ METRIC_SAMPLES_DISTRIBUTED_TABLE_SQL,
WRITABLE_TOPHOG_TABLE_SQL,
DISTRIBUTED_TOPHOG_TABLE_SQL,
DISTRIBUTED_AI_EVENTS_TABLE_SQL,
diff --git a/posthog/clickhouse/test/__snapshots__/test_schema.ambr b/posthog/clickhouse/test/__snapshots__/test_schema.ambr
index b43987000487..f5d1c56a0351 100644
--- a/posthog/clickhouse/test/__snapshots__/test_schema.ambr
+++ b/posthog/clickhouse/test/__snapshots__/test_schema.ambr
@@ -3376,6 +3376,59 @@
'''
# ---
+# name: test_create_table_query[metric_samples1]
+ '''
+
+ CREATE TABLE IF NOT EXISTS posthog_test.metric_samples1
+ (
+ `team_id` Int32,
+ `metric_name` LowCardinality(String),
+ `series_fingerprint` UInt64 CODEC(DoubleDelta),
+ `timestamp` DateTime64(6) CODEC(DoubleDelta),
+ `value` Float64 CODEC(Gorilla),
+ `trace_id` String,
+ `span_id` String,
+ `trace_flags` Int32,
+ INDEX idx_trace_id_bf trace_id TYPE bloom_filter(0.01) GRANULARITY 1
+ )
+ ENGINE = ReplicatedMergeTree('/clickhouse/tables/77f1df52-4b43-11e9-910f-b8ca3a9b9f3e_noshard/posthog.metric_samples1', '{replica}-{shard}')
+ PARTITION BY toDate(timestamp)
+ ORDER BY (team_id, metric_name, series_fingerprint, timestamp)
+ TTL toDateTime(timestamp) + INTERVAL 30 DAY
+ SETTINGS index_granularity = 8192, ttl_only_drop_parts = 1
+
+ '''
+# ---
+# name: test_create_table_query[metric_samples]
+ "CREATE TABLE IF NOT EXISTS posthog_test.metric_samples AS posthog_test.metric_samples1 ENGINE = Distributed('posthog_single_shard', 'posthog_test', 'metric_samples1')"
+# ---
+# name: test_create_table_query[metric_series1]
+ '''
+
+ CREATE TABLE IF NOT EXISTS posthog_test.metric_series1
+ (
+ `team_id` Int32,
+ `metric_name` LowCardinality(String),
+ `series_fingerprint` UInt64 CODEC(DoubleDelta),
+ `metric_type` LowCardinality(String),
+ `unit` LowCardinality(String),
+ `service_name` LowCardinality(String),
+ `resource_attributes` Map(LowCardinality(String), String),
+ `attributes` Map(LowCardinality(String), String),
+ `last_seen` DateTime64(6) CODEC(DoubleDelta),
+ INDEX idx_service_set service_name TYPE set(1000) GRANULARITY 1,
+ INDEX idx_attr_keys mapKeys(attributes) TYPE bloom_filter(0.01) GRANULARITY 1,
+ INDEX idx_attr_values mapValues(attributes) TYPE bloom_filter(0.01) GRANULARITY 1
+ )
+ ENGINE = ReplicatedReplacingMergeTree('/clickhouse/tables/77f1df52-4b43-11e9-910f-b8ca3a9b9f3e_noshard/posthog.metric_series1', '{replica}-{shard}', last_seen)
+ ORDER BY (team_id, metric_name, series_fingerprint)
+ SETTINGS index_granularity = 8192
+
+ '''
+# ---
+# name: test_create_table_query[metric_series]
+ "CREATE TABLE IF NOT EXISTS posthog_test.metric_series AS posthog_test.metric_series1 ENGINE = Distributed('posthog_single_shard', 'posthog_test', 'metric_series1')"
+# ---
# name: test_create_table_query[metrics1]
'''
@@ -9376,6 +9429,53 @@
'''
# ---
+# name: test_create_table_query_replicated_and_storage[metric_samples1]
+ '''
+
+ CREATE TABLE IF NOT EXISTS posthog_test.metric_samples1
+ (
+ `team_id` Int32,
+ `metric_name` LowCardinality(String),
+ `series_fingerprint` UInt64 CODEC(DoubleDelta),
+ `timestamp` DateTime64(6) CODEC(DoubleDelta),
+ `value` Float64 CODEC(Gorilla),
+ `trace_id` String,
+ `span_id` String,
+ `trace_flags` Int32,
+ INDEX idx_trace_id_bf trace_id TYPE bloom_filter(0.01) GRANULARITY 1
+ )
+ ENGINE = ReplicatedMergeTree('/clickhouse/tables/77f1df52-4b43-11e9-910f-b8ca3a9b9f3e_noshard/posthog.metric_samples1', '{replica}-{shard}')
+ PARTITION BY toDate(timestamp)
+ ORDER BY (team_id, metric_name, series_fingerprint, timestamp)
+ TTL toDateTime(timestamp) + INTERVAL 30 DAY
+ SETTINGS index_granularity = 8192, ttl_only_drop_parts = 1
+
+ '''
+# ---
+# name: test_create_table_query_replicated_and_storage[metric_series1]
+ '''
+
+ CREATE TABLE IF NOT EXISTS posthog_test.metric_series1
+ (
+ `team_id` Int32,
+ `metric_name` LowCardinality(String),
+ `series_fingerprint` UInt64 CODEC(DoubleDelta),
+ `metric_type` LowCardinality(String),
+ `unit` LowCardinality(String),
+ `service_name` LowCardinality(String),
+ `resource_attributes` Map(LowCardinality(String), String),
+ `attributes` Map(LowCardinality(String), String),
+ `last_seen` DateTime64(6) CODEC(DoubleDelta),
+ INDEX idx_service_set service_name TYPE set(1000) GRANULARITY 1,
+ INDEX idx_attr_keys mapKeys(attributes) TYPE bloom_filter(0.01) GRANULARITY 1,
+ INDEX idx_attr_values mapValues(attributes) TYPE bloom_filter(0.01) GRANULARITY 1
+ )
+ ENGINE = ReplicatedReplacingMergeTree('/clickhouse/tables/77f1df52-4b43-11e9-910f-b8ca3a9b9f3e_noshard/posthog.metric_series1', '{replica}-{shard}', last_seen)
+ ORDER BY (team_id, metric_name, series_fingerprint)
+ SETTINGS index_granularity = 8192
+
+ '''
+# ---
# name: test_create_table_query_replicated_and_storage[metrics1]
'''