: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(metrics): Metrics capture and ingestion scaffolding (#50936)
Ben Whitea35c1ab27a5e
diff --git a/bin/clickhouse-metrics-init b/bin/clickhouse-metrics-initnew file mode 100755index 000000000000..d057be56c1a5--- /dev/null+++ b/bin/clickhouse-metrics-init@@ -0,0 +1,5 @@+#!/usr/bin/env bash+# temporary script to init metrics clickhouse schema before we've got migrations setup properly+bin/wait-for-docker++cat bin/clickhouse-metrics.sql | docker-compose exec -T clickhouse clickhouse-clientdiff --git a/bin/clickhouse-metrics.sql b/bin/clickhouse-metrics.sqlnew file mode 100644index 000000000000..e28982e7beb1--- /dev/null+++ b/bin/clickhouse-metrics.sql@@ -0,0 +1,265 @@+-- temporary sql to initialise metrics tables for local development+-- will be removed once we have migrations set up+-- modelled after clickhouse-logs.sql following the same patterns+CREATE OR REPLACE TABLE metrics1+(+ `time_bucket` DateTime MATERIALIZED toStartOfDay(timestamp) CODEC(DoubleDelta, ZSTD(1)),+ `uuid` String CODEC(ZSTD(1)),+ `team_id` Int32 CODEC(ZSTD(1)),+ `trace_id` String CODEC(ZSTD(1)),+ `span_id` String CODEC(ZSTD(1)),+ `trace_flags` Int32 CODEC(ZSTD(1)),+ `timestamp` DateTime64(6) CODEC(DoubleDelta, ZSTD(1)),+ `observed_timestamp` DateTime64(6) CODEC(DoubleDelta, ZSTD(1)),+ `created_at` DateTime64(6) MATERIALIZED now() CODEC(DoubleDelta, ZSTD(1)),+ `service_name` LowCardinality(String) CODEC(ZSTD(1)),+ `metric_name` LowCardinality(String) CODEC(ZSTD(1)),+ `metric_type` LowCardinality(String) CODEC(ZSTD(1)),+ `value` Float64 CODEC(Gorilla, ZSTD(1)),+ `count` UInt64 DEFAULT 1 CODEC(T64, ZSTD(1)),+ `histogram_bounds` Array(Float64) CODEC(ZSTD(1)),+ `histogram_counts` Array(UInt64) CODEC(ZSTD(1)),+ `unit` LowCardinality(String) CODEC(ZSTD(1)),+ `aggregation_temporality` LowCardinality(String) CODEC(ZSTD(1)),+ `is_monotonic` Bool DEFAULT false CODEC(ZSTD(1)),+ `resource_attributes` Map(LowCardinality(String), String) CODEC(ZSTD(1)),+ `resource_fingerprint` UInt64 MATERIALIZED cityHash64(resource_attributes) CODEC(DoubleDelta, ZSTD(1)),+ `instrumentation_scope` String CODEC(ZSTD(1)),+ `attributes_map_str` Map(LowCardinality(String), String) CODEC(ZSTD(1)),+ `attributes_map_float` Map(LowCardinality(String), Float64) CODEC(ZSTD(1)),+ `time_minute` DateTime ALIAS toStartOfMinute(timestamp),+ `attributes` Map(String, String) ALIAS mapApply((k, v) -> (left(k, -5), v), attributes_map_str),+ INDEX idx_metric_name_set metric_name TYPE set(100) GRANULARITY 1,+ INDEX idx_metric_type_set metric_type TYPE set(10) GRANULARITY 1,+ INDEX idx_attributes_str_keys mapKeys(attributes_map_str) TYPE bloom_filter(0.01) GRANULARITY 1,+ INDEX idx_attributes_str_values mapValues(attributes_map_str) TYPE bloom_filter(0.001) GRANULARITY 1,+ INDEX idx_observed_minmax observed_timestamp TYPE minmax GRANULARITY 1,+ PROJECTION projection_aggregate_counts+ (+ SELECT+ team_id,+ time_bucket,+ toStartOfMinute(timestamp),+ service_name,+ metric_name,+ metric_type,+ resource_fingerprint,+ count() AS event_count,+ sum(value) AS total_value,+ min(value) AS min_value,+ max(value) AS max_value+ GROUP BY+ team_id,+ time_bucket,+ toStartOfMinute(timestamp),+ service_name,+ metric_name,+ metric_type,+ resource_fingerprint+ )+)+ENGINE = MergeTree+PARTITION BY toDate(timestamp)+PRIMARY KEY (team_id, time_bucket, service_name, metric_name, resource_fingerprint, timestamp)+ORDER BY (team_id, time_bucket, service_name, metric_name, resource_fingerprint, timestamp)+SETTINGS+ index_granularity_bytes = 104857600,+ index_granularity = 8192,+ ttl_only_drop_parts = 1;++create or replace TABLE metrics AS metrics1 ENGINE = Distributed('posthog', 'default', 'metrics1');++-- Attribute discovery table (reuses logs pattern)+create or replace table default.metric_attributes+(+ `team_id` Int32,+ `time_bucket` DateTime64(0),+ `service_name` LowCardinality(String),+ `resource_fingerprint` UInt64 DEFAULT 0,+ `attribute_key` LowCardinality(String),+ `attribute_value` String,+ `attribute_type` LowCardinality(String),+ `attribute_count` SimpleAggregateFunction(sum, UInt64),+ INDEX idx_attribute_key attribute_key TYPE bloom_filter(0.01) GRANULARITY 1,+ INDEX idx_attribute_value attribute_value TYPE bloom_filter(0.01) GRANULARITY 1,+ INDEX idx_attribute_key_n3 attribute_key TYPE ngrambf_v1(3, 32768, 3, 0) GRANULARITY 1,+ INDEX idx_attribute_value_n3 attribute_value TYPE ngrambf_v1(3, 32768, 3, 0) GRANULARITY 1+)+ENGINE = AggregatingMergeTree+PARTITION BY toDate(time_bucket)+ORDER BY (team_id, attribute_type, time_bucket, resource_fingerprint, attribute_key, attribute_value);++-- MV: resource attributes -> metric_attributes+drop view if exists metric_to_resource_attributes;+CREATE MATERIALIZED VIEW metric_to_resource_attributes TO metric_attributes+(+ `team_id` Int32,+ `time_bucket` DateTime64(0),+ `service_name` LowCardinality(String),+ `resource_fingerprint` UInt64,+ `attribute_key` LowCardinality(String),+ `attribute_value` String,+ `attribute_type` LowCardinality(String),+ `attribute_count` SimpleAggregateFunction(sum, UInt64)+)+AS SELECT+ team_id,+ time_bucket,+ service_name,+ resource_fingerprint,+ attribute_key,+ attribute_value,+ 'resource' as attribute_type,+ attribute_count+FROM+(+ SELECT+ team_id AS team_id,+ toStartOfInterval(timestamp, toIntervalMinute(10)) AS time_bucket,+ service_name AS service_name,+ resource_fingerprint,+ arrayJoin(resource_attributes) AS attribute,+ attribute.1 AS attribute_key,+ attribute.2 AS attribute_value,+ sumSimpleState(1) AS attribute_count+ FROM metrics1+ GROUP BY+ team_id,+ time_bucket,+ service_name,+ resource_fingerprint,+ attribute+);++-- MV: metric attributes -> metric_attributes+drop view if exists metric_to_metric_attributes;+CREATE MATERIALIZED VIEW metric_to_metric_attributes TO metric_attributes+(+ `team_id` Int32,+ `time_bucket` DateTime64(0),+ `service_name` LowCardinality(String),+ `resource_fingerprint` UInt64,+ `attribute_key` LowCardinality(String),+ `attribute_value` String,+ `attribute_type` LowCardinality(String),+ `attribute_count` SimpleAggregateFunction(sum, UInt64)+)+AS SELECT+ team_id,+ time_bucket,+ service_name,+ resource_fingerprint,+ attribute_key,+ attribute_value,+ 'metric' as attribute_type,+ attribute_count+FROM+(+ SELECT+ team_id AS team_id,+ toStartOfInterval(timestamp, toIntervalMinute(10)) AS time_bucket,+ service_name AS service_name,+ resource_fingerprint,+ arrayJoin(mapFilter((k, v) -> ((length(k) < 256) AND (length(v) < 256)), attributes)) AS attribute,+ attribute.1 AS attribute_key,+ attribute.2 AS attribute_value,+ sumSimpleState(1) AS attribute_count+ FROM metrics1+ GROUP BY+ team_id,+ time_bucket,+ service_name,+ resource_fingerprint,+ attribute+);++-- Kafka engine table reading AVRO from clickhouse_metrics topic+CREATE OR REPLACE TABLE kafka_metrics_avro+(+ `uuid` String,+ `trace_id` String,+ `span_id` String,+ `trace_flags` Nullable(Int32),+ `timestamp` DateTime64(6),+ `observed_timestamp` DateTime64(6),+ `service_name` Nullable(String),+ `metric_name` Nullable(String),+ `metric_type` Nullable(String),+ `value` Nullable(Float64),+ `count` Nullable(Int64),+ `histogram_bounds` Array(Float64),+ `histogram_counts` Array(Int64),+ `unit` Nullable(String),+ `aggregation_temporality` Nullable(String),+ `is_monotonic` Nullable(UInt8),+ `resource_attributes` Map(String, String),+ `instrumentation_scope` Nullable(String),+ `attributes` Map(String, String)+)+ENGINE = Kafka('kafka:9092', 'clickhouse_metrics', 'clickhouse-metrics-avro', 'Avro')+SETTINGS+ kafka_skip_broken_messages = 100,+ kafka_security_protocol = 'PLAINTEXT',+ kafka_thread_per_consumer = 1,+ kafka_num_consumers = 1,+ kafka_poll_timeout_ms=15000,+ kafka_poll_max_batch_size=10,+ kafka_max_block_size=10;++-- MV: kafka_metrics_avro -> metrics1+drop table if exists kafka_metrics_avro_mv;++CREATE MATERIALIZED VIEW kafka_metrics_avro_mv TO metrics1+AS SELECT+ uuid,+ trace_id,+ span_id,+ ifNull(trace_flags, 0) as trace_flags,+ timestamp,+ observed_timestamp,+ ifNull(service_name, '') as service_name,+ ifNull(metric_name, '') as metric_name,+ ifNull(metric_type, '') as metric_type,+ ifNull(value, 0) as value,+ toUInt64(ifNull(count, 1)) as count,+ histogram_bounds,+ arrayMap(x -> toUInt64(x), histogram_counts) as histogram_counts,+ ifNull(unit, '') as unit,+ ifNull(aggregation_temporality, '') as aggregation_temporality,+ ifNull(is_monotonic, 0) as is_monotonic,+ mapSort(mapApply((k, v) -> (k, JSONExtractString(v)), resource_attributes)) AS resource_attributes,+ ifNull(instrumentation_scope, '') as instrumentation_scope,+ mapSort(mapApply((k,v) -> (concat(k, '__str'), JSONExtractString(v)), attributes)) as attributes_map_str,+ mapSort(mapFilter((k, v) -> isNotNull(v), mapApply((k,v) -> (concat(k, '__float'), toFloat64OrNull(JSONExtract(v, 'String'))), attributes))) as attributes_map_float,+ toInt32OrZero(_headers.value[indexOf(_headers.name, 'team_id')]) as team_id+FROM kafka_metrics_avro settings min_insert_block_size_rows=0, min_insert_block_size_bytes=0;++-- Kafka consumer lag tracking+create or replace table metrics_kafka_metrics+(+ `_partition` UInt32,+ `_topic` String,+ `max_offset` SimpleAggregateFunction(max, UInt64),+ `max_observed_timestamp` SimpleAggregateFunction(max, DateTime64(9)),+ `max_timestamp` SimpleAggregateFunction(max, DateTime64(9)),+ `max_created_at` SimpleAggregateFunction(max, DateTime64(9)),+ `max_lag` SimpleAggregateFunction(max, UInt64)+)+ENGINE = MergeTree+ORDER BY (_topic, _partition);++drop view if exists kafka_metrics_avro_kafka_metrics_mv;+CREATE MATERIALIZED VIEW kafka_metrics_avro_kafka_metrics_mv TO metrics_kafka_metrics+AS+ SELECT+ _partition,+ _topic,+ maxSimpleState(_offset) as max_offset,+ maxSimpleState(observed_timestamp) as max_observed_timestamp,+ maxSimpleState(timestamp) as max_timestamp,+ maxSimpleState(now()) as max_created_at,+ maxSimpleState(now() - observed_timestamp) as max_lag+ FROM kafka_metrics_avro+ group by _partition, _topic;++select 'clickhouse metrics tables initialised successfully!';diff --git a/bin/mprocs.yaml b/bin/mprocs.yamlindex d0684ea1da17..696817d2aa3e 100755--- a/bin/mprocs.yaml+++ b/bin/mprocs.yaml@@ -67,7 +67,7 @@ procs:tech: Node# Node.js capabilities are controlled via NODEJS_CAPABILITY_GROUPS env var# Set by hogli dev:generate based on selected nodejs_* capabilities- # Valid groups: cdp_workflows, realtime_cohorts, session_replay, logs, traces, feature_flags+ # Valid groups: cdp_workflows, realtime_cohorts, session_replay, logs, traces, metrics, feature_flags# Example: NODEJS_CAPABILITY_GROUPS=cdp_workflows,session_replayingestion-errortracking:@@ -86,8 +86,13 @@ procs:layer: Ingestion pipelinetech: Node+ ingestion-metrics:+ shell: 'bin/wait-for-docker && PLUGIN_SERVER_MODE=ingestion-metrics HTTP_SERVER_PORT=6744 ./bin/posthog-node'+ capability: nodejs_metrics+ ready_pattern: 'All systems go'+ingestion-traces:- shell: 'bin/wait-for-docker && PLUGIN_SERVER_MODE=ingestion-traces HTTP_SERVER_PORT=6744 ./bin/posthog-node'+ shell: 'bin/wait-for-docker && PLUGIN_SERVER_MODE=ingestion-traces HTTP_SERVER_PORT=6745 ./bin/posthog-node'capability: nodejs_tracesready_pattern: 'All systems go'groups:@@ -313,6 +318,12 @@ procs:layer: Ingestion pipelinetech: Rust+ capture-logs:+ shell: |-+ bin/wait-for-docker && \+ bin/start-rust-service capture-logs+ capability: logs_ingestion+batch-import-worker:shell: |-bin/wait-for-docker && \diff --git a/bin/start-rust-service b/bin/start-rust-serviceindex c7cd915b0069..a940da291f2f 100755--- a/bin/start-rust-service+++ b/bin/start-rust-service@@ -89,6 +89,17 @@ case "$RS_SVC" inexport DEV_RUST_SVC_OVERRIDE=capture # we want to run the same "capture" binary in a separate mode;;+ capture-logs)+ export RUST_LOG=debug,rdkafka=warn+ export RUST_BACKTRACE=1+ export BIND_HOST=0.0.0.0+ export BIND_PORT=4320 # Offset from 4318 to avoid conflict with otel-collector host port mapping+ export MANAGEMENT_BIND_PORT=8081 # Avoid clash with other Rust services on 8080+ export KAFKA_HOSTS=localhost:9092+ export KAFKA_TOPIC=logs_ingestion+ export KAFKA_METRICS_TOPIC=metrics_ingestion+ ;;+cymbal)export RUST_LOG=debug,rdkafka=warnexport RUST_BACKTRACE=1diff --git a/devenv/intent-map.yaml b/devenv/intent-map.yamlindex 5d9e3797b027..1b359cf17bdd 100644--- a/devenv/intent-map.yaml+++ b/devenv/intent-map.yaml@@ -135,11 +135,21 @@ capabilities:requires: [event_ingestion]docker_profiles: [observability]+ nodejs_metrics:+ description: 'Node.js Metrics - metric ingestion'+ requires: [event_ingestion]+ docker_profiles: [observability]+nodejs_traces:description: 'Node.js Traces - trace ingestion'requires: [event_ingestion]docker_profiles: [observability]+ logs_ingestion:+ description: 'OTEL logs, traces, and metrics capture service'+ requires: [event_ingestion]+ docker_profiles: [observability]+nodejs_feature_flags:description: 'Node.js Feature Flags - evaluation scheduler'requires: [flag_evaluation]@@ -292,7 +302,11 @@ intents:logs:description: 'Log aggregation and viewing'- capabilities: [event_ingestion, property_definitions, nodejs_logs, nodejs_traces]+ capabilities: [event_ingestion, property_definitions, logs_ingestion, nodejs_logs, nodejs_traces]++ metrics:+ description: 'Metric ingestion and viewing'+ capabilities: [event_ingestion, property_definitions, logs_ingestion, nodejs_metrics]workflows:description: 'Workflow automation and orchestration'diff --git a/docker-compose.base.yml b/docker-compose.base.ymlindex 501fb924c595..a5ab078a0648 100644--- a/docker-compose.base.yml+++ b/docker-compose.base.yml@@ -53,6 +53,9 @@ services:path /i/v1/tracespath /i/v1/traces/path /i/v1/traces/*+ path /i/v1/metrics+ path /i/v1/metrics/+ path /i/v1/metrics/*}@flags {@@ -342,6 +345,7 @@ services:KAFKA_HOSTS: kafka:9092JWT_SECRET: '<randomly generated secret key>'KAFKA_TOPIC: logs_ingestion+ KAFKA_METRICS_TOPIC: metrics_ingestionnetworks:- otel_network- defaultdiff --git a/docker-compose.dev.yml b/docker-compose.dev.ymlindex 50e52f2e79a6..dd5059d6800b 100644--- a/docker-compose.dev.yml+++ b/docker-compose.dev.yml@@ -25,6 +25,7 @@ services:- 'plugins:host-gateway'- 'capture:host-gateway'- 'capture-ai:host-gateway'+ - 'capture-logs:host-gateway'- 'replay-capture:host-gateway'- 'feature-flags:host-gateway'- 'hypercache-server:host-gateway'@@ -58,6 +59,8 @@ services:@capture-logs {path /i/v1/logs+ path /i/v1/traces+ path /i/v1/metrics}@flags {@@ -92,7 +95,7 @@ services:}handle @capture-logs {- reverse_proxy capture-logs:4318+ reverse_proxy capture-logs:4320}handle @replay-capture {@@ -570,16 +573,10 @@ services:# Used by otel-collector-config.dev.yaml to scope container log# collection to this compose project only.COMPOSE_PROJECT: posthog+ extra_hosts:+ - 'host.docker.internal:host-gateway'depends_on:- jaeger- - capture-logs-- capture-logs:- extends:- file: docker-compose.base.yml- service: capture-logs- depends_on:- - kafkajaeger:extends:diff --git a/docker-compose.profiles.yml b/docker-compose.profiles.ymlindex 31c351448ed4..81c08777f8c0 100644--- a/docker-compose.profiles.yml+++ b/docker-compose.profiles.yml@@ -33,8 +33,6 @@ services:profiles: [observability]jaeger:profiles: [observability]- capture-logs:- profiles: [observability]# Dev tools - debugging and monitoring UIskafka_ui:diff --git a/hogli.yaml b/hogli.yamlindex c893039b7393..16ff0ee3ebd1 100644--- a/hogli.yaml+++ b/hogli.yaml@@ -837,7 +837,11 @@ tools:hidden: trueclickhouse:logs:init:bin_script: clickhouse-logs-init- description: 'TODO: add description for clickhouse-logs-init'+ description: Initialize ClickHouse logs schema (temporary, pre-migration)+ hidden: true+ clickhouse:metrics:init:+ bin_script: clickhouse-metrics-init+ description: Initialize ClickHouse metrics schema (temporary, pre-migration)hidden: truecreate:notebook:node:bin_script: create-notebook-node.shdiff --git a/nodejs/src/capabilities.ts b/nodejs/src/capabilities.tsindex ebdd3af956ca..9433c23d1823 100644--- a/nodejs/src/capabilities.ts+++ b/nodejs/src/capabilities.ts@@ -147,6 +147,7 @@ export function getPluginServerCapabilities(evaluationScheduler: true,}case PluginServerMode.ingestion_logs:+ case PluginServerMode.ingestion_metrics:case PluginServerMode.ingestion_traces:throw new Error(`Mode ${mode} is handled by a dedicated server, not PluginServer`)case PluginServerMode.ingestion_error_tracking:diff --git a/nodejs/src/common/config.ts b/nodejs/src/common/config.tsindex 8c23e3955fb8..40723cd0594c 100644--- a/nodejs/src/common/config.ts+++ b/nodejs/src/common/config.ts@@ -30,6 +30,7 @@ export enum PluginServerMode {evaluation_scheduler = 'evaluation-scheduler',ingestion_logs = 'ingestion-logs',ingestion_error_tracking = 'ingestion-errortracking',+ ingestion_metrics = 'ingestion-metrics',cdp_batch_hogflow_requests = 'cdp-batch-hogflow-requests',cdp_cyclotron_v2_janitor = 'cdp-cyclotron-v2-janitor',recording_api = 'recording-api',diff --git a/nodejs/src/common/services/quota-limiting.service.ts b/nodejs/src/common/services/quota-limiting.service.tsindex 61f914f2ad84..9313d2ab4abc 100644--- a/nodejs/src/common/services/quota-limiting.service.ts+++ b/nodejs/src/common/services/quota-limiting.service.ts@@ -11,6 +11,7 @@ export type QuotaResource =| 'workflow_emails'| 'workflow_destinations_dispatched'| 'logs_mb_ingested'+ | 'metrics_mb_ingested'export const QUOTA_LIMITER_CACHE_KEY = '@posthog/quota-limits/'diff --git a/nodejs/src/config/config.ts b/nodejs/src/config/config.tsindex be8aeec94b04..f1b1e5409f2e 100644--- a/nodejs/src/config/config.ts+++ b/nodejs/src/config/config.ts@@ -13,6 +13,7 @@ import {getDefaultLogsIngestionConsumerConfig,getDefaultTracesIngestionConsumerConfig,} from '../logs-ingestion/config'+import { getDefaultMetricsIngestionConsumerConfig } from '../metrics-ingestion/config'import { getDefaultSessionRecordingApiConfig, getDefaultSessionRecordingConfig } from '../session-recording/config'import { PluginsServerConfig, ValueMatcher, stringToPluginServerMode } from '../types'import { stringToBoolean } from '../utils/env-utils'@@ -29,6 +30,7 @@ export function getDefaultConfig(): PluginsServerConfig {...getDefaultLlmAnalyticsConfig(),...getDefaultIngestionConsumerConfig(),...getDefaultLogsIngestionConsumerConfig(),+ ...getDefaultMetricsIngestionConsumerConfig(),...getDefaultTracesIngestionConsumerConfig(),...getDefaultErrorTrackingConsumerConfig(),...getDefaultSessionRecordingConfig(),diff --git a/nodejs/src/config/kafka-topics.ts b/nodejs/src/config/kafka-topics.tsindex 9eddad83beb8..7b31a97fc815 100644--- a/nodejs/src/config/kafka-topics.ts+++ b/nodejs/src/config/kafka-topics.ts@@ -76,6 +76,11 @@ export const KAFKA_TRACES_INGESTION = `${prefix}ingestion-traces${suffix}`export const KAFKA_TRACES_INGESTION_DLQ = `${prefix}ingestion-traces-dlq${suffix}`export const KAFKA_TRACES_INGESTION_OVERFLOW = `${prefix}ingestion-traces-overflow${suffix}`export const KAFKA_TRACES_CLICKHOUSE = `${prefix}clickhouse_traces${suffix}`+// Metrics ingestion topics+export const KAFKA_METRICS_INGESTION = `${prefix}metrics_ingestion${suffix}`+export const KAFKA_METRICS_INGESTION_DLQ = `${prefix}metrics_ingestion_dlq${suffix}`+export const KAFKA_METRICS_INGESTION_OVERFLOW = `${prefix}metrics_ingestion_overflow${suffix}`+export const KAFKA_METRICS_CLICKHOUSE = `${prefix}clickhouse_metrics${suffix}`// TopHog metricsexport const KAFKA_CLICKHOUSE_TOPHOG = `${prefix}clickhouse_tophog${suffix}`diff --git a/nodejs/src/index.ts b/nodejs/src/index.tsindex e68d38c69229..f561d7b9cec5 100644--- a/nodejs/src/index.ts+++ b/nodejs/src/index.ts@@ -8,6 +8,7 @@ import { ErrorTrackingServer } from '~/servers/error-tracking-server'import { IngestionApiServer } from '~/servers/ingestion-api-server'import { IngestionGeneralServer } from '~/servers/ingestion-general-server'import { IngestionLogsServer } from '~/servers/ingestion-logs-server'+import { IngestionMetricsServer } from '~/servers/ingestion-metrics-server'import { IngestionSessionReplayServer } from '~/servers/ingestion-session-replay-server'import { IngestionTracesServer } from '~/servers/ingestion-traces-server'import { RecordingApiServer } from '~/servers/recording-api-server'@@ -36,6 +37,9 @@ function createServer(): NodeServer {case PluginServerMode.ingestion_logs:return new IngestionLogsServer()+ case PluginServerMode.ingestion_metrics:+ return new IngestionMetricsServer()+case PluginServerMode.ingestion_traces:return new IngestionTracesServer()diff --git a/nodejs/src/metrics-ingestion/config.ts b/nodejs/src/metrics-ingestion/config.tsnew file mode 100644index 000000000000..fc6c868fcd65--- /dev/null+++ b/nodejs/src/metrics-ingestion/config.ts@@ -0,0 +1,76 @@+import {+ KAFKA_APP_METRICS_2,+ KAFKA_METRICS_CLICKHOUSE,+ KAFKA_METRICS_INGESTION,+ KAFKA_METRICS_INGESTION_DLQ,+ KAFKA_METRICS_INGESTION_OVERFLOW,+} from '../config/kafka-topics'+import { isProdEnv } from '../utils/env-utils'+import { MetricsProducerName, WARPSTREAM_INGESTION_PRODUCER, WARPSTREAM_METRICS_PRODUCER } from './outputs/producers'++export type MetricsIngestionOutputsConfig = {+ METRICS_INGESTION_OUTPUT_APP_METRICS_TOPIC: string+ METRICS_INGESTION_OUTPUT_APP_METRICS_PRODUCER: MetricsProducerName+ METRICS_INGESTION_OUTPUT_METRICS_PRODUCER: MetricsProducerName+ METRICS_INGESTION_OUTPUT_DLQ_PRODUCER: MetricsProducerName+}++export function getDefaultMetricsIngestionOutputsConfig(): MetricsIngestionOutputsConfig {+ return {+ METRICS_INGESTION_OUTPUT_APP_METRICS_TOPIC: KAFKA_APP_METRICS_2,+ METRICS_INGESTION_OUTPUT_APP_METRICS_PRODUCER: WARPSTREAM_INGESTION_PRODUCER,+ METRICS_INGESTION_OUTPUT_METRICS_PRODUCER: WARPSTREAM_METRICS_PRODUCER,+ METRICS_INGESTION_OUTPUT_DLQ_PRODUCER: WARPSTREAM_METRICS_PRODUCER,+ }+}++export type MetricsIngestionConsumerConfig = {+ METRICS_INGESTION_CONSUMER_GROUP_ID: string+ METRICS_INGESTION_CONSUMER_CONSUME_TOPIC: string+ METRICS_INGESTION_CONSUMER_OVERFLOW_TOPIC: string+ METRICS_INGESTION_CONSUMER_DLQ_TOPIC: string+ METRICS_INGESTION_CONSUMER_CLICKHOUSE_TOPIC: string+ METRICS_REDIS_HOST: string+ METRICS_REDIS_PORT: number+ METRICS_REDIS_PASSWORD: string+ METRICS_REDIS_TLS: boolean+ METRICS_LIMITER_ENABLED_TEAMS: string+ METRICS_LIMITER_DISABLED_FOR_TEAMS: string+ METRICS_LIMITER_BUCKET_SIZE_KB: number+ METRICS_LIMITER_REFILL_RATE_KB_PER_SECOND: number+ METRICS_LIMITER_TTL_SECONDS: number+ METRICS_LIMITER_TEAM_BUCKET_SIZE_KB: string+ METRICS_LIMITER_TEAM_REFILL_RATE_KB_PER_SECOND: string+ REDIS_URL: string+ REDIS_POOL_MIN_SIZE: number+ REDIS_POOL_MAX_SIZE: number+ KAFKA_CLIENT_RACK: string | undefined+}++export function getDefaultMetricsIngestionConsumerConfig(): MetricsIngestionConsumerConfig {+ return {+ METRICS_INGESTION_CONSUMER_GROUP_ID: 'ingestion-metrics',+ METRICS_INGESTION_CONSUMER_CONSUME_TOPIC: KAFKA_METRICS_INGESTION,+ METRICS_INGESTION_CONSUMER_OVERFLOW_TOPIC: KAFKA_METRICS_INGESTION_OVERFLOW,+ METRICS_INGESTION_CONSUMER_DLQ_TOPIC: KAFKA_METRICS_INGESTION_DLQ,+ METRICS_INGESTION_CONSUMER_CLICKHOUSE_TOPIC: KAFKA_METRICS_CLICKHOUSE,+ METRICS_REDIS_HOST: '127.0.0.1',+ METRICS_REDIS_PORT: 6379,+ METRICS_REDIS_PASSWORD: '',+ METRICS_REDIS_TLS: isProdEnv() ? true : false,+ METRICS_LIMITER_ENABLED_TEAMS: isProdEnv() ? '' : '*',+ METRICS_LIMITER_DISABLED_FOR_TEAMS: '',+ METRICS_LIMITER_BUCKET_SIZE_KB: 10000,+ METRICS_LIMITER_REFILL_RATE_KB_PER_SECOND: 1000,+ METRICS_LIMITER_TTL_SECONDS: 60 * 60 * 24,+ METRICS_LIMITER_TEAM_BUCKET_SIZE_KB: '',+ METRICS_LIMITER_TEAM_REFILL_RATE_KB_PER_SECOND: '',+ // Overlapping fields with CommonConfig, included for standalone usage+ // ok to connect to localhost over plaintext+ // nosemgrep: trailofbits.generic.redis-unencrypted-transport.redis-unencrypted-transport+ REDIS_URL: 'redis://127.0.0.1',+ REDIS_POOL_MIN_SIZE: 1,+ REDIS_POOL_MAX_SIZE: 3,+ KAFKA_CLIENT_RACK: undefined,+ }+}diff --git a/nodejs/src/metrics-ingestion/metrics-ingestion-consumer.ts b/nodejs/src/metrics-ingestion/metrics-ingestion-consumer.tsnew file mode 100644index 000000000000..f338856ae970--- /dev/null+++ b/nodejs/src/metrics-ingestion/metrics-ingestion-consumer.ts@@ -0,0 +1,472 @@+import { Message } from 'node-rdkafka'+import { Counter } from 'prom-client'++import { RedisV2, createRedisV2PoolFromConfig } from '~/common/redis/redis-v2'+import { AppMetricsAggregator } from '~/common/services/app-metrics-aggregator'+import { QuotaLimiting } from '~/common/services/quota-limiting.service'+import { instrumentFn, instrumented } from '~/common/tracing/tracing-utils'+import { AppMetricsOutput } from '~/ingestion/common/outputs'+import { IngestionOutputs } from '~/ingestion/outputs/ingestion-outputs'++import { KafkaConsumerInterface, createKafkaConsumer, parseKafkaHeaders } from '../kafka/consumer'+import { HealthCheckResult, PluginServerService } from '../types'+import { isDevEnv } from '../utils/env-utils'+import { logger } from '../utils/logger'+import { TeamManager } from '../utils/team-manager'+import { MetricsIngestionConsumerConfig } from './config'+import { METRICS_DLQ_OUTPUT, METRICS_OUTPUT, MetricsDlqOutput, MetricsOutput } from './outputs/outputs'+import { MetricsRateLimiterService } from './services/metrics-rate-limiter.service'+import { MetricsIngestionMessage } from './types'++export interface MetricsIngestionConsumerDeps {+ teamManager: TeamManager+ quotaLimiting: QuotaLimiting+ /**+ * Resolved outputs registry — must include `METRICS_OUTPUT`, `METRICS_DLQ_OUTPUT`,+ * and `APP_METRICS_OUTPUT`. The producer + topic for each is wired by the+ * server via env vars — this consumer never touches a `KafkaProducerWrapper`+ * directly.+ */+ outputs: IngestionOutputs<MetricsOutput | MetricsDlqOutput | AppMetricsOutput>+}++export type UsageStats = {+ bytesReceived: number+ recordsReceived: number+ bytesAllowed: number+ recordsAllowed: number+ bytesDropped: number+ recordsDropped: number+}++const DEFAULT_USAGE_STATS: UsageStats = {+ bytesReceived: 0,+ recordsReceived: 0,+ bytesAllowed: 0,+ recordsAllowed: 0,+ bytesDropped: 0,+ recordsDropped: 0,+}++export type UsageStatsByTeam = Map<number, UsageStats>++export const metricMessageDroppedCounter = new Counter({+ name: 'metrics_ingestion_message_dropped_count',+ help: 'The number of metrics ingestion messages dropped',+ labelNames: ['reason', 'team_id'],+})++export const metricMessageDlqCounter = new Counter({+ name: 'metrics_ingestion_message_dlq_count',+ help: 'The number of metrics ingestion messages sent to DLQ',+ labelNames: ['reason', 'team_id'],+})++export const metricsBytesReceivedCounter = new Counter({+ name: 'metrics_ingestion_bytes_received_total',+ help: 'Total uncompressed bytes received for metrics ingestion',+})++export const metricsBytesAllowedCounter = new Counter({+ name: 'metrics_ingestion_bytes_allowed_total',+ help: 'Total uncompressed bytes allowed through quota and rate limiting',+})++export const metricsBytesDroppedCounter = new Counter({+ name: 'metrics_ingestion_bytes_dropped_total',+ help: 'Total uncompressed bytes dropped due to quota or rate limiting',+ labelNames: ['team_id'],+})++export const metricsRecordsReceivedCounter = new Counter({+ name: 'metrics_ingestion_records_received_total',+ help: 'Total metric records received',+})++export const metricsRecordsAllowedCounter = new Counter({+ name: 'metrics_ingestion_records_allowed_total',+ help: 'Total metric records allowed through quota and rate limiting',+})++export const metricsRecordsDroppedCounter = new Counter({+ name: 'metrics_ingestion_records_dropped_total',+ help: 'Total metric records dropped due to quota or rate limiting',+ labelNames: ['team_id'],+})++export class MetricsIngestionConsumer {+ protected name = 'MetricsIngestionConsumer'+ protected kafkaConsumer: KafkaConsumerInterface+ private appMetricsAggregator: AppMetricsAggregator+ private redis: RedisV2+ private rateLimiter: MetricsRateLimiterService++ protected groupId: string+ protected topic: string++ constructor(+ config: MetricsIngestionConsumerConfig,+ private deps: MetricsIngestionConsumerDeps,+ overrides: Partial<MetricsIngestionConsumerConfig> = {}+ ) {+ this.groupId = overrides.METRICS_INGESTION_CONSUMER_GROUP_ID ?? config.METRICS_INGESTION_CONSUMER_GROUP_ID+ this.topic =+ overrides.METRICS_INGESTION_CONSUMER_CONSUME_TOPIC ?? config.METRICS_INGESTION_CONSUMER_CONSUME_TOPIC++ this.appMetricsAggregator = new AppMetricsAggregator(deps.outputs)++ this.kafkaConsumer = createKafkaConsumer({ groupId: this.groupId, topic: this.topic })+ this.redis = createRedisV2PoolFromConfig({+ connection:+ (overrides.METRICS_REDIS_HOST ?? config.METRICS_REDIS_HOST)+ ? {+ url: overrides.METRICS_REDIS_HOST ?? config.METRICS_REDIS_HOST,+ options: {+ port: overrides.METRICS_REDIS_PORT ?? config.METRICS_REDIS_PORT,+ tls: (overrides.METRICS_REDIS_TLS ?? config.METRICS_REDIS_TLS) ? {} : undefined,+ },+ name: 'metrics-redis',+ }+ : { url: config.REDIS_URL, name: 'metrics-redis-fallback' },+ poolMinSize: config.REDIS_POOL_MIN_SIZE,+ poolMaxSize: config.REDIS_POOL_MAX_SIZE,+ })+ this.rateLimiter = new MetricsRateLimiterService(+ { ...config, ...overrides } as MetricsIngestionConsumerConfig,+ this.redis+ )+ }++ public get service(): PluginServerService {+ return {+ id: this.name,+ onShutdown: async () => await this.stop(),+ healthcheck: () => this.isHealthy(),+ }+ }++ public async processBatch(+ messages: MetricsIngestionMessage[]+ ): Promise<{ backgroundTask?: Promise<any>; messages: MetricsIngestionMessage[] }> {+ if (!messages.length) {+ return { messages: [] }+ }++ this.trackIncomingTraffic(messages)++ const { quotaAllowedMessages, quotaDroppedMessages } = await this.filterQuotaLimitedMessages(messages)+ const { rateLimiterAllowedMessages, rateLimiterDroppedMessages } =+ await this.filterRateLimitedMessages(quotaAllowedMessages)++ const usageStats = this.trackOutgoingTrafficAndBuildUsageStats(rateLimiterAllowedMessages, [+ ...quotaDroppedMessages,+ ...rateLimiterDroppedMessages,+ ])++ return {+ backgroundTask: Promise.all([+ this.produceValidMetricMessages(rateLimiterAllowedMessages),+ this.emitUsageMetrics(usageStats),+ ]),+ messages: rateLimiterAllowedMessages,+ }+ }++ private trackIncomingTraffic(messages: MetricsIngestionMessage[]): void {+ let totalBytesReceived = 0+ let totalRecordsReceived = 0+ for (const message of messages) {+ totalBytesReceived += message.bytesUncompressed+ totalRecordsReceived += message.recordCount+ }+ metricsBytesReceivedCounter.inc(totalBytesReceived)+ metricsRecordsReceivedCounter.inc(totalRecordsReceived)+ }++ private trackOutgoingTrafficAndBuildUsageStats(+ allowedMessages: MetricsIngestionMessage[],+ droppedMessages: MetricsIngestionMessage[]+ ): UsageStatsByTeam {+ let totalBytesAllowed = 0+ let totalRecordsAllowed = 0+ const usageStats: UsageStatsByTeam = new Map()++ for (const message of allowedMessages) {+ const stats = usageStats.get(message.teamId) || { ...DEFAULT_USAGE_STATS }+ stats.bytesReceived += message.bytesUncompressed+ stats.recordsReceived += message.recordCount+ stats.bytesAllowed += message.bytesUncompressed+ stats.recordsAllowed += message.recordCount+ usageStats.set(message.teamId, stats)++ totalBytesAllowed += message.bytesUncompressed+ totalRecordsAllowed += message.recordCount+ }++ metricsBytesAllowedCounter.inc(totalBytesAllowed)+ metricsRecordsAllowedCounter.inc(totalRecordsAllowed)++ for (const message of droppedMessages) {+ const stats = usageStats.get(message.teamId) || { ...DEFAULT_USAGE_STATS }+ stats.bytesReceived += message.bytesUncompressed+ stats.recordsReceived += message.recordCount+ stats.bytesDropped += message.bytesUncompressed+ stats.recordsDropped += message.recordCount+ usageStats.set(message.teamId, stats)+ }++ for (const [teamId, stats] of usageStats) {+ const teamIdLabel = teamId.toString()+ if (stats.bytesDropped > 0) {+ metricsBytesDroppedCounter.inc({ team_id: teamIdLabel }, stats.bytesDropped)+ }+ if (stats.recordsDropped > 0) {+ metricsRecordsDroppedCounter.inc({ team_id: teamIdLabel }, stats.recordsDropped)+ }+ }++ return usageStats+ }++ private async filterQuotaLimitedMessages(messages: MetricsIngestionMessage[]): Promise<{+ quotaAllowedMessages: MetricsIngestionMessage[]+ quotaDroppedMessages: MetricsIngestionMessage[]+ }> {+ const quotaDroppedMessages: MetricsIngestionMessage[] = []+ const quotaAllowedMessages: MetricsIngestionMessage[] = []++ const uniqueTokens = [...new Set(messages.map((m) => m.token))]++ const quotaLimitedTokens = new Set(+ (+ await Promise.all(+ uniqueTokens.map(async (token) =>+ (await this.deps.quotaLimiting.isTeamTokenQuotaLimited(token, 'metrics_mb_ingested'))+ ? token+ : null+ )+ )+ ).filter((token): token is string => token !== null)+ )++ const droppedCountByTeam = new Map<number, number>()+ for (const message of messages) {+ if (quotaLimitedTokens.has(message.token)) {+ quotaDroppedMessages.push(message)+ droppedCountByTeam.set(message.teamId, (droppedCountByTeam.get(message.teamId) || 0) + 1)+ } else {+ quotaAllowedMessages.push(message)+ }+ }++ for (const [teamId, count] of droppedCountByTeam) {+ metricMessageDroppedCounter.inc({ reason: 'quota_limited', team_id: teamId.toString() }, count)+ }++ return { quotaAllowedMessages, quotaDroppedMessages }+ }++ private async filterRateLimitedMessages(messages: MetricsIngestionMessage[]): Promise<{+ rateLimiterAllowedMessages: MetricsIngestionMessage[]+ rateLimiterDroppedMessages: MetricsIngestionMessage[]+ }> {+ const { allowed, dropped } = await this.rateLimiter.filterMessages(messages)++ const droppedCountByTeam = new Map<number, number>()+ for (const message of dropped) {+ droppedCountByTeam.set(message.teamId, (droppedCountByTeam.get(message.teamId) || 0) + 1)+ }+ for (const [teamId, count] of droppedCountByTeam) {+ metricMessageDroppedCounter.inc({ reason: 'rate_limited', team_id: teamId.toString() }, count)+ }++ return { rateLimiterAllowedMessages: allowed, rateLimiterDroppedMessages: dropped }+ }++ private async produceValidMetricMessages(messages: MetricsIngestionMessage[]): Promise<void> {+ const results = await Promise.allSettled(+ messages.map(async (message) => {+ try {+ if (message.message.value === null) {+ return Promise.resolve()+ }++ // No enrichment needed for metrics — data is already structured numerically.+ // Just pass through the AVRO buffer as-is.+ await this.deps.outputs.queueMessages(METRICS_OUTPUT, [+ {+ value: message.message.value,+ key: null,+ headers: {+ ...parseKafkaHeaders(message.message.headers),+ token: message.token,+ team_id: message.teamId.toString(),+ },+ },+ ])+ } catch (error) {+ await this.produceToDlq(message, error)+ throw error+ }+ })+ )++ const failures = results.filter((r) => r.status === 'rejected')+ if (failures.length > 0) {+ logger.error('Failed to process some metric messages', {+ failureCount: failures.length,+ totalCount: messages.length,+ })+ }+ }++ private async produceToDlq(message: MetricsIngestionMessage, error: unknown): Promise<void> {+ const errorMessage = error instanceof Error ? error.message : String(error)+ const errorName = error instanceof Error ? error.name : 'UnknownError'++ metricMessageDlqCounter.inc({ reason: errorName, team_id: message.teamId.toString() })++ try {+ await this.deps.outputs.queueMessages(METRICS_DLQ_OUTPUT, [+ {+ value: message.message.value,+ key: null,+ headers: {+ ...parseKafkaHeaders(message.message.headers),+ token: message.token,+ team_id: message.teamId.toString(),+ error_message: errorMessage,+ error_name: errorName,+ failed_at: new Date().toISOString(),+ },+ },+ ])+ } catch (dlqError) {+ logger.error('Failed to produce message to DLQ', {+ error: dlqError,+ originalError: errorMessage,+ })+ }+ }++ private async emitUsageMetrics(usageStats: UsageStatsByTeam): Promise<void> {+ for (const [teamId, stats] of usageStats) {+ this.queueUsageMetric(teamId, 'bytes_received', stats.bytesReceived)+ this.queueUsageMetric(teamId, 'records_received', stats.recordsReceived)+ this.queueUsageMetric(teamId, 'bytes_ingested', stats.bytesAllowed)+ this.queueUsageMetric(teamId, 'records_ingested', stats.recordsAllowed)+ this.queueUsageMetric(teamId, 'bytes_dropped', stats.bytesDropped)+ this.queueUsageMetric(teamId, 'records_dropped', stats.recordsDropped)+ }++ // Best-effort: don't let metric failures block ingestion+ try {+ await this.appMetricsAggregator.flush()+ } catch (error) {+ logger.error('🔴', 'Failed to emit usage metrics - billing data may be lost', { error })+ }+ }++ private queueUsageMetric(teamId: number, metricName: string, count: number): void {+ if (count === 0) {+ return+ }+ this.appMetricsAggregator.queue({+ team_id: teamId,+ app_source: 'metrics',+ app_source_id: '',+ instance_id: '',+ metric_kind: 'usage',+ metric_name: metricName,+ count,+ })+ }++ @instrumented('metricsIngestionConsumer.handleEachBatch.parseKafkaMessages')+ public async _parseKafkaBatch(messages: Message[]): Promise<MetricsIngestionMessage[]> {+ const events: MetricsIngestionMessage[] = []++ await Promise.all(+ messages.map(async (message) => {+ try {+ const headers = parseKafkaHeaders(message.headers)+ const token = headers.token++ if (!token) {+ logger.error('missing_token')+ metricMessageDroppedCounter.inc({ reason: 'missing_token', team_id: 'unknown' })+ return+ }++ let team+ try {+ if (isDevEnv() && token === 'phc_local') {+ // phc_local is a special token used in dev to refer to team 1+ team = await this.deps.teamManager.getTeam(1)+ } else {+ team = await this.deps.teamManager.getTeamByToken(token)+ }+ } catch (e) {+ logger.error('team_lookup_error', { error: e })+ metricMessageDroppedCounter.inc({ reason: 'team_lookup_error', team_id: 'unknown' })+ return+ }++ if (!team) {+ logger.error('team_not_found', { token_with_no_team: token })+ metricMessageDroppedCounter.inc({ reason: 'team_not_found', team_id: 'unknown' })+ return+ }++ const bytesUncompressed = parseInt(headers.bytes_uncompressed ?? '0', 10)+ const bytesCompressed = parseInt(headers.bytes_compressed ?? '0', 10)+ const recordCount = parseInt(headers.record_count ?? '0', 10)++ events.push({+ token,+ message,+ teamId: team.id,+ bytesUncompressed,+ bytesCompressed,+ recordCount,+ })+ } catch (e) {+ logger.error('Error parsing message', e)+ metricMessageDroppedCounter.inc({ reason: 'parse_error', team_id: 'unknown' })+ return+ }+ })+ )++ return events+ }++ public async processKafkaBatch(+ messages: Message[]+ ): Promise<{ backgroundTask?: Promise<any>; messages: MetricsIngestionMessage[] }> {+ const events = await this._parseKafkaBatch(messages)+ return await this.processBatch(events)+ }++ public async start(): Promise<void> {+ await this.kafkaConsumer.connect(async (messages) => {+ logger.info('🔁', `${this.name} - handling batch`, {+ size: messages.length,+ })++ return await instrumentFn('metricsIngestionConsumer.handleEachBatch', async () => {+ return await this.processKafkaBatch(messages)+ })+ })+ }++ public async stop(): Promise<void> {+ logger.info('💤', 'Stopping metrics consumer...')+ await this.kafkaConsumer.disconnect()+ logger.info('💤', 'Metrics consumer stopped!')+ }++ public isHealthy(): HealthCheckResult {+ return this.kafkaConsumer.isHealthy()+ }+}diff --git a/nodejs/src/metrics-ingestion/outputs/outputs.ts b/nodejs/src/metrics-ingestion/outputs/outputs.tsnew file mode 100644index 000000000000..300c18e4c641--- /dev/null+++ b/nodejs/src/metrics-ingestion/outputs/outputs.ts@@ -0,0 +1,9 @@+/**+ * Output names registered by the metrics ingestion deployment.+ */++export const METRICS_OUTPUT = 'metrics' as const+export type MetricsOutput = typeof METRICS_OUTPUT++export const METRICS_DLQ_OUTPUT = 'metrics_dlq' as const+export type MetricsDlqOutput = typeof METRICS_DLQ_OUTPUTdiff --git a/nodejs/src/metrics-ingestion/outputs/producer-registry.ts b/nodejs/src/metrics-ingestion/outputs/producer-registry.tsnew file mode 100644index 000000000000..2169f56449d6--- /dev/null+++ b/nodejs/src/metrics-ingestion/outputs/producer-registry.ts@@ -0,0 +1,20 @@+import { KafkaProducerRegistryBuilder } from '../../ingestion/outputs/kafka-producer-registry-builder'+import {+ WARPSTREAM_INGESTION_PRODUCER,+ WARPSTREAM_INGESTION_PRODUCER_CONFIG_MAP,+ WARPSTREAM_METRICS_PRODUCER,+ WARPSTREAM_METRICS_PRODUCER_CONFIG_MAP,+} from './producers'++/**+ * Producers used by the metrics ingestion deployment.+ *+ * - `WARPSTREAM_METRICS_PRODUCER` — main metrics data path (Warpstream metrics cluster).+ * - `WARPSTREAM_INGESTION_PRODUCER` — destination for app_metrics rows on the+ * shared ingestion Warpstream cluster.+ */+export function createProducerRegistry(kafkaClientRack: string | undefined) {+ return new KafkaProducerRegistryBuilder(kafkaClientRack)+ .register(WARPSTREAM_METRICS_PRODUCER, WARPSTREAM_METRICS_PRODUCER_CONFIG_MAP)+ .register(WARPSTREAM_INGESTION_PRODUCER, WARPSTREAM_INGESTION_PRODUCER_CONFIG_MAP)+}diff --git a/nodejs/src/metrics-ingestion/outputs/producers.ts b/nodejs/src/metrics-ingestion/outputs/producers.tsnew file mode 100644index 000000000000..93eb5fc0a265--- /dev/null+++ b/nodejs/src/metrics-ingestion/outputs/producers.ts@@ -0,0 +1,169 @@+/**+ * Metrics ingestion producer names + their typed env-var config.+ *+ * Each producer is named explicitly after the cluster it targets, and its env+ * vars share the same prefix so deployment config is unambiguous (e.g.+ * `WARPSTREAM_METRICS_PRODUCER` ↔ `KAFKA_WARPSTREAM_METRICS_PRODUCER_*`).+ */+import { AllowedConfigKey } from '../../ingestion/outputs/kafka-producer-config'++/**+ * Targets the Warpstream cluster dedicated to metrics. The main metrics data+ * path produces here.+ */+export const WARPSTREAM_METRICS_PRODUCER = 'WARPSTREAM_METRICS_PRODUCER' as const+export type WarpstreamMetricsProducer = typeof WARPSTREAM_METRICS_PRODUCER++/** Targets the Warpstream cluster shared with the rest of ingestion. App metrics produce here. */+export const WARPSTREAM_INGESTION_PRODUCER = 'WARPSTREAM_INGESTION_PRODUCER' as const+export type WarpstreamIngestionProducer = typeof WARPSTREAM_INGESTION_PRODUCER++/** Producer names registered by the metrics deployment. */+export type MetricsProducerName = WarpstreamMetricsProducer | WarpstreamIngestionProducer++/** Cluster-named env var prefix mirroring the producer it configures. */+export const WARPSTREAM_METRICS_PRODUCER_CONFIG_MAP = {+ 'client.id': 'KAFKA_WARPSTREAM_METRICS_PRODUCER_CLIENT_ID',+ 'metadata.broker.list': 'KAFKA_WARPSTREAM_METRICS_PRODUCER_METADATA_BROKER_LIST',+ 'security.protocol': 'KAFKA_WARPSTREAM_METRICS_PRODUCER_SECURITY_PROTOCOL',+ 'sasl.mechanisms': 'KAFKA_WARPSTREAM_METRICS_PRODUCER_SASL_MECHANISMS',+ 'sasl.username': 'KAFKA_WARPSTREAM_METRICS_PRODUCER_SASL_USERNAME',+ 'sasl.password': 'KAFKA_WARPSTREAM_METRICS_PRODUCER_SASL_PASSWORD',+ 'compression.codec': 'KAFKA_WARPSTREAM_METRICS_PRODUCER_COMPRESSION_CODEC',+ 'linger.ms': 'KAFKA_WARPSTREAM_METRICS_PRODUCER_LINGER_MS',+ 'batch.size': 'KAFKA_WARPSTREAM_METRICS_PRODUCER_BATCH_SIZE',+ 'queue.buffering.max.messages': 'KAFKA_WARPSTREAM_METRICS_PRODUCER_QUEUE_BUFFERING_MAX_MESSAGES',+ 'queue.buffering.max.kbytes': 'KAFKA_WARPSTREAM_METRICS_PRODUCER_QUEUE_BUFFERING_MAX_KBYTES',+ 'enable.ssl.certificate.verification': 'KAFKA_WARPSTREAM_METRICS_PRODUCER_ENABLE_SSL_CERTIFICATE_VERIFICATION',+ 'enable.idempotence': 'KAFKA_WARPSTREAM_METRICS_PRODUCER_ENABLE_IDEMPOTENCE',+ 'message.max.bytes': 'KAFKA_WARPSTREAM_METRICS_PRODUCER_MESSAGE_MAX_BYTES',+ 'batch.num.messages': 'KAFKA_WARPSTREAM_METRICS_PRODUCER_BATCH_NUM_MESSAGES',+ 'sticky.partitioning.linger.ms': 'KAFKA_WARPSTREAM_METRICS_PRODUCER_STICKY_PARTITIONING_LINGER_MS',+ 'topic.metadata.refresh.interval.ms': 'KAFKA_WARPSTREAM_METRICS_PRODUCER_TOPIC_METADATA_REFRESH_INTERVAL_MS',+ 'metadata.max.age.ms': 'KAFKA_WARPSTREAM_METRICS_PRODUCER_METADATA_MAX_AGE_MS',+ 'message.send.max.retries': 'KAFKA_WARPSTREAM_METRICS_PRODUCER_RETRIES',+ 'max.in.flight.requests.per.connection': 'KAFKA_WARPSTREAM_METRICS_PRODUCER_MAX_IN_FLIGHT_REQUESTS_PER_CONNECTION',+} as const satisfies Partial<Record<AllowedConfigKey, string>>++/** Typed env vars referenced by `WARPSTREAM_METRICS_PRODUCER_CONFIG_MAP`. */+export type KafkaWarpstreamMetricsProducerEnvConfig = {+ KAFKA_WARPSTREAM_METRICS_PRODUCER_CLIENT_ID: string+ KAFKA_WARPSTREAM_METRICS_PRODUCER_METADATA_BROKER_LIST: string+ KAFKA_WARPSTREAM_METRICS_PRODUCER_SECURITY_PROTOCOL: string+ KAFKA_WARPSTREAM_METRICS_PRODUCER_SASL_MECHANISMS: string+ KAFKA_WARPSTREAM_METRICS_PRODUCER_SASL_USERNAME: string+ KAFKA_WARPSTREAM_METRICS_PRODUCER_SASL_PASSWORD: string+ KAFKA_WARPSTREAM_METRICS_PRODUCER_COMPRESSION_CODEC: string+ KAFKA_WARPSTREAM_METRICS_PRODUCER_LINGER_MS: string+ KAFKA_WARPSTREAM_METRICS_PRODUCER_BATCH_SIZE: string+ KAFKA_WARPSTREAM_METRICS_PRODUCER_QUEUE_BUFFERING_MAX_MESSAGES: string+ KAFKA_WARPSTREAM_METRICS_PRODUCER_QUEUE_BUFFERING_MAX_KBYTES: string+ KAFKA_WARPSTREAM_METRICS_PRODUCER_ENABLE_SSL_CERTIFICATE_VERIFICATION: string+ KAFKA_WARPSTREAM_METRICS_PRODUCER_ENABLE_IDEMPOTENCE: string+ KAFKA_WARPSTREAM_METRICS_PRODUCER_MESSAGE_MAX_BYTES: string+ KAFKA_WARPSTREAM_METRICS_PRODUCER_BATCH_NUM_MESSAGES: string+ KAFKA_WARPSTREAM_METRICS_PRODUCER_STICKY_PARTITIONING_LINGER_MS: string+ KAFKA_WARPSTREAM_METRICS_PRODUCER_TOPIC_METADATA_REFRESH_INTERVAL_MS: string+ KAFKA_WARPSTREAM_METRICS_PRODUCER_METADATA_MAX_AGE_MS: string+ KAFKA_WARPSTREAM_METRICS_PRODUCER_RETRIES: string+ KAFKA_WARPSTREAM_METRICS_PRODUCER_MAX_IN_FLIGHT_REQUESTS_PER_CONNECTION: string+}++export function getDefaultKafkaWarpstreamMetricsProducerEnvConfig(): KafkaWarpstreamMetricsProducerEnvConfig {+ return {+ KAFKA_WARPSTREAM_METRICS_PRODUCER_CLIENT_ID: '',+ KAFKA_WARPSTREAM_METRICS_PRODUCER_METADATA_BROKER_LIST: '',+ KAFKA_WARPSTREAM_METRICS_PRODUCER_SECURITY_PROTOCOL: '',+ KAFKA_WARPSTREAM_METRICS_PRODUCER_SASL_MECHANISMS: '',+ KAFKA_WARPSTREAM_METRICS_PRODUCER_SASL_USERNAME: '',+ KAFKA_WARPSTREAM_METRICS_PRODUCER_SASL_PASSWORD: '',+ KAFKA_WARPSTREAM_METRICS_PRODUCER_COMPRESSION_CODEC: '',+ KAFKA_WARPSTREAM_METRICS_PRODUCER_LINGER_MS: '',+ KAFKA_WARPSTREAM_METRICS_PRODUCER_BATCH_SIZE: '',+ KAFKA_WARPSTREAM_METRICS_PRODUCER_QUEUE_BUFFERING_MAX_MESSAGES: '',+ KAFKA_WARPSTREAM_METRICS_PRODUCER_QUEUE_BUFFERING_MAX_KBYTES: '',+ KAFKA_WARPSTREAM_METRICS_PRODUCER_ENABLE_SSL_CERTIFICATE_VERIFICATION: '',+ KAFKA_WARPSTREAM_METRICS_PRODUCER_ENABLE_IDEMPOTENCE: '',+ KAFKA_WARPSTREAM_METRICS_PRODUCER_MESSAGE_MAX_BYTES: '',+ KAFKA_WARPSTREAM_METRICS_PRODUCER_BATCH_NUM_MESSAGES: '',+ KAFKA_WARPSTREAM_METRICS_PRODUCER_STICKY_PARTITIONING_LINGER_MS: '',+ KAFKA_WARPSTREAM_METRICS_PRODUCER_TOPIC_METADATA_REFRESH_INTERVAL_MS: '',+ KAFKA_WARPSTREAM_METRICS_PRODUCER_METADATA_MAX_AGE_MS: '',+ KAFKA_WARPSTREAM_METRICS_PRODUCER_RETRIES: '',+ KAFKA_WARPSTREAM_METRICS_PRODUCER_MAX_IN_FLIGHT_REQUESTS_PER_CONNECTION: '',+ }+}++/** Cluster-named env var prefix mirroring the producer it configures. */+export const WARPSTREAM_INGESTION_PRODUCER_CONFIG_MAP = {+ 'client.id': 'KAFKA_WARPSTREAM_INGESTION_PRODUCER_CLIENT_ID',+ 'metadata.broker.list': 'KAFKA_WARPSTREAM_INGESTION_PRODUCER_METADATA_BROKER_LIST',+ 'security.protocol': 'KAFKA_WARPSTREAM_INGESTION_PRODUCER_SECURITY_PROTOCOL',+ 'sasl.mechanisms': 'KAFKA_WARPSTREAM_INGESTION_PRODUCER_SASL_MECHANISMS',+ 'sasl.username': 'KAFKA_WARPSTREAM_INGESTION_PRODUCER_SASL_USERNAME',+ 'sasl.password': 'KAFKA_WARPSTREAM_INGESTION_PRODUCER_SASL_PASSWORD',+ 'compression.codec': 'KAFKA_WARPSTREAM_INGESTION_PRODUCER_COMPRESSION_CODEC',+ 'linger.ms': 'KAFKA_WARPSTREAM_INGESTION_PRODUCER_LINGER_MS',+ 'batch.size': 'KAFKA_WARPSTREAM_INGESTION_PRODUCER_BATCH_SIZE',+ 'queue.buffering.max.messages': 'KAFKA_WARPSTREAM_INGESTION_PRODUCER_QUEUE_BUFFERING_MAX_MESSAGES',+ 'queue.buffering.max.kbytes': 'KAFKA_WARPSTREAM_INGESTION_PRODUCER_QUEUE_BUFFERING_MAX_KBYTES',+ 'enable.ssl.certificate.verification': 'KAFKA_WARPSTREAM_INGESTION_PRODUCER_ENABLE_SSL_CERTIFICATE_VERIFICATION',+ 'enable.idempotence': 'KAFKA_WARPSTREAM_INGESTION_PRODUCER_ENABLE_IDEMPOTENCE',+ 'message.max.bytes': 'KAFKA_WARPSTREAM_INGESTION_PRODUCER_MESSAGE_MAX_BYTES',+ 'batch.num.messages': 'KAFKA_WARPSTREAM_INGESTION_PRODUCER_BATCH_NUM_MESSAGES',+ 'sticky.partitioning.linger.ms': 'KAFKA_WARPSTREAM_INGESTION_PRODUCER_STICKY_PARTITIONING_LINGER_MS',+ 'topic.metadata.refresh.interval.ms': 'KAFKA_WARPSTREAM_INGESTION_PRODUCER_TOPIC_METADATA_REFRESH_INTERVAL_MS',+ 'metadata.max.age.ms': 'KAFKA_WARPSTREAM_INGESTION_PRODUCER_METADATA_MAX_AGE_MS',+ 'message.send.max.retries': 'KAFKA_WARPSTREAM_INGESTION_PRODUCER_RETRIES',+ 'max.in.flight.requests.per.connection':+ 'KAFKA_WARPSTREAM_INGESTION_PRODUCER_MAX_IN_FLIGHT_REQUESTS_PER_CONNECTION',+} as const satisfies Partial<Record<AllowedConfigKey, string>>++/** Typed env vars referenced by `WARPSTREAM_INGESTION_PRODUCER_CONFIG_MAP`. */+export type KafkaWarpstreamIngestionProducerEnvConfig = {+ KAFKA_WARPSTREAM_INGESTION_PRODUCER_CLIENT_ID: string+ KAFKA_WARPSTREAM_INGESTION_PRODUCER_METADATA_BROKER_LIST: string+ KAFKA_WARPSTREAM_INGESTION_PRODUCER_SECURITY_PROTOCOL: string+ KAFKA_WARPSTREAM_INGESTION_PRODUCER_SASL_MECHANISMS: string+ KAFKA_WARPSTREAM_INGESTION_PRODUCER_SASL_USERNAME: string+ KAFKA_WARPSTREAM_INGESTION_PRODUCER_SASL_PASSWORD: string+ KAFKA_WARPSTREAM_INGESTION_PRODUCER_COMPRESSION_CODEC: string+ KAFKA_WARPSTREAM_INGESTION_PRODUCER_LINGER_MS: string+ KAFKA_WARPSTREAM_INGESTION_PRODUCER_BATCH_SIZE: string+ KAFKA_WARPSTREAM_INGESTION_PRODUCER_QUEUE_BUFFERING_MAX_MESSAGES: string+ KAFKA_WARPSTREAM_INGESTION_PRODUCER_QUEUE_BUFFERING_MAX_KBYTES: string+ KAFKA_WARPSTREAM_INGESTION_PRODUCER_ENABLE_SSL_CERTIFICATE_VERIFICATION: string+ KAFKA_WARPSTREAM_INGESTION_PRODUCER_ENABLE_IDEMPOTENCE: string+ KAFKA_WARPSTREAM_INGESTION_PRODUCER_MESSAGE_MAX_BYTES: string+ KAFKA_WARPSTREAM_INGESTION_PRODUCER_BATCH_NUM_MESSAGES: string+ KAFKA_WARPSTREAM_INGESTION_PRODUCER_STICKY_PARTITIONING_LINGER_MS: string+ KAFKA_WARPSTREAM_INGESTION_PRODUCER_TOPIC_METADATA_REFRESH_INTERVAL_MS: string+ KAFKA_WARPSTREAM_INGESTION_PRODUCER_METADATA_MAX_AGE_MS: string+ KAFKA_WARPSTREAM_INGESTION_PRODUCER_RETRIES: string+ KAFKA_WARPSTREAM_INGESTION_PRODUCER_MAX_IN_FLIGHT_REQUESTS_PER_CONNECTION: string+}++export function getDefaultKafkaWarpstreamIngestionProducerEnvConfig(): KafkaWarpstreamIngestionProducerEnvConfig {+ return {+ KAFKA_WARPSTREAM_INGESTION_PRODUCER_CLIENT_ID: '',+ KAFKA_WARPSTREAM_INGESTION_PRODUCER_METADATA_BROKER_LIST: '',+ KAFKA_WARPSTREAM_INGESTION_PRODUCER_SECURITY_PROTOCOL: '',+ KAFKA_WARPSTREAM_INGESTION_PRODUCER_SASL_MECHANISMS: '',+ KAFKA_WARPSTREAM_INGESTION_PRODUCER_SASL_USERNAME: '',+ KAFKA_WARPSTREAM_INGESTION_PRODUCER_SASL_PASSWORD: '',+ KAFKA_WARPSTREAM_INGESTION_PRODUCER_COMPRESSION_CODEC: '',+ KAFKA_WARPSTREAM_INGESTION_PRODUCER_LINGER_MS: '',+ KAFKA_WARPSTREAM_INGESTION_PRODUCER_BATCH_SIZE: '',+ KAFKA_WARPSTREAM_INGESTION_PRODUCER_QUEUE_BUFFERING_MAX_MESSAGES: '',+ KAFKA_WARPSTREAM_INGESTION_PRODUCER_QUEUE_BUFFERING_MAX_KBYTES: '',+ KAFKA_WARPSTREAM_INGESTION_PRODUCER_ENABLE_SSL_CERTIFICATE_VERIFICATION: '',+ KAFKA_WARPSTREAM_INGESTION_PRODUCER_ENABLE_IDEMPOTENCE: '',+ KAFKA_WARPSTREAM_INGESTION_PRODUCER_MESSAGE_MAX_BYTES: '',+ KAFKA_WARPSTREAM_INGESTION_PRODUCER_BATCH_NUM_MESSAGES: '',+ KAFKA_WARPSTREAM_INGESTION_PRODUCER_STICKY_PARTITIONING_LINGER_MS: '',+ KAFKA_WARPSTREAM_INGESTION_PRODUCER_TOPIC_METADATA_REFRESH_INTERVAL_MS: '',+ KAFKA_WARPSTREAM_INGESTION_PRODUCER_METADATA_MAX_AGE_MS: '',+ KAFKA_WARPSTREAM_INGESTION_PRODUCER_RETRIES: '',+ KAFKA_WARPSTREAM_INGESTION_PRODUCER_MAX_IN_FLIGHT_REQUESTS_PER_CONNECTION: '',+ }+}diff --git a/nodejs/src/metrics-ingestion/outputs/registry.ts b/nodejs/src/metrics-ingestion/outputs/registry.tsnew file mode 100644index 000000000000..9cb7f188a8c4--- /dev/null+++ b/nodejs/src/metrics-ingestion/outputs/registry.ts@@ -0,0 +1,29 @@+import { APP_METRICS_OUTPUT } from '../../ingestion/common/outputs'+import { IngestionOutputsBuilder } from '../../ingestion/outputs/ingestion-outputs-builder'+import { METRICS_DLQ_OUTPUT, METRICS_OUTPUT } from './outputs'++/**+ * Outputs for the metrics ingestion deployment.+ *+ * - `METRICS_OUTPUT` — main metrics data path → topic from `METRICS_INGESTION_CONSUMER_CLICKHOUSE_TOPIC`.+ * - `METRICS_DLQ_OUTPUT` — DLQ for failed messages → topic from `METRICS_INGESTION_CONSUMER_DLQ_TOPIC`.+ * - `APP_METRICS_OUTPUT` — usage metrics → topic from `METRICS_INGESTION_OUTPUT_APP_METRICS_TOPIC`.+ *+ * Per-output producer is env-controlled (`*_PRODUCER` keys) so the route can be+ * flipped between Warpstream-metrics / Warpstream-ingestion without code changes.+ */+export function createMetricsOutputsRegistry() {+ return new IngestionOutputsBuilder()+ .register(APP_METRICS_OUTPUT, {+ topicKey: 'METRICS_INGESTION_OUTPUT_APP_METRICS_TOPIC',+ producerKey: 'METRICS_INGESTION_OUTPUT_APP_METRICS_PRODUCER',+ })+ .register(METRICS_OUTPUT, {+ topicKey: 'METRICS_INGESTION_CONSUMER_CLICKHOUSE_TOPIC',+ producerKey: 'METRICS_INGESTION_OUTPUT_METRICS_PRODUCER',+ })+ .register(METRICS_DLQ_OUTPUT, {+ topicKey: 'METRICS_INGESTION_CONSUMER_DLQ_TOPIC',+ producerKey: 'METRICS_INGESTION_OUTPUT_DLQ_PRODUCER',+ })+}diff --git a/nodejs/src/metrics-ingestion/services/metrics-rate-limiter.service.ts b/nodejs/src/metrics-ingestion/services/metrics-rate-limiter.service.tsnew file mode 100644index 000000000000..e5c0271d3218--- /dev/null+++ b/nodejs/src/metrics-ingestion/services/metrics-rate-limiter.service.ts@@ -0,0 +1,249 @@+import { Histogram } from 'prom-client'++import { RedisV2, getRedisPipelineResults } from '~/common/redis/redis-v2'++import { MetricsIngestionConsumerConfig } from '../config'+import { MetricsIngestionMessage } from '../types'++const msToSeconds = (ms: number): number => Math.round(ms / 1000)+const bytesToKb = (bytes: number): number => Math.ceil(bytes / 1000)++export const metricsMessageLagHistogram = new Histogram({+ name: 'metrics_rate_limiter_message_lag_seconds',+ help: 'Lag between message observed timestamp and wall clock time (seconds)',+ buckets: [-60, 0, 1, 5, 10, 30, 60, 300, 600, 1800, 3600],+})++export type MetricsRateLimiterConfig = Pick<+ MetricsIngestionConsumerConfig,+ | 'METRICS_LIMITER_TEAM_BUCKET_SIZE_KB'+ | 'METRICS_LIMITER_TEAM_REFILL_RATE_KB_PER_SECOND'+ | 'METRICS_LIMITER_DISABLED_FOR_TEAMS'+ | 'METRICS_LIMITER_ENABLED_TEAMS'+ | 'METRICS_LIMITER_BUCKET_SIZE_KB'+ | 'METRICS_LIMITER_REFILL_RATE_KB_PER_SECOND'+ | 'METRICS_LIMITER_TTL_SECONDS'+>++export const BASE_REDIS_KEY =+ process.env.NODE_ENV == 'test' ? '@posthog-test/metrics-rate-limiter' : '@posthog/metrics-rate-limiter'+const REDIS_KEY_TOKENS = `${BASE_REDIS_KEY}/tokens`++export type MetricsRateLimit = {+ tokensBefore: number+ tokensAfter: number+ isRateLimited: boolean+}++export type FilteredMessages = {+ allowed: MetricsIngestionMessage[]+ dropped: MetricsIngestionMessage[]+}++export class MetricsRateLimiterService {+ private teamBucketSizes: Map<number, number>+ private teamRefillRates: Map<number, number>+ private disabledTeamIds: Set<number> | '*' | null+ private enabledTeamIds: Set<number> | '*' | null++ constructor(+ private config: MetricsRateLimiterConfig,+ private redis: RedisV2+ ) {+ this.teamBucketSizes = this.parseTeamConfig(config.METRICS_LIMITER_TEAM_BUCKET_SIZE_KB)+ this.teamRefillRates = this.parseTeamConfig(config.METRICS_LIMITER_TEAM_REFILL_RATE_KB_PER_SECOND)+ this.disabledTeamIds = this.parseTeamIdList(config.METRICS_LIMITER_DISABLED_FOR_TEAMS)+ this.enabledTeamIds = this.parseTeamIdList(config.METRICS_LIMITER_ENABLED_TEAMS)+ }++ private parseTeamIdList(config: string): Set<number> | '*' | null {+ if (config === '*') {+ return '*'+ }+ if (!config) {+ return null+ }+ const ids = new Set<number>()+ for (const id of config.split(',')) {+ const parsed = parseInt(id.trim(), 10)+ if (!isNaN(parsed)) {+ ids.add(parsed)+ }+ }+ return ids+ }++ private parseTeamConfig(config: string): Map<number, number> {+ const result = new Map<number, number>()+ if (!config) {+ return result+ }+ for (const entry of config.split(',')) {+ const [teamId, value] = entry.split(':').map((s) => parseInt(s.trim(), 10))+ if (!isNaN(teamId) && !isNaN(value)) {+ result.set(teamId, value)+ }+ }+ return result+ }++ private rateLimitArgs(+ id: string,+ cost: number,+ nowSeconds: number+ ): [string, number, number, number, number, number] {+ const teamId = parseInt(id, 10)++ return [+ `${REDIS_KEY_TOKENS}/${id}`,+ nowSeconds,+ cost,+ this.teamBucketSizes.get(teamId) ?? this.config.METRICS_LIMITER_BUCKET_SIZE_KB,+ this.teamRefillRates.get(teamId) ?? this.config.METRICS_LIMITER_REFILL_RATE_KB_PER_SECOND,+ this.config.METRICS_LIMITER_TTL_SECONDS,+ ]+ }++ private getHeaderValue(headers: any[] | undefined, key: string): string | undefined {+ if (!headers || !Array.isArray(headers)) {+ return undefined+ }++ for (const header of headers) {+ if (header[key]) {+ return Buffer.from(header[key]).toString('utf8')+ }+ }+ return undefined+ }++ private getTimestampFromMessage(message: MetricsIngestionMessage): number {+ const createdAtHeader = this.getHeaderValue(message.message.headers, 'created_at')+ if (createdAtHeader) {+ const timestamp = Date.parse(createdAtHeader)+ if (!isNaN(timestamp)) {+ return msToSeconds(timestamp)+ }+ }+ return msToSeconds(Date.now())+ }++ public async rateLimitMany(idCosts: [string, number, number][]): Promise<[string, MetricsRateLimit][]> {+ const res = await this.redis.usePipeline({ name: 'metrics-rate-limiter', failOpen: true }, (pipeline) => {+ idCosts.forEach(([id, cost, nowSeconds]) => {+ pipeline.checkRateLimitV2(...this.rateLimitArgs(id, cost, nowSeconds))+ })+ })++ if (!res) {+ throw new Error('Failed to rate limit')+ }++ return idCosts.map(([id, ,], index) => {+ const [tokenRes] = getRedisPipelineResults(res, index, 1)+ const tokensBefore = Number(tokenRes[1]?.[0] ?? this.config.METRICS_LIMITER_BUCKET_SIZE_KB)+ const tokensAfter = Number(tokenRes[1]?.[1] ?? this.config.METRICS_LIMITER_BUCKET_SIZE_KB)+ return [+ id,+ {+ tokensBefore,+ tokensAfter,+ isRateLimited: tokensAfter <= 0,+ },+ ]+ })+ }++ private isRateLimitingEnabledForTeam(teamId: number): boolean {+ if (this.disabledTeamIds === '*') {+ return false+ }++ if (this.disabledTeamIds?.has(teamId)) {+ return false+ }++ if (this.enabledTeamIds === '*') {+ return true+ }++ if (!this.enabledTeamIds) {+ return false+ }++ return this.enabledTeamIds.has(teamId)+ }++ public async filterMessages(messages: MetricsIngestionMessage[]): Promise<FilteredMessages> {+ const teamCosts = new Map<number, number>()+ const teamOldestTimestamps = new Map<number, number>()+ const teamNewestTimestamps = new Map<number, number>()++ for (const message of messages) {+ const messageTimestamp = this.getTimestampFromMessage(message)++ const existingOldest = teamOldestTimestamps.get(message.teamId)+ if (existingOldest === undefined || messageTimestamp < existingOldest) {+ teamOldestTimestamps.set(message.teamId, messageTimestamp)+ }++ const existingNewest = teamNewestTimestamps.get(message.teamId)+ if (existingNewest === undefined || messageTimestamp > existingNewest) {+ teamNewestTimestamps.set(message.teamId, messageTimestamp)+ }++ if (!this.isRateLimitingEnabledForTeam(message.teamId)) {+ continue+ }+ const currentCost = teamCosts.get(message.teamId) ?? 0+ const costKb = bytesToKb(message.bytesUncompressed)+ teamCosts.set(message.teamId, currentCost + costKb)+ }++ const nowSeconds = msToSeconds(Date.now())+ for (const [, timestamp] of teamOldestTimestamps) {+ metricsMessageLagHistogram.observe(nowSeconds - timestamp)+ }++ // Use the newest timestamp per team for the token bucket: this gives the bucket credit+ // for the full producer-time span the batch covers, so a catch-up batch refills against+ // its own time range instead of seeing timeDiff=0 from the previous batch's last call.+ const rateLimitResults = await this.rateLimitMany(+ Array.from(teamCosts.entries()).map(([teamId, cost]) => [+ teamId.toString(),+ cost,+ teamNewestTimestamps.get(teamId) ?? msToSeconds(Date.now()),+ ])+ )++ const teamLimits = new Map<number, { tokensBefore: number; tokensAfter: number; isRateLimited: boolean }>()+ for (const [teamIdStr, result] of rateLimitResults) {+ teamLimits.set(parseInt(teamIdStr, 10), result)+ }++ const allowed: MetricsIngestionMessage[] = []+ const dropped: MetricsIngestionMessage[] = []+ const teamKbUsed = new Map<number, number>()++ for (const message of messages) {+ const limit = teamLimits.get(message.teamId)+ if (!limit) {+ allowed.push(message)+ continue+ }++ const kbUsed = teamKbUsed.get(message.teamId) ?? 0+ const availableKb = limit.tokensBefore+ const messageKb = bytesToKb(message.bytesUncompressed)++ if (kbUsed + messageKb <= availableKb) {+ allowed.push(message)+ teamKbUsed.set(message.teamId, kbUsed + messageKb)+ } else {+ dropped.push(message)+ }+ }++ return { allowed, dropped }+ }+}diff --git a/nodejs/src/metrics-ingestion/types.ts b/nodejs/src/metrics-ingestion/types.tsnew file mode 100644index 000000000000..bb16e96028b9--- /dev/null+++ b/nodejs/src/metrics-ingestion/types.ts@@ -0,0 +1,10 @@+import { Message } from 'node-rdkafka'++export type MetricsIngestionMessage = {+ token: string+ teamId: number+ message: Message+ bytesUncompressed: number+ bytesCompressed: number+ recordCount: number+}diff --git a/nodejs/src/server.ts b/nodejs/src/server.tsindex 72f6aff773b1..d3ce58c37220 100644--- a/nodejs/src/server.ts+++ b/nodejs/src/server.ts@@ -240,6 +240,14 @@ export class PluginServer implements NodeServer {return Promise.resolve(serverCommands.service)})+ if (capabilities.cdpBatchHogFlow) {+ serviceLoaders.push(async () => {+ const consumer = new CdpBatchHogFlowRequestsConsumer(this.config, cdpDeps!)+ await consumer.start()+ return consumer.service+ })+ }+if (capabilities.cdpPrecalculatedFilters) {serviceLoaders.push(async () => {const worker = new CdpPrecalculatedFiltersConsumer(this.config, cdpDeps!)diff --git a/nodejs/src/servers/ingestion-metrics-server.ts b/nodejs/src/servers/ingestion-metrics-server.tsnew file mode 100644index 000000000000..3394b9260331--- /dev/null+++ b/nodejs/src/servers/ingestion-metrics-server.ts@@ -0,0 +1,133 @@+import { QuotaLimiting } from '~/common/services/quota-limiting.service'++import { CommonConfig } from '../common/config'+import { defaultConfig, overrideConfigWithEnv } from '../config/config'+import { createPosthogRedisConnectionConfig } from '../config/redis-pools'+import { DatabaseConnectionConfig, KafkaBrokerConfig, RedisConnectionsConfig } from '../ingestion/config'+import { KafkaProducerRegistry } from '../ingestion/outputs/kafka-producer-registry'+import {+ MetricsIngestionConsumerConfig,+ MetricsIngestionOutputsConfig,+ getDefaultMetricsIngestionOutputsConfig,+} from '../metrics-ingestion/config'+import { MetricsIngestionConsumer } from '../metrics-ingestion/metrics-ingestion-consumer'+import { createProducerRegistry } from '../metrics-ingestion/outputs/producer-registry'+import {+ KafkaWarpstreamIngestionProducerEnvConfig,+ KafkaWarpstreamMetricsProducerEnvConfig,+ MetricsProducerName,+ getDefaultKafkaWarpstreamIngestionProducerEnvConfig,+ getDefaultKafkaWarpstreamMetricsProducerEnvConfig,+} from '../metrics-ingestion/outputs/producers'+import { createMetricsOutputsRegistry } from '../metrics-ingestion/outputs/registry'+import { PluginServerService, RedisPool } from '../types'+import { PostgresRouter } from '../utils/db/postgres'+import { createRedisPoolFromConfig } from '../utils/db/redis'+import { logger } from '../utils/logger'+import { TeamManager } from '../utils/team-manager'+import { BaseServerConfig, CleanupResources, NodeServer, ServerLifecycle } from './base-server'++/**+ * Config type for a standalone Metrics ingestion deployment.+ *+ * This is the union of:+ * - BaseServerConfig: HTTP server, profiling, pod termination lifecycle+ * - MetricsIngestionConsumerConfig: Kafka topics, Redis, rate limiter settings+ * - MetricsIngestionOutputsConfig: per-output topic + producer routing+ * - Producer env configs: typed env vars for the Warpstream metrics + ingestion producers+ * - Infrastructure configs: Kafka broker, Postgres, Redis+ * - Remaining CommonConfig picks: server mode, observability+ */+export type IngestionMetricsServerConfig = BaseServerConfig &+ MetricsIngestionConsumerConfig &+ MetricsIngestionOutputsConfig &+ KafkaWarpstreamMetricsProducerEnvConfig &+ KafkaWarpstreamIngestionProducerEnvConfig &+ KafkaBrokerConfig &+ DatabaseConnectionConfig &+ RedisConnectionsConfig &+ Pick<CommonConfig, 'LOG_LEVEL' | 'PLUGIN_SERVER_MODE' | 'CLOUD_DEPLOYMENT' | 'HEALTHCHECK_MAX_STALE_SECONDS'>++export class IngestionMetricsServer implements NodeServer {+ readonly lifecycle: ServerLifecycle+ private config: IngestionMetricsServerConfig++ private postgres?: PostgresRouter+ private posthogRedisPool?: RedisPool+ private producerRegistry?: KafkaProducerRegistry<MetricsProducerName>++ constructor(config: Partial<IngestionMetricsServerConfig> = {}) {+ this.config = {+ ...defaultConfig,+ ...overrideConfigWithEnv(getDefaultKafkaWarpstreamMetricsProducerEnvConfig()),+ ...overrideConfigWithEnv(getDefaultKafkaWarpstreamIngestionProducerEnvConfig()),+ ...overrideConfigWithEnv(getDefaultMetricsIngestionOutputsConfig()),+ ...config,+ }+ this.lifecycle = new ServerLifecycle(this.config)+ }++ async start(): Promise<void> {+ return this.lifecycle.start(+ () => this.startServices(),+ () => this.getCleanupResources()+ )+ }++ async stop(error?: Error): Promise<void> {+ return this.lifecycle.stop(() => this.getCleanupResources(), error)+ }++ private async startServices(): Promise<void> {+ // 1. Shared infrastructure+ logger.info('ℹ️', 'Connecting to shared infrastructure...')++ this.postgres = new PostgresRouter(this.config)+ logger.info('👍', 'Postgres Router ready')++ logger.info('🤔', 'Connecting to Kafka...')+ this.producerRegistry = await createProducerRegistry(this.config.KAFKA_CLIENT_RACK).build(this.config)+ logger.info('👍', 'Kafka ready')++ logger.info('🤔', 'Connecting to PostHog Redis...')+ this.posthogRedisPool = createRedisPoolFromConfig({+ connection: createPosthogRedisConnectionConfig(this.config),+ poolMinSize: this.config.REDIS_POOL_MIN_SIZE,+ poolMaxSize: this.config.REDIS_POOL_MAX_SIZE,+ })+ logger.info('👍', 'PostHog Redis ready')++ const teamManager = new TeamManager(this.postgres)+ const quotaLimiting = new QuotaLimiting(this.posthogRedisPool, teamManager)++ // 2. Resolve outputs (topic + producer per logical name, env-controlled)+ const outputs = createMetricsOutputsRegistry().build(this.producerRegistry, this.config)++ // 3. Metrics ingestion consumer+ const serviceLoaders: (() => Promise<PluginServerService>)[] = []++ serviceLoaders.push(async () => {+ const consumer = new MetricsIngestionConsumer(this.config, {+ teamManager,+ quotaLimiting,+ outputs,+ })+ await consumer.start()+ return consumer.service+ })++ const readyServices = await Promise.all(serviceLoaders.map((loader) => loader()))+ this.lifecycle.services.push(...readyServices)+ }++ private getCleanupResources(): CleanupResources {+ return {+ kafkaProducers: [],+ redisPools: [this.posthogRedisPool].filter(Boolean) as RedisPool[],+ postgres: this.postgres,+ additionalCleanup: async () => {+ await this.producerRegistry?.disconnectAll()+ },+ }+ }+}diff --git a/nodejs/src/types.ts b/nodejs/src/types.tsindex bf2d275592a4..4c006965aa38 100644--- a/nodejs/src/types.ts+++ b/nodejs/src/types.ts@@ -21,6 +21,7 @@ import type { CookielessManager } from './ingestion/cookieless/cookieless-manageimport type { ErrorTrackingConsumerConfig } from './ingestion/error-tracking/config'import type { LlmAnalyticsConfig } from './llm-analytics/config'import type { LogsIngestionConsumerConfig, TracesIngestionConsumerConfig } from './logs-ingestion/config'+import type { MetricsIngestionConsumerConfig } from './metrics-ingestion/config'import type { SessionRecordingApiConfig, SessionRecordingConfig } from './session-recording/config'import { PostgresRouter } from './utils/db/postgres'import { GeoIPService } from './utils/geoip'@@ -46,6 +47,7 @@ export {} from './ingestion/config'export { ErrorTrackingConsumerConfig } from './ingestion/error-tracking/config'export { LogsIngestionConsumerConfig } from './logs-ingestion/config'+export { MetricsIngestionConsumerConfig } from './metrics-ingestion/config'export { SessionRecordingApiConfig, SessionRecordingConfig } from './session-recording/config'interface HealthCheckResultResponse {@@ -117,6 +119,7 @@ export interface PluginsServerConfigLogsIngestionConsumerConfig,TracesIngestionConsumerConfig,ErrorTrackingConsumerConfig,+ MetricsIngestionConsumerConfig,SessionRecordingConfig,SessionRecordingApiConfig,// Producer envs needed by the CDP producer registry the legacy big server builds.@@ -150,6 +153,8 @@ export interface PluginServerCapabilities {ingestionV2Combined?: booleaningestionV2?: booleanerrorTrackingIngestion?: boolean+ logsIngestion?: boolean+ metricsIngestion?: booleansessionRecordingBlobIngestionV2?: booleansessionRecordingBlobIngestionV2Overflow?: booleancdpProcessedEvents?: booleandiff --git a/otel-collector-config.dev.yaml b/otel-collector-config.dev.yamlindex c210fd5c5a91..873c353c386a 100644--- a/otel-collector-config.dev.yaml+++ b/otel-collector-config.dev.yaml@@ -54,6 +54,14 @@ receivers:endpoint: 0.0.0.0:4317 # Collector receiving OTLP gRPChttp:endpoint: 0.0.0.0:4318 # Collector receiving OTLP HTTP+ prometheus:+ config:+ scrape_configs:+ - job_name: 'nodejs'+ scrape_interval: 15s+ metrics_path: /_metrics+ static_configs:+ - targets: ['host.docker.internal:6738']exporters:otlp: # Using the standard OTLP exporter@@ -69,13 +77,20 @@ exporters:# special "local" token is automatically mapped to team_id 1 in dev environmentsauthorization: Bearer phc_localotlphttp/logs:- endpoint: 'http://capture-logs:4318'+ endpoint: 'http://host.docker.internal:4320'compression: nonetls:insecure: trueheaders:# special "local" token is automatically mapped to team_id 1 in dev environmentsauthorization: Bearer phc_local+ otlphttp/metrics:+ endpoint: 'http://host.docker.internal:4320'+ compression: none+ tls:+ insecure: true+ headers:+ authorization: Bearer phc_localprocessors:batch:@@ -94,4 +109,8 @@ service:receivers:- otlp- receiver_creator+ metrics:+ receivers: [otlp, prometheus]+ processors: [batch]+ exporters: [otlphttp/metrics]extensions: [docker_observer, health_check, zpages] # Enabling the declared extensionsdiff --git a/posthog/clickhouse/metrics/__init__.py b/posthog/clickhouse/metrics/__init__.pynew file mode 100644index 000000000000..5df721690eea--- /dev/null+++ b/posthog/clickhouse/metrics/__init__.py@@ -0,0 +1,15 @@+from .metric_attributes import METRIC_ATTRIBUTES_TABLE_SQL+from .metrics1 import (+ METRIC_ATTRIBUTES_MV,+ METRIC_RESOURCE_ATTRIBUTES_MV,+ METRICS1_TABLE_SQL,+ METRICS_DISTRIBUTED_TABLE_SQL,+)++__all__ = [+ "METRICS1_TABLE_SQL",+ "METRICS_DISTRIBUTED_TABLE_SQL",+ "METRIC_ATTRIBUTES_MV",+ "METRIC_RESOURCE_ATTRIBUTES_MV",+ "METRIC_ATTRIBUTES_TABLE_SQL",+]diff --git a/posthog/clickhouse/metrics/metric_attributes.py b/posthog/clickhouse/metrics/metric_attributes.pynew file mode 100644index 000000000000..6efbed5745e8--- /dev/null+++ b/posthog/clickhouse/metrics/metric_attributes.py@@ -0,0 +1,31 @@+from django.conf import settings++from posthog.clickhouse.table_engines import AggregatingMergeTree, ReplicationScheme++TABLE_NAME = "metric_attributes"+++def METRIC_ATTRIBUTES_TABLE_SQL():+ return f"""+CREATE TABLE IF NOT EXISTS {settings.CLICKHOUSE_LOGS_CLUSTER_DATABASE}.{TABLE_NAME}+(+ `team_id` Int32 CODEC(DoubleDelta, ZSTD(1)),+ `time_bucket` DateTime64(0) CODEC(DoubleDelta, ZSTD(1)),+ `service_name` LowCardinality(String) CODEC(ZSTD(1)),+ `resource_fingerprint` UInt64 DEFAULT 0 CODEC(DoubleDelta, ZSTD(1)),+ `attribute_key` LowCardinality(String) CODEC(ZSTD(1)),+ `attribute_value` String CODEC(ZSTD(1)),+ `attribute_count` SimpleAggregateFunction(sum, UInt64),+ `attribute_type` LowCardinality(String),+ INDEX idx_attribute_key attribute_key TYPE bloom_filter(0.01) GRANULARITY 1,+ INDEX idx_attribute_value attribute_value TYPE bloom_filter(0.01) GRANULARITY 1,+ INDEX idx_attribute_key_n3 attribute_key TYPE ngrambf_v1(3, 32768, 3, 0) GRANULARITY 1,+ INDEX idx_attribute_value_n3 attribute_value TYPE ngrambf_v1(3, 32768, 3, 0) GRANULARITY 1+)+ENGINE = {AggregatingMergeTree("metric_attributes", replication_scheme=ReplicationScheme.REPLICATED)}+PARTITION BY toDate(time_bucket)+ORDER BY (team_id, attribute_type, time_bucket, resource_fingerprint, attribute_key, attribute_value)+SETTINGS+ deduplicate_merge_projection_mode = 'drop',+ index_granularity = 8192+"""diff --git a/posthog/clickhouse/metrics/metrics1.py b/posthog/clickhouse/metrics/metrics1.pynew file mode 100644index 000000000000..0cca91b7f210--- /dev/null+++ b/posthog/clickhouse/metrics/metrics1.py@@ -0,0 +1,181 @@+from django.conf import settings++from posthog.clickhouse.table_engines import Distributed, MergeTreeEngine, ReplicationScheme++from .metric_attributes import TABLE_NAME as METRIC_ATTRIBUTES_TABLE_NAME++TABLE_NAME = "metrics1"+++def METRICS1_TABLE_SQL():+ return f"""+CREATE TABLE IF NOT EXISTS {settings.CLICKHOUSE_LOGS_CLUSTER_DATABASE}.{TABLE_NAME}+(+ `time_bucket` DateTime MATERIALIZED toStartOfDay(timestamp) CODEC(DoubleDelta, ZSTD(1)),+ `uuid` String CODEC(ZSTD(1)),+ `team_id` Int32 CODEC(ZSTD(1)),+ `trace_id` String CODEC(ZSTD(1)),+ `span_id` String CODEC(ZSTD(1)),+ `trace_flags` Int32 CODEC(ZSTD(1)),+ `timestamp` DateTime64(6) CODEC(DoubleDelta, ZSTD(1)),+ `observed_timestamp` DateTime64(6) CODEC(DoubleDelta, ZSTD(1)),+ `created_at` DateTime64(6) MATERIALIZED now() CODEC(DoubleDelta, ZSTD(1)),+ `service_name` LowCardinality(String) CODEC(ZSTD(1)),+ `metric_name` LowCardinality(String) CODEC(ZSTD(1)),+ `metric_type` LowCardinality(String) CODEC(ZSTD(1)),+ `value` Float64 CODEC(Gorilla, ZSTD(1)),+ `count` UInt64 DEFAULT 1 CODEC(T64, ZSTD(1)),+ `histogram_bounds` Array(Float64) CODEC(ZSTD(1)),+ `histogram_counts` Array(UInt64) CODEC(ZSTD(1)),+ `unit` LowCardinality(String) CODEC(ZSTD(1)),+ `aggregation_temporality` LowCardinality(String) CODEC(ZSTD(1)),+ `is_monotonic` Bool DEFAULT false CODEC(ZSTD(1)),+ `resource_attributes` Map(LowCardinality(String), String) CODEC(ZSTD(1)),+ `resource_fingerprint` UInt64 MATERIALIZED cityHash64(resource_attributes) CODEC(DoubleDelta, ZSTD(1)),+ `instrumentation_scope` String CODEC(ZSTD(1)),+ `attributes_map_str` Map(LowCardinality(String), String) CODEC(ZSTD(1)),+ `attributes_map_float` Map(LowCardinality(String), Float64) CODEC(ZSTD(1)),+ `time_minute` DateTime ALIAS toStartOfMinute(timestamp),+ `attributes` Map(String, String) ALIAS mapApply((k, v) -> (left(k, -5), v), attributes_map_str),+ INDEX idx_metric_name_set metric_name TYPE set(100) GRANULARITY 1,+ INDEX idx_metric_type_set metric_type TYPE set(10) GRANULARITY 1,+ INDEX idx_attributes_str_keys mapKeys(attributes_map_str) TYPE bloom_filter(0.01) GRANULARITY 1,+ INDEX idx_attributes_str_values mapValues(attributes_map_str) TYPE bloom_filter(0.001) GRANULARITY 1,+ INDEX idx_observed_minmax observed_timestamp TYPE minmax GRANULARITY 1,+ PROJECTION projection_aggregate_counts+ (+ SELECT+ team_id,+ time_bucket,+ toStartOfMinute(timestamp),+ service_name,+ metric_name,+ metric_type,+ resource_fingerprint,+ count() AS event_count,+ sum(value) AS total_value,+ min(value) AS min_value,+ max(value) AS max_value+ GROUP BY+ team_id,+ time_bucket,+ toStartOfMinute(timestamp),+ service_name,+ metric_name,+ metric_type,+ resource_fingerprint+ )+)+ENGINE = {MergeTreeEngine(TABLE_NAME, replication_scheme=ReplicationScheme.REPLICATED)}+PARTITION BY toDate(timestamp)+PRIMARY KEY (team_id, time_bucket, service_name, metric_name, resource_fingerprint, timestamp)+ORDER BY (team_id, time_bucket, service_name, metric_name, resource_fingerprint, timestamp)+SETTINGS+ index_granularity_bytes = 104857600,+ index_granularity = 8192,+ ttl_only_drop_parts = 1+"""+++def METRICS_DISTRIBUTED_TABLE_SQL():+ return """+CREATE TABLE IF NOT EXISTS {database}.metrics AS {database}.{table_name} ENGINE = {engine}+""".format(+ engine=Distributed(+ data_table=f"{TABLE_NAME}",+ cluster=settings.CLICKHOUSE_LOGS_CLUSTER,+ ),+ database=settings.CLICKHOUSE_LOGS_CLUSTER_DATABASE,+ table_name=TABLE_NAME,+ )+++def METRIC_ATTRIBUTES_MV():+ return f"""+CREATE MATERIALIZED VIEW IF NOT EXISTS {settings.CLICKHOUSE_LOGS_CLUSTER_DATABASE}.{TABLE_NAME}_to_metric_attributes TO {settings.CLICKHOUSE_LOGS_CLUSTER_DATABASE}.{METRIC_ATTRIBUTES_TABLE_NAME}+(+ `team_id` Int32,+ `time_bucket` DateTime64(0),+ `service_name` LowCardinality(String),+ `resource_fingerprint` UInt64,+ `attribute_key` LowCardinality(String),+ `attribute_value` String,+ `attribute_type` LowCardinality(String),+ `attribute_count` SimpleAggregateFunction(sum, UInt64)+)+AS SELECT+ team_id,+ time_bucket,+ service_name,+ resource_fingerprint,+ attribute_key,+ attribute_value,+ attribute_type,+ attribute_count+FROM+(+ SELECT+ team_id AS team_id,+ toStartOfInterval(timestamp, toIntervalMinute(10)) AS time_bucket,+ service_name AS service_name,+ resource_fingerprint,+ mapFilter((k, v) -> ((length(k) < 256) AND (length(v) < 256)), attributes) AS attributes,+ arrayJoin(attributes) AS attribute,+ 'metric' AS attribute_type,+ attribute.1 AS attribute_key,+ attribute.2 AS attribute_value,+ sumSimpleState(1) AS attribute_count+ FROM {settings.CLICKHOUSE_LOGS_CLUSTER_DATABASE}.{TABLE_NAME}+ GROUP BY+ team_id,+ time_bucket,+ service_name,+ resource_fingerprint,+ attributes+)+"""+++def METRIC_RESOURCE_ATTRIBUTES_MV():+ return f"""+CREATE MATERIALIZED VIEW IF NOT EXISTS {settings.CLICKHOUSE_LOGS_CLUSTER_DATABASE}.{TABLE_NAME}_to_resource_attributes TO {settings.CLICKHOUSE_LOGS_CLUSTER_DATABASE}.{METRIC_ATTRIBUTES_TABLE_NAME}+(+ `team_id` Int32,+ `time_bucket` DateTime64(0),+ `service_name` LowCardinality(String),+ `resource_fingerprint` UInt64,+ `attribute_key` LowCardinality(String),+ `attribute_value` String,+ `attribute_type` LowCardinality(String),+ `attribute_count` SimpleAggregateFunction(sum, UInt64)+)+AS SELECT+ team_id,+ time_bucket,+ service_name,+ resource_fingerprint,+ attribute_key,+ attribute_value,+ attribute_type,+ attribute_count+FROM+(+ SELECT+ team_id AS team_id,+ toStartOfInterval(timestamp, toIntervalMinute(10)) AS time_bucket,+ service_name AS service_name,+ resource_fingerprint,+ arrayJoin(resource_attributes) AS attribute,+ 'resource' AS attribute_type,+ attribute.1 AS attribute_key,+ attribute.2 AS attribute_value,+ sumSimpleState(1) AS attribute_count+ FROM {settings.CLICKHOUSE_LOGS_CLUSTER_DATABASE}.{TABLE_NAME}+ GROUP BY+ team_id,+ time_bucket,+ service_name,+ resource_fingerprint,+ resource_attributes+)+"""diff --git a/posthog/clickhouse/schema.py b/posthog/clickhouse/schema.pyindex de93684e0475..57b19a68ed2d 100644--- a/posthog/clickhouse/schema.py+++ b/posthog/clickhouse/schema.py@@ -20,6 +20,13 @@ from posthog.clickhouse.logs import (LOGS_KAFKA_METRICS_DISTRIBUTED_TABLE_SQL,LOGS_KAFKA_METRICS_TABLE_SQL,)+from posthog.clickhouse.metrics import (+ METRIC_ATTRIBUTES_MV,+ METRIC_ATTRIBUTES_TABLE_SQL,+ METRIC_RESOURCE_ATTRIBUTES_MV,+ METRICS1_TABLE_SQL,+ METRICS_DISTRIBUTED_TABLE_SQL,+)from posthog.clickhouse.plugin_log_entries import (KAFKA_PLUGIN_LOG_ENTRIES_TABLE_SQL,PLUGIN_LOG_ENTRIES_TABLE_MV_SQL,@@ -286,6 +293,8 @@ CREATE_MERGETREE_TABLE_QUERIES = (LOGS32_TABLE_SQL,LOG_ATTRIBUTES_TABLE_SQL,LOGS_KAFKA_METRICS_TABLE_SQL,+ METRICS1_TABLE_SQL,+ METRIC_ATTRIBUTES_TABLE_SQL,TOPHOG_DATA_TABLE_SQL,AI_EVENTS_DATA_TABLE_SQL,PROPERTY_VALUES_TABLE_SQL,@@ -341,6 +350,7 @@ CREATE_DISTRIBUTED_TABLE_QUERIES = (LOGS_DISTRIBUTED2_TABLE_SQL,LOG_ATTRIBUTES_DISTRIBUTED_TABLE_SQL,LOGS_KAFKA_METRICS_DISTRIBUTED_TABLE_SQL,+ METRICS_DISTRIBUTED_TABLE_SQL,WRITABLE_TOPHOG_TABLE_SQL,DISTRIBUTED_TOPHOG_TABLE_SQL,DISTRIBUTED_AI_EVENTS_TABLE_SQL,@@ -408,6 +418,8 @@ CREATE_MV_TABLE_QUERIES = (DISTINCT_ID_USAGE_MV_SQL,LOG_ATTRIBUTES_MV,LOG_RESOURCE_ATTRIBUTES_MV,+ METRIC_ATTRIBUTES_MV,+ METRIC_RESOURCE_ATTRIBUTES_MV,TOPHOG_MV_SQL,AI_EVENTS_MV_SQL,PROPERTY_VALUES_MV_SQL,diff --git a/posthog/clickhouse/test/__snapshots__/test_schema.ambr b/posthog/clickhouse/test/__snapshots__/test_schema.ambrindex 10d0aa323179..63e5cf163303 100644--- a/posthog/clickhouse/test/__snapshots__/test_schema.ambr+++ b/posthog/clickhouse/test/__snapshots__/test_schema.ambr@@ -2803,6 +2803,204 @@'''# ---+# name: test_create_table_query[metric_attributes]+ '''++ CREATE TABLE IF NOT EXISTS posthog_test.metric_attributes+ (+ `team_id` Int32 CODEC(DoubleDelta, ZSTD(1)),+ `time_bucket` DateTime64(0) CODEC(DoubleDelta, ZSTD(1)),+ `service_name` LowCardinality(String) CODEC(ZSTD(1)),+ `resource_fingerprint` UInt64 DEFAULT 0 CODEC(DoubleDelta, ZSTD(1)),+ `attribute_key` LowCardinality(String) CODEC(ZSTD(1)),+ `attribute_value` String CODEC(ZSTD(1)),+ `attribute_count` SimpleAggregateFunction(sum, UInt64),+ `attribute_type` LowCardinality(String),+ INDEX idx_attribute_key attribute_key TYPE bloom_filter(0.01) GRANULARITY 1,+ INDEX idx_attribute_value attribute_value TYPE bloom_filter(0.01) GRANULARITY 1,+ INDEX idx_attribute_key_n3 attribute_key TYPE ngrambf_v1(3, 32768, 3, 0) GRANULARITY 1,+ INDEX idx_attribute_value_n3 attribute_value TYPE ngrambf_v1(3, 32768, 3, 0) GRANULARITY 1+ )+ ENGINE = ReplicatedAggregatingMergeTree('/clickhouse/tables/77f1df52-4b43-11e9-910f-b8ca3a9b9f3e_noshard/posthog.metric_attributes', '{replica}-{shard}')+ PARTITION BY toDate(time_bucket)+ ORDER BY (team_id, attribute_type, time_bucket, resource_fingerprint, attribute_key, attribute_value)+ SETTINGS+ deduplicate_merge_projection_mode = 'drop',+ index_granularity = 8192++ '''+# ---+# name: test_create_table_query[metrics1]+ '''++ CREATE TABLE IF NOT EXISTS posthog_test.metrics1+ (+ `time_bucket` DateTime MATERIALIZED toStartOfDay(timestamp) CODEC(DoubleDelta, ZSTD(1)),+ `uuid` String CODEC(ZSTD(1)),+ `team_id` Int32 CODEC(ZSTD(1)),+ `trace_id` String CODEC(ZSTD(1)),+ `span_id` String CODEC(ZSTD(1)),+ `trace_flags` Int32 CODEC(ZSTD(1)),+ `timestamp` DateTime64(6) CODEC(DoubleDelta, ZSTD(1)),+ `observed_timestamp` DateTime64(6) CODEC(DoubleDelta, ZSTD(1)),+ `created_at` DateTime64(6) MATERIALIZED now() CODEC(DoubleDelta, ZSTD(1)),+ `service_name` LowCardinality(String) CODEC(ZSTD(1)),+ `metric_name` LowCardinality(String) CODEC(ZSTD(1)),+ `metric_type` LowCardinality(String) CODEC(ZSTD(1)),+ `value` Float64 CODEC(Gorilla, ZSTD(1)),+ `count` UInt64 DEFAULT 1 CODEC(T64, ZSTD(1)),+ `histogram_bounds` Array(Float64) CODEC(ZSTD(1)),+ `histogram_counts` Array(UInt64) CODEC(ZSTD(1)),+ `unit` LowCardinality(String) CODEC(ZSTD(1)),+ `aggregation_temporality` LowCardinality(String) CODEC(ZSTD(1)),+ `is_monotonic` Bool DEFAULT false CODEC(ZSTD(1)),+ `resource_attributes` Map(LowCardinality(String), String) CODEC(ZSTD(1)),+ `resource_fingerprint` UInt64 MATERIALIZED cityHash64(resource_attributes) CODEC(DoubleDelta, ZSTD(1)),+ `instrumentation_scope` String CODEC(ZSTD(1)),+ `attributes_map_str` Map(LowCardinality(String), String) CODEC(ZSTD(1)),+ `attributes_map_float` Map(LowCardinality(String), Float64) CODEC(ZSTD(1)),+ `time_minute` DateTime ALIAS toStartOfMinute(timestamp),+ `attributes` Map(String, String) ALIAS mapApply((k, v) -> (left(k, -5), v), attributes_map_str),+ INDEX idx_metric_name_set metric_name TYPE set(100) GRANULARITY 1,+ INDEX idx_metric_type_set metric_type TYPE set(10) GRANULARITY 1,+ INDEX idx_attributes_str_keys mapKeys(attributes_map_str) TYPE bloom_filter(0.01) GRANULARITY 1,+ INDEX idx_attributes_str_values mapValues(attributes_map_str) TYPE bloom_filter(0.001) GRANULARITY 1,+ INDEX idx_observed_minmax observed_timestamp TYPE minmax GRANULARITY 1,+ PROJECTION projection_aggregate_counts+ (+ SELECT+ team_id,+ time_bucket,+ toStartOfMinute(timestamp),+ service_name,+ metric_name,+ metric_type,+ resource_fingerprint,+ count() AS event_count,+ sum(value) AS total_value,+ min(value) AS min_value,+ max(value) AS max_value+ GROUP BY+ team_id,+ time_bucket,+ toStartOfMinute(timestamp),+ service_name,+ metric_name,+ metric_type,+ resource_fingerprint+ )+ )+ ENGINE = ReplicatedMergeTree('/clickhouse/tables/77f1df52-4b43-11e9-910f-b8ca3a9b9f3e_noshard/posthog.metrics1', '{replica}-{shard}')+ PARTITION BY toDate(timestamp)+ PRIMARY KEY (team_id, time_bucket, service_name, metric_name, resource_fingerprint, timestamp)+ ORDER BY (team_id, time_bucket, service_name, metric_name, resource_fingerprint, timestamp)+ SETTINGS+ index_granularity_bytes = 104857600,+ index_granularity = 8192,+ ttl_only_drop_parts = 1++ '''+# ---+# name: test_create_table_query[metrics1_to_metric_attributes]+ '''++ CREATE MATERIALIZED VIEW IF NOT EXISTS posthog_test.metrics1_to_metric_attributes TO posthog_test.metric_attributes+ (+ `team_id` Int32,+ `time_bucket` DateTime64(0),+ `service_name` LowCardinality(String),+ `resource_fingerprint` UInt64,+ `attribute_key` LowCardinality(String),+ `attribute_value` String,+ `attribute_type` LowCardinality(String),+ `attribute_count` SimpleAggregateFunction(sum, UInt64)+ )+ AS SELECT+ team_id,+ time_bucket,+ service_name,+ resource_fingerprint,+ attribute_key,+ attribute_value,+ attribute_type,+ attribute_count+ FROM+ (+ SELECT+ team_id AS team_id,+ toStartOfInterval(timestamp, toIntervalMinute(10)) AS time_bucket,+ service_name AS service_name,+ resource_fingerprint,+ mapFilter((k, v) -> ((length(k) < 256) AND (length(v) < 256)), attributes) AS attributes,+ arrayJoin(attributes) AS attribute,+ 'metric' AS attribute_type,+ attribute.1 AS attribute_key,+ attribute.2 AS attribute_value,+ sumSimpleState(1) AS attribute_count+ FROM posthog_test.metrics1+ GROUP BY+ team_id,+ time_bucket,+ service_name,+ resource_fingerprint,+ attributes+ )++ '''+# ---+# name: test_create_table_query[metrics1_to_resource_attributes]+ '''++ CREATE MATERIALIZED VIEW IF NOT EXISTS posthog_test.metrics1_to_resource_attributes TO posthog_test.metric_attributes+ (+ `team_id` Int32,+ `time_bucket` DateTime64(0),+ `service_name` LowCardinality(String),+ `resource_fingerprint` UInt64,+ `attribute_key` LowCardinality(String),+ `attribute_value` String,+ `attribute_type` LowCardinality(String),+ `attribute_count` SimpleAggregateFunction(sum, UInt64)+ )+ AS SELECT+ team_id,+ time_bucket,+ service_name,+ resource_fingerprint,+ attribute_key,+ attribute_value,+ attribute_type,+ attribute_count+ FROM+ (+ SELECT+ team_id AS team_id,+ toStartOfInterval(timestamp, toIntervalMinute(10)) AS time_bucket,+ service_name AS service_name,+ resource_fingerprint,+ arrayJoin(resource_attributes) AS attribute,+ 'resource' AS attribute_type,+ attribute.1 AS attribute_key,+ attribute.2 AS attribute_value,+ sumSimpleState(1) AS attribute_count+ FROM posthog_test.metrics1+ GROUP BY+ team_id,+ time_bucket,+ service_name,+ resource_fingerprint,+ resource_attributes+ )++ '''+# ---+# name: test_create_table_query[metrics]+ '''++ CREATE TABLE IF NOT EXISTS posthog_test.metrics AS posthog_test.metrics1 ENGINE = Distributed('posthog_single_shard', 'posthog_test', 'metrics1')++ '''+# ---# name: test_create_table_query[partitioned_sharded_posthog_document_embeddings]'''@@ -7406,6 +7604,104 @@'''# ---+# name: test_create_table_query_replicated_and_storage[metric_attributes]+ '''++ CREATE TABLE IF NOT EXISTS posthog_test.metric_attributes+ (+ `team_id` Int32 CODEC(DoubleDelta, ZSTD(1)),+ `time_bucket` DateTime64(0) CODEC(DoubleDelta, ZSTD(1)),+ `service_name` LowCardinality(String) CODEC(ZSTD(1)),+ `resource_fingerprint` UInt64 DEFAULT 0 CODEC(DoubleDelta, ZSTD(1)),+ `attribute_key` LowCardinality(String) CODEC(ZSTD(1)),+ `attribute_value` String CODEC(ZSTD(1)),+ `attribute_count` SimpleAggregateFunction(sum, UInt64),+ `attribute_type` LowCardinality(String),+ INDEX idx_attribute_key attribute_key TYPE bloom_filter(0.01) GRANULARITY 1,+ INDEX idx_attribute_value attribute_value TYPE bloom_filter(0.01) GRANULARITY 1,+ INDEX idx_attribute_key_n3 attribute_key TYPE ngrambf_v1(3, 32768, 3, 0) GRANULARITY 1,+ INDEX idx_attribute_value_n3 attribute_value TYPE ngrambf_v1(3, 32768, 3, 0) GRANULARITY 1+ )+ ENGINE = ReplicatedAggregatingMergeTree('/clickhouse/tables/77f1df52-4b43-11e9-910f-b8ca3a9b9f3e_noshard/posthog.metric_attributes', '{replica}-{shard}')+ PARTITION BY toDate(time_bucket)+ ORDER BY (team_id, attribute_type, time_bucket, resource_fingerprint, attribute_key, attribute_value)+ SETTINGS+ deduplicate_merge_projection_mode = 'drop',+ index_granularity = 8192++ '''+# ---+# name: test_create_table_query_replicated_and_storage[metrics1]+ '''++ CREATE TABLE IF NOT EXISTS posthog_test.metrics1+ (+ `time_bucket` DateTime MATERIALIZED toStartOfDay(timestamp) CODEC(DoubleDelta, ZSTD(1)),+ `uuid` String CODEC(ZSTD(1)),+ `team_id` Int32 CODEC(ZSTD(1)),+ `trace_id` String CODEC(ZSTD(1)),+ `span_id` String CODEC(ZSTD(1)),+ `trace_flags` Int32 CODEC(ZSTD(1)),+ `timestamp` DateTime64(6) CODEC(DoubleDelta, ZSTD(1)),+ `observed_timestamp` DateTime64(6) CODEC(DoubleDelta, ZSTD(1)),+ `created_at` DateTime64(6) MATERIALIZED now() CODEC(DoubleDelta, ZSTD(1)),+ `service_name` LowCardinality(String) CODEC(ZSTD(1)),+ `metric_name` LowCardinality(String) CODEC(ZSTD(1)),+ `metric_type` LowCardinality(String) CODEC(ZSTD(1)),+ `value` Float64 CODEC(Gorilla, ZSTD(1)),+ `count` UInt64 DEFAULT 1 CODEC(T64, ZSTD(1)),+ `histogram_bounds` Array(Float64) CODEC(ZSTD(1)),+ `histogram_counts` Array(UInt64) CODEC(ZSTD(1)),+ `unit` LowCardinality(String) CODEC(ZSTD(1)),+ `aggregation_temporality` LowCardinality(String) CODEC(ZSTD(1)),+ `is_monotonic` Bool DEFAULT false CODEC(ZSTD(1)),+ `resource_attributes` Map(LowCardinality(String), String) CODEC(ZSTD(1)),+ `resource_fingerprint` UInt64 MATERIALIZED cityHash64(resource_attributes) CODEC(DoubleDelta, ZSTD(1)),+ `instrumentation_scope` String CODEC(ZSTD(1)),+ `attributes_map_str` Map(LowCardinality(String), String) CODEC(ZSTD(1)),+ `attributes_map_float` Map(LowCardinality(String), Float64) CODEC(ZSTD(1)),+ `time_minute` DateTime ALIAS toStartOfMinute(timestamp),+ `attributes` Map(String, String) ALIAS mapApply((k, v) -> (left(k, -5), v), attributes_map_str),+ INDEX idx_metric_name_set metric_name TYPE set(100) GRANULARITY 1,+ INDEX idx_metric_type_set metric_type TYPE set(10) GRANULARITY 1,+ INDEX idx_attributes_str_keys mapKeys(attributes_map_str) TYPE bloom_filter(0.01) GRANULARITY 1,+ INDEX idx_attributes_str_values mapValues(attributes_map_str) TYPE bloom_filter(0.001) GRANULARITY 1,+ INDEX idx_observed_minmax observed_timestamp TYPE minmax GRANULARITY 1,+ PROJECTION projection_aggregate_counts+ (+ SELECT+ team_id,+ time_bucket,+ toStartOfMinute(timestamp),+ service_name,+ metric_name,+ metric_type,+ resource_fingerprint,+ count() AS event_count,+ sum(value) AS total_value,+ min(value) AS min_value,+ max(value) AS max_value+ GROUP BY+ team_id,+ time_bucket,+ toStartOfMinute(timestamp),+ service_name,+ metric_name,+ metric_type,+ resource_fingerprint+ )+ )+ ENGINE = ReplicatedMergeTree('/clickhouse/tables/77f1df52-4b43-11e9-910f-b8ca3a9b9f3e_noshard/posthog.metrics1', '{replica}-{shard}')+ PARTITION BY toDate(timestamp)+ PRIMARY KEY (team_id, time_bucket, service_name, metric_name, resource_fingerprint, timestamp)+ ORDER BY (team_id, time_bucket, service_name, metric_name, resource_fingerprint, timestamp)+ SETTINGS+ index_granularity_bytes = 104857600,+ index_granularity = 8192,+ ttl_only_drop_parts = 1++ '''+# ---# name: test_create_table_query_replicated_and_storage[partitioned_sharded_posthog_document_embeddings]'''diff --git a/posthog/hogql/database/database.py b/posthog/hogql/database/database.pyindex 15dd56ed3cf1..a20e983c05e2 100644--- a/posthog/hogql/database/database.py+++ b/posthog/hogql/database/database.py@@ -93,6 +93,7 @@ from posthog.hogql.database.schema.log_entries import (ReplayConsoleLogsLogEntriesTable,)from posthog.hogql.database.schema.logs import LogAttributesTable, LogsKafkaMetricsTable, LogsTable+from posthog.hogql.database.schema.metrics import MetricAttributesTable, MetricsKafkaMetricsTable, MetricsTablefrom posthog.hogql.database.schema.numbers import NumbersTablefrom posthog.hogql.database.schema.person_distinct_id_overrides import (PersonDistinctIdOverridesTable,@@ -279,6 +280,9 @@ def build_database_root_node(*, include_posthog_tables: bool = True) -> TableNod"session_replay_features": TableNode(name="session_replay_features", table=SessionReplayFeaturesTable()),+ "metrics": TableNode(name="metrics", table=MetricsTable()),+ "metric_attributes": TableNode(name="metric_attributes", table=MetricAttributesTable()),+ "metrics_kafka_metrics": TableNode(name="metrics_kafka_metrics", table=MetricsKafkaMetricsTable()),},),"system": SystemTables(),@@ -418,7 +422,13 @@ class Database(BaseModel):# These are the tables exposed via SQL editor autocomplete and data managementdef get_posthog_table_names(self, include_hidden: bool = False) -> list[str]:if include_hidden:- return sorted(ROOT_TABLES__DO_NOT_ADD_ANY_MORE.keys())+ root_keys = set(ROOT_TABLES__DO_NOT_ADD_ANY_MORE.keys())+ posthog_node = self.tables.children.get("posthog")+ if posthog_node and posthog_node.children:+ posthog_only_keys = {f"posthog.{k}" for k in posthog_node.children.keys() if k not in root_keys}+ else:+ posthog_only_keys = set()+ return sorted(root_keys | posthog_only_keys)return ["events",diff --git a/posthog/hogql/database/schema/metrics.py b/posthog/hogql/database/schema/metrics.pynew file mode 100644index 000000000000..bcceb024dc47--- /dev/null+++ b/posthog/hogql/database/schema/metrics.py@@ -0,0 +1,93 @@+from posthog.hogql.database.models import (+ BooleanDatabaseField,+ DANGEROUS_NoTeamIdCheckTable,+ DateTimeDatabaseField,+ FieldOrTable,+ FloatDatabaseField,+ IntegerDatabaseField,+ StringDatabaseField,+ StringJSONDatabaseField,+ Table,+)++from posthog.clickhouse.workload import Workload++# 50GB - limit for user-provided HogQL queries on metrics tables to prevent expensive full scans+HOGQL_MAX_BYTES_TO_READ_FOR_METRICS_USER_QUERIES = 50_000_000_000+++class MetricsTable(Table):+ workload: Workload | None = Workload.LOGS # reuse LOGS workload for now++ fields: dict[str, FieldOrTable] = {+ "uuid": StringDatabaseField(name="uuid", nullable=False),+ "team_id": IntegerDatabaseField(name="team_id", nullable=False),+ "trace_id": StringDatabaseField(name="trace_id", nullable=False),+ "span_id": StringDatabaseField(name="span_id", nullable=False),+ "time_bucket": DateTimeDatabaseField(name="time_bucket", nullable=False),+ "timestamp": DateTimeDatabaseField(name="timestamp", nullable=False),+ "observed_timestamp": DateTimeDatabaseField(name="observed_timestamp", nullable=False),+ "service_name": StringDatabaseField(name="service_name", nullable=False),+ "metric_name": StringDatabaseField(name="metric_name", nullable=False),+ "metric_type": StringDatabaseField(name="metric_type", nullable=False),+ "value": FloatDatabaseField(name="value", nullable=False),+ "count": IntegerDatabaseField(name="count", nullable=False),+ "histogram_bounds": StringJSONDatabaseField(name="histogram_bounds", nullable=False),+ "histogram_counts": StringJSONDatabaseField(name="histogram_counts", nullable=False),+ "unit": StringDatabaseField(name="unit", nullable=False),+ "aggregation_temporality": StringDatabaseField(name="aggregation_temporality", nullable=False),+ "is_monotonic": BooleanDatabaseField(name="is_monotonic", nullable=False),+ "resource_attributes": StringJSONDatabaseField(name="resource_attributes", nullable=False),+ "resource_fingerprint": IntegerDatabaseField(name="resource_fingerprint", nullable=False),+ "instrumentation_scope": StringDatabaseField(name="instrumentation_scope", nullable=False),+ "attributes": StringJSONDatabaseField(name="attributes", nullable=False),+ }++ def to_printed_clickhouse(self, context):+ return "metrics"++ def to_printed_hogql(self):+ return "metrics"+++class MetricAttributesTable(Table):+ workload: Workload | None = Workload.LOGS++ fields: dict[str, FieldOrTable] = {+ "team_id": IntegerDatabaseField(name="team_id", nullable=False),+ "time_bucket": DateTimeDatabaseField(name="time_bucket", nullable=False),+ "attribute_key": StringDatabaseField(name="attribute_key", nullable=False),+ "attribute_value": StringDatabaseField(name="attribute_value", nullable=False),+ "attribute_type": StringDatabaseField(name="attribute_type", nullable=False),+ "attribute_count": IntegerDatabaseField(name="attribute_count", nullable=False),+ "resource_fingerprint": IntegerDatabaseField(name="resource_fingerprint", nullable=False),+ "service_name": StringDatabaseField(name="service_name", nullable=False),+ }++ def to_printed_clickhouse(self, context):+ return "metric_attributes"++ def to_printed_hogql(self):+ return "metric_attributes"+++class MetricsKafkaMetricsTable(DANGEROUS_NoTeamIdCheckTable):+ """+ Table stores meta information about kafka consumption _not_ scoped to teams++ This is so we can find out the overall lag per partition and filter live metrics accordingly+ """++ workload: Workload | None = Workload.LOGS++ fields: dict[str, FieldOrTable] = {+ "_partition": IntegerDatabaseField(name="_partition", nullable=False),+ "_topic": StringDatabaseField(name="_topic", nullable=False),+ "max_observed_timestamp": DateTimeDatabaseField(name="max_observed_timestamp", nullable=False),+ }++ def to_printed_clickhouse(self, context):+ return "metrics_kafka_metrics"++ def to_printed_hogql(self):+ return "metrics_kafka_metrics"diff --git a/rust/capture-logs/src/kafka.rs b/rust/capture-logs/src/kafka.rsindex b0e7ba9f065a..d392ace4731f 100644--- a/rust/capture-logs/src/kafka.rs+++ b/rust/capture-logs/src/kafka.rs@@ -1,5 +1,7 @@use crate::avro_schema::AVRO_SCHEMA;use crate::log_record::KafkaLogRow;+use crate::metric_record::KafkaMetricRow;+use crate::metrics_avro_schema::METRICS_AVRO_SCHEMA;use crate::trace_record::KafkaTraceRow;use crate::traces_avro_schema::TRACES_AVRO_SCHEMA;use anyhow::anyhow;@@ -111,8 +113,10 @@ impl rdkafka::ClientContext for KafkaContext {pub struct KafkaSink {logs_producer: FutureProducer<KafkaContext>,traces_producer: FutureProducer<KafkaContext>,+ metrics_producer: FutureProducer<KafkaContext>,logs_topic: String,traces_topic: String,+ metrics_topic: String,}#[allow(clippy::too_many_arguments)]@@ -197,6 +201,7 @@ impl KafkaSink {config: KafkaConfig,logs_liveness: HealthHandle,traces_liveness: HealthHandle,+ metrics_liveness: HealthHandle,) -> anyhow::Result<KafkaSink> {info!("connecting to logs Kafka brokers at {}...",@@ -263,18 +268,69 @@ impl KafkaSink {let traces_producer =build_producer(traces_client_config, traces_liveness, "traces").await?;+ let metrics_hosts = config+ .kafka_metrics_hosts+ .clone()+ .unwrap_or_else(|| config.kafka_hosts.clone());+ info!(+ "connecting to metrics Kafka brokers at {}...",+ metrics_hosts+ );+ let metrics_client_config = build_client_config(+ &metrics_hosts,+ config.kafka_metrics_tls.unwrap_or(config.kafka_tls),+ &config+ .kafka_metrics_client_id+ .clone()+ .unwrap_or_else(|| config.kafka_client_id.clone()),+ &config+ .kafka_metrics_compression_codec+ .clone()+ .unwrap_or_else(|| config.kafka_compression_codec.clone()),+ &config+ .kafka_metrics_producer_acks+ .clone()+ .unwrap_or_else(|| config.kafka_producer_acks.clone()),+ config+ .kafka_metrics_producer_linger_ms+ .unwrap_or(config.kafka_producer_linger_ms),+ config+ .kafka_metrics_producer_queue_mib+ .unwrap_or(config.kafka_producer_queue_mib),+ config+ .kafka_metrics_message_timeout_ms+ .unwrap_or(config.kafka_message_timeout_ms),+ config+ .kafka_metrics_producer_message_max_bytes+ .unwrap_or(config.kafka_producer_message_max_bytes),+ config+ .kafka_metrics_producer_max_retries+ .unwrap_or(config.kafka_producer_max_retries),+ config+ .kafka_metrics_topic_metadata_refresh_interval_ms+ .unwrap_or(config.kafka_topic_metadata_refresh_interval_ms),+ config+ .kafka_metrics_metadata_max_age_ms+ .unwrap_or(config.kafka_metadata_max_age_ms),+ );+ let metrics_producer =+ build_producer(metrics_client_config, metrics_liveness, "metrics").await?;+Ok(KafkaSink {logs_producer,traces_producer,+ metrics_producer,logs_topic: config.kafka_topic,traces_topic: config.kafka_traces_topic,+ metrics_topic: config.kafka_metrics_topic,})}pub fn flush(&self) -> Result<(), KafkaError> {// TODO: hook it up on shutdownself.logs_producer.flush(Duration::new(30, 0))?;- self.traces_producer.flush(Duration::new(30, 0))+ self.traces_producer.flush(Duration::new(30, 0))?;+ self.metrics_producer.flush(Duration::new(30, 0))}#[allow(clippy::too_many_arguments)]@@ -406,4 +462,33 @@ impl KafkaSink {Ok(())}++ pub async fn write_metrics(+ &self,+ token: &str,+ rows: Vec<KafkaMetricRow>,+ uncompressed_bytes: u64,+ timestamps_overridden: u64,+ ) -> Result<(), anyhow::Error> {+ if rows.is_empty() {+ return Ok(());+ }++ if timestamps_overridden > 0 {+ counter!("capture_metrics_timestamps_overridden").increment(timestamps_overridden);+ }++ self.write_avro_batch(+ &self.metrics_producer,+ &self.metrics_topic,+ METRICS_AVRO_SCHEMA,+ token,+ &rows,+ uncompressed_bytes,+ timestamps_overridden,+ )+ .await?;++ Ok(())+ }}diff --git a/rust/capture-logs/src/lib.rs b/rust/capture-logs/src/lib.rsindex bd1555161410..c200d8158e60 100644--- a/rust/capture-logs/src/lib.rs+++ b/rust/capture-logs/src/lib.rs@@ -4,6 +4,8 @@ pub mod config;pub mod endpoints;pub mod kafka;pub mod log_record;+pub mod metric_record;+pub mod metrics_avro_schema;pub mod middleware;pub mod service;pub mod trace_record;diff --git a/rust/capture-logs/src/main.rs b/rust/capture-logs/src/main.rsindex 9c60a860ce39..0bfdac7e2978 100644--- a/rust/capture-logs/src/main.rs+++ b/rust/capture-logs/src/main.rs@@ -8,7 +8,9 @@ use capture_logs::endpoints::datadog;use capture_logs::kafka::KafkaSink;use capture_logs::middleware::translate_compression_query_param;use capture_logs::service::Service;-use capture_logs::service::{export_logs_http, export_traces_http, options_handler};+use capture_logs::service::{+ export_logs_http, export_metrics_http, export_traces_http, options_handler,+};use common_metrics::setup_metrics_routes;use std::future::ready;use std::net::SocketAddr;@@ -87,11 +89,15 @@ async fn main() {let traces_sink_liveness = health_registry.register("rdkafka_traces".to_string(), Duration::from_secs(30)).await;+ let metrics_sink_liveness = health_registry+ .register("rdkafka_metrics".to_string(), Duration::from_secs(30))+ .await;let kafka_sink = KafkaSink::new(config.kafka.clone(),logs_sink_liveness,traces_sink_liveness,+ metrics_sink_liveness,).await.expect("failed to start Kafka sink");@@ -146,6 +152,14 @@ async fn main() {"/i/v1/traces",post(export_traces_http).options(options_handler),)+ .route(+ "/v1/metrics",+ post(export_metrics_http).options(options_handler),+ )+ .route(+ "/i/v1/metrics",+ post(export_metrics_http).options(options_handler),+ ).route("/i/v1/logs/datadog",post(datadog::export_datadog_logs_http).options(options_handler),diff --git a/rust/capture-logs/src/metric_record.rs b/rust/capture-logs/src/metric_record.rsnew file mode 100644index 000000000000..681e2b042736--- /dev/null+++ b/rust/capture-logs/src/metric_record.rs@@ -0,0 +1,501 @@+use std::collections::HashMap;++use anyhow::Result;+use base64::{prelude::BASE64_STANDARD, Engine};+use chrono::serde::ts_microseconds;+use chrono::DateTime;+use chrono::TimeDelta;+use chrono::Utc;+use opentelemetry_proto::tonic::{+ common::v1::{+ any_value::{self, Value},+ AnyValue, InstrumentationScope, KeyValue,+ },+ metrics::v1::{+ exponential_histogram_data_point::Buckets, metric::Data, AggregationTemporality, Metric,+ },+ resource::v1::Resource,+};+use serde::{Deserialize, Serialize};+use serde_json::{json, Value as JsonValue};+use tracing::debug;+use uuid::Uuid;++#[derive(Debug, Serialize, Deserialize)]+pub struct KafkaMetricRow {+ pub uuid: String,+ pub trace_id: String,+ pub span_id: String,+ pub trace_flags: u32,+ #[serde(with = "ts_microseconds")]+ pub timestamp: DateTime<Utc>,+ #[serde(with = "ts_microseconds")]+ pub observed_timestamp: DateTime<Utc>,+ pub service_name: String,+ pub metric_name: String,+ pub metric_type: String,+ pub value: f64,+ pub count: i64,+ pub histogram_bounds: Vec<f64>,+ pub histogram_counts: Vec<i64>,+ pub unit: String,+ pub aggregation_temporality: String,+ pub is_monotonic: bool,+ pub resource_attributes: HashMap<String, String>,+ pub instrumentation_scope: String,+ pub attributes: HashMap<String, String>,+}++/// Flatten an OTEL Metric into one or more KafkaMetricRow records.+/// Each data point in the metric becomes a separate row.+pub fn flatten_metric(+ metric: Metric,+ resource: Option<&Resource>,+ scope: Option<&InstrumentationScope>,+) -> Result<(Vec<KafkaMetricRow>, u64)> {+ let metric_name = metric.name;+ let unit = metric.unit;+ let resource_attributes = extract_resource_attributes(resource);+ let service_name = extract_string_from_map(&resource_attributes, "service.name");+ let instrumentation_scope = match scope {+ Some(s) => format!("{}@{}", s.name, s.version),+ None => String::new(),+ };++ let mut rows = Vec::new();+ let mut timestamps_overridden: u64 = 0;++ let Some(data) = metric.data else {+ return Ok((rows, timestamps_overridden));+ };++ match data {+ Data::Gauge(gauge) => {+ for dp in gauge.data_points {+ let (row, overridden) = build_number_row(+ &metric_name,+ "gauge",+ &unit,+ &resource_attributes,+ &service_name,+ &instrumentation_scope,+ dp.time_unix_nano,+ dp.start_time_unix_nano,+ &dp.attributes,+ number_value(&dp.value),+ None,+ None,+ &dp.exemplars,+ dp.flags,+ )?;+ if overridden {+ timestamps_overridden += 1;+ }+ rows.push(row);+ }+ }+ Data::Sum(sum) => {+ let temporality = temporality_str(sum.aggregation_temporality);+ let is_monotonic = sum.is_monotonic;+ for dp in sum.data_points {+ let (mut row, overridden) = build_number_row(+ &metric_name,+ "sum",+ &unit,+ &resource_attributes,+ &service_name,+ &instrumentation_scope,+ dp.time_unix_nano,+ dp.start_time_unix_nano,+ &dp.attributes,+ number_value(&dp.value),+ None,+ None,+ &dp.exemplars,+ dp.flags,+ )?;+ row.aggregation_temporality = temporality.clone();+ row.is_monotonic = is_monotonic;+ if overridden {+ timestamps_overridden += 1;+ }+ rows.push(row);+ }+ }+ Data::Histogram(hist) => {+ let temporality = temporality_str(hist.aggregation_temporality);+ for dp in hist.data_points {+ let value = dp.sum.unwrap_or(0.0);+ let count = dp.count as i64;+ let bounds = dp.explicit_bounds.clone();+ let counts: Vec<i64> = dp.bucket_counts.iter().map(|c| *c as i64).collect();++ let (mut row, overridden) = build_number_row(+ &metric_name,+ "histogram",+ &unit,+ &resource_attributes,+ &service_name,+ &instrumentation_scope,+ dp.time_unix_nano,+ dp.start_time_unix_nano,+ &dp.attributes,+ value,+ Some(bounds),+ Some(counts),+ &dp.exemplars,+ dp.flags,+ )?;+ row.count = count;+ row.aggregation_temporality = temporality.clone();+ if overridden {+ timestamps_overridden += 1;+ }+ rows.push(row);+ }+ }+ Data::ExponentialHistogram(hist) => {+ let temporality = temporality_str(hist.aggregation_temporality);+ for dp in hist.data_points {+ let value = dp.sum.unwrap_or(0.0);+ let count = dp.count as i64;++ // Flatten exponential histogram buckets into explicit bounds/counts+ let (bounds, counts) = flatten_exponential_buckets(+ dp.scale,+ dp.zero_count,+ &dp.positive,+ &dp.negative,+ );++ let (mut row, overridden) = build_number_row(+ &metric_name,+ "exponential_histogram",+ &unit,+ &resource_attributes,+ &service_name,+ &instrumentation_scope,+ dp.time_unix_nano,+ dp.start_time_unix_nano,+ &dp.attributes,+ value,+ Some(bounds),+ Some(counts),+ &dp.exemplars,+ dp.flags,+ )?;+ row.count = count;+ row.aggregation_temporality = temporality.clone();+ if overridden {+ timestamps_overridden += 1;+ }+ rows.push(row);+ }+ }+ Data::Summary(summary) => {+ for dp in summary.data_points {+ let value = dp.sum;+ let count = dp.count as i64;++ // Store quantile values as histogram_bounds (quantiles) and histogram_counts (values)+ let bounds: Vec<f64> = dp.quantile_values.iter().map(|q| q.quantile).collect();+ let counts: Vec<i64> = dp+ .quantile_values+ .iter()+ .map(|q| q.value.to_bits() as i64)+ .collect();++ let (mut row, overridden) = build_number_row(+ &metric_name,+ "summary",+ &unit,+ &resource_attributes,+ &service_name,+ &instrumentation_scope,+ dp.time_unix_nano,+ dp.start_time_unix_nano,+ &dp.attributes,+ value,+ Some(bounds),+ Some(counts),+ &[],+ dp.flags,+ )?;+ row.count = count;+ if overridden {+ timestamps_overridden += 1;+ }+ rows.push(row);+ }+ }+ }++ debug!(+ "Flattened metric '{}' into {} rows",+ metric_name,+ rows.len()+ );+ Ok((rows, timestamps_overridden))+}++#[allow(clippy::too_many_arguments)]+fn build_number_row(+ metric_name: &str,+ metric_type: &str,+ unit: &str,+ resource_attributes: &HashMap<String, String>,+ service_name: &str,+ instrumentation_scope: &str,+ time_unix_nano: u64,+ _start_time_unix_nano: u64,+ dp_attributes: &[KeyValue],+ value: f64,+ histogram_bounds: Option<Vec<f64>>,+ histogram_counts: Option<Vec<i64>>,+ _exemplars: &[opentelemetry_proto::tonic::metrics::v1::Exemplar],+ flags: u32,+) -> Result<(KafkaMetricRow, bool)> {+ let raw_timestamp = match time_unix_nano {+ 0 => Utc::now(),+ _ => DateTime::<Utc>::from_timestamp_nanos(time_unix_nano.try_into()?),+ };++ let (timestamp, original_timestamp) = override_timestamp(raw_timestamp);+ let was_overridden = original_timestamp.is_some();++ let mut attributes: HashMap<String, String> = dp_attributes+ .iter()+ .map(|kv| {+ (+ kv.key.clone(),+ any_value_to_string(kv.value.clone().unwrap_or(AnyValue {+ value: Some(Value::StringValue(String::new())),+ })),+ )+ })+ .collect();++ if let Some(original) = original_timestamp {+ attributes.insert("$originalTimestamp".to_string(), original.to_rfc3339());+ }++ let observed_timestamp = Utc::now();++ let row = KafkaMetricRow {+ uuid: Uuid::now_v7().to_string(),+ trace_id: String::new(),+ span_id: String::new(),+ trace_flags: flags,+ timestamp,+ observed_timestamp,+ service_name: service_name.to_string(),+ metric_name: metric_name.to_string(),+ metric_type: metric_type.to_string(),+ value,+ count: 1,+ histogram_bounds: histogram_bounds.unwrap_or_default(),+ histogram_counts: histogram_counts.unwrap_or_default(),+ unit: unit.to_string(),+ aggregation_temporality: String::new(),+ is_monotonic: false,+ resource_attributes: resource_attributes.clone(),+ instrumentation_scope: instrumentation_scope.to_string(),+ attributes,+ };++ Ok((row, was_overridden))+}++/// Flatten exponential histogram buckets into explicit bounds and counts.+fn flatten_exponential_buckets(+ scale: i32,+ zero_count: u64,+ positive: &Option<Buckets>,+ negative: &Option<Buckets>,+) -> (Vec<f64>, Vec<i64>) {+ let mut bounds = Vec::new();+ let mut counts = Vec::new();++ // Add zero bucket+ if zero_count > 0 {+ bounds.push(0.0);+ counts.push(zero_count as i64);+ }++ let base = 2.0_f64.powf(2.0_f64.powi(-scale));++ if let Some(neg) = negative {+ for (i, &count) in neg.bucket_counts.iter().enumerate() {+ let idx = neg.offset as i64 + i as i64;+ let bound = -base.powf(idx as f64);+ bounds.push(bound);+ counts.push(count as i64);+ }+ }++ if let Some(pos) = positive {+ for (i, &count) in pos.bucket_counts.iter().enumerate() {+ let idx = pos.offset as i64 + i as i64;+ let bound = base.powf(idx as f64);+ bounds.push(bound);+ counts.push(count as i64);+ }+ }++ (bounds, counts)+}++fn number_value(+ value: &Option<opentelemetry_proto::tonic::metrics::v1::number_data_point::Value>,+) -> f64 {+ match value {+ Some(opentelemetry_proto::tonic::metrics::v1::number_data_point::Value::AsDouble(d)) => *d,+ Some(opentelemetry_proto::tonic::metrics::v1::number_data_point::Value::AsInt(i)) => {+ *i as f64+ }+ None => 0.0,+ }+}++fn temporality_str(temporality: i32) -> String {+ match AggregationTemporality::try_from(temporality) {+ Ok(AggregationTemporality::Delta) => "delta".to_string(),+ Ok(AggregationTemporality::Cumulative) => "cumulative".to_string(),+ _ => "unspecified".to_string(),+ }+}++const TIMESTAMP_OVERRIDE_HOURS: i64 = 24;++pub fn override_timestamp(timestamp: DateTime<Utc>) -> (DateTime<Utc>, Option<DateTime<Utc>>) {+ let now = Utc::now();+ let max_delta = TimeDelta::hours(TIMESTAMP_OVERRIDE_HOURS);++ if timestamp < now - max_delta || timestamp > now + max_delta {+ (now, Some(timestamp))+ } else {+ (timestamp, None)+ }+}++fn extract_string_from_map(attributes: &HashMap<String, String>, key: &str) -> String {+ if let Some(value) = attributes.get(key) {+ if let Ok(JsonValue::String(value)) = serde_json::from_str::<JsonValue>(value) {+ value.to_string()+ } else {+ value.to_string()+ }+ } else {+ String::new()+ }+}++fn extract_resource_attributes(resource: Option<&Resource>) -> HashMap<String, String> {+ let Some(resource) = resource else {+ return HashMap::new();+ };++ resource+ .attributes+ .iter()+ .map(|kv| {+ (+ kv.key.clone(),+ any_value_to_string(kv.value.clone().unwrap_or(AnyValue {+ value: Some(Value::StringValue(String::new())),+ })),+ )+ })+ .collect()+}++fn any_value_to_json(value: AnyValue) -> JsonValue {+ match value.value {+ Some(value_enum) => match value_enum {+ any_value::Value::StringValue(s) => json!(s),+ any_value::Value::BoolValue(b) => json!(b),+ any_value::Value::IntValue(i) => json!(i),+ any_value::Value::DoubleValue(d) => json!(d),+ any_value::Value::ArrayValue(arr) => {+ json!(arr+ .values+ .into_iter()+ .map(any_value_to_json)+ .collect::<Vec<_>>())+ }+ any_value::Value::KvlistValue(kvlist) => {+ let mut map = HashMap::new();+ for kv in kvlist.values.into_iter() {+ if let Some(v) = kv.value {+ map.insert(kv.key.clone(), any_value_to_json(v));+ }+ }+ json!(map)+ }+ any_value::Value::BytesValue(b) => {+ json!(BASE64_STANDARD.encode(b))+ }+ },+ None => JsonValue::Null,+ }+}++fn any_value_to_string(value: AnyValue) -> String {+ any_value_to_json(value).to_string()+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn test_override_timestamp_within_range_is_unchanged() {+ let now = Utc::now();+ let one_hour_ago = now - TimeDelta::hours(1);+ let (final_ts, original) = override_timestamp(one_hour_ago);+ assert_eq!(final_ts, one_hour_ago);+ assert!(original.is_none());+ }++ #[test]+ fn test_override_timestamp_far_past_is_overridden() {+ let now = Utc::now();+ let two_days_ago = now - TimeDelta::hours(48);+ let (final_ts, original) = override_timestamp(two_days_ago);+ assert!((final_ts - now).num_seconds().abs() < 2);+ assert_eq!(original.unwrap(), two_days_ago);+ }++ #[test]+ fn test_override_timestamp_far_future_is_overridden() {+ let now = Utc::now();+ let two_days_ahead = now + TimeDelta::hours(48);+ let (final_ts, original) = override_timestamp(two_days_ahead);+ assert!((final_ts - now).num_seconds().abs() < 2);+ assert_eq!(original.unwrap(), two_days_ahead);+ }++ #[test]+ fn test_number_value_as_double() {+ use opentelemetry_proto::tonic::metrics::v1::number_data_point::Value;+ assert_eq!(number_value(&Some(Value::AsDouble(3.125))), 3.125);+ }++ #[test]+ fn test_number_value_as_int() {+ use opentelemetry_proto::tonic::metrics::v1::number_data_point::Value;+ assert_eq!(number_value(&Some(Value::AsInt(42))), 42.0);+ }++ #[test]+ fn test_number_value_none() {+ assert_eq!(number_value(&None), 0.0);+ }++ #[test]+ fn test_temporality_str() {+ assert_eq!(temporality_str(1), "delta");+ assert_eq!(temporality_str(2), "cumulative");+ assert_eq!(temporality_str(0), "unspecified");+ }+}diff --git a/rust/capture-logs/src/metrics_avro_schema.rs b/rust/capture-logs/src/metrics_avro_schema.rsnew file mode 100644index 000000000000..7b19f07d4b5b--- /dev/null+++ b/rust/capture-logs/src/metrics_avro_schema.rs@@ -0,0 +1,121 @@+pub const METRICS_AVRO_SCHEMA: &str = r#"+{+"type": "record",+"name": "MetricRecord",+"doc": "Schema for an OTEL metric data point.",+"fields": [+ {+ "name": "uuid",+ "type": ["null", "string"],+ "doc": "Unique identifier for the metric record."+ },+ {+ "name": "trace_id",+ "type": ["null", "bytes"],+ "doc": "Identifier for the trace this metric is associated with."+ },+ {+ "name": "span_id",+ "type": ["null", "bytes"],+ "doc": "Identifier for the span within the trace."+ },+ {+ "name": "trace_flags",+ "type": ["null", "int"],+ "doc": "Flags associated with the trace."+ },+ {+ "name": "timestamp",+ "type": ["null", {+ "type": "long",+ "logicalType": "timestamp-micros"+ }],+ "doc": "The primary timestamp of the data point, in microseconds since epoch."+ },+ {+ "name": "observed_timestamp",+ "type": ["null", {+ "type": "long",+ "logicalType": "timestamp-micros"+ }],+ "doc": "The timestamp when the metric was ingested, in microseconds since epoch."+ },+ {+ "name": "service_name",+ "type": ["null", "string"],+ "doc": "The name of the service that generated the metric."+ },+ {+ "name": "metric_name",+ "type": ["null", "string"],+ "doc": "The name of the metric (e.g., 'system.cpu.utilization')."+ },+ {+ "name": "metric_type",+ "type": ["null", "string"],+ "doc": "The type of metric: gauge, sum, histogram, summary, exponential_histogram."+ },+ {+ "name": "value",+ "type": ["null", "double"],+ "doc": "The primary numeric value of the data point."+ },+ {+ "name": "count",+ "type": ["null", "long"],+ "doc": "Count for histogram/summary data points, or 1 for simple data points."+ },+ {+ "name": "histogram_bounds",+ "type": ["null", {+ "type": "array",+ "items": "double"+ }],+ "doc": "Explicit bucket boundaries for histogram metrics."+ },+ {+ "name": "histogram_counts",+ "type": ["null", {+ "type": "array",+ "items": "long"+ }],+ "doc": "Bucket counts for histogram metrics."+ },+ {+ "name": "unit",+ "type": ["null", "string"],+ "doc": "The unit of the metric (e.g., 'bytes', 'seconds', '1')."+ },+ {+ "name": "aggregation_temporality",+ "type": ["null", "string"],+ "doc": "Aggregation temporality: delta or cumulative."+ },+ {+ "name": "is_monotonic",+ "type": ["null", "boolean"],+ "doc": "Whether the sum is monotonic (counter vs up-down counter)."+ },+ {+ "name": "resource_attributes",+ "type": ["null", {+ "type": "map",+ "values": "string"+ }],+ "doc": "Attributes describing the resource that produced the metric."+ },+ {+ "name": "instrumentation_scope",+ "type": ["null", "string"],+ "doc": "The name of the library or framework that captured the metric."+ },+ {+ "name": "attributes",+ "type": ["null", {+ "type": "map",+ "values": "string"+ }],+ "doc": "A map of custom string-valued attributes associated with the data point."+ }+]+}"#;diff --git a/rust/capture-logs/src/service.rs b/rust/capture-logs/src/service.rsindex 8422a4fca84e..f79159d8ed21 100644--- a/rust/capture-logs/src/service.rs+++ b/rust/capture-logs/src/service.rs@@ -1,4 +1,5 @@use crate::log_record::KafkaLogRow;+use crate::metric_record::{flatten_metric, KafkaMetricRow};use crate::trace_record::KafkaTraceRow;use axum::{extract::Query,@@ -9,6 +10,7 @@ use axum::{use bytes::Bytes;use limiters::token_dropper::TokenDropper;use opentelemetry_proto::tonic::collector::logs::v1::ExportLogsServiceRequest;+use opentelemetry_proto::tonic::collector::metrics::v1::ExportMetricsServiceRequest;use opentelemetry_proto::tonic::collector::trace::v1::ExportTraceServiceRequest;use prost::Message;use serde::Deserialize;@@ -442,3 +444,180 @@ pub async fn export_traces_http(Ok(Json(json!({})))}++/// Parse OpenTelemetry metric message from JSON bytes.+///+/// Supports both single JSON objects and JSONL format (JSON Lines).+/// For JSONL, multiple ExportMetricsServiceRequest objects are parsed and merged+/// into a single request by combining their resource_metrics arrays.+pub fn parse_otel_metrics_message(+ json_bytes: &Bytes,+) -> Result<ExportMetricsServiceRequest, anyhow::Error> {+ if let Ok(mut v) = serde_json::from_slice::<Value>(json_bytes) {+ patch_otel_json(&mut v);+ let result: ExportMetricsServiceRequest = serde_json::from_value(v)?;+ return Ok(result);+ }++ let json_str = std::str::from_utf8(json_bytes)?;+ let lines: Vec<&str> = json_str+ .lines()+ .filter(|line| !line.trim().is_empty())+ .collect();++ let mut merged_request = ExportMetricsServiceRequest {+ resource_metrics: Vec::new(),+ };++ for line in lines {+ let mut v: Value = serde_json::from_str(line)?;+ patch_otel_json(&mut v);+ let request: ExportMetricsServiceRequest = serde_json::from_value(v)?;+ merged_request+ .resource_metrics+ .extend(request.resource_metrics);+ }++ Ok(merged_request)+}++#[instrument(skip_all, fields(+ token = tracing::field::Empty,+ content_type = %headers.get("content-type")+ .and_then(|v| v.to_str().ok())+ .unwrap_or(""),+ user_agent = %headers.get("user-agent")+ .and_then(|v| v.to_str().ok())+ .unwrap_or(""),+ content_length = %headers.get("content-length")+ .and_then(|v| v.to_str().ok())+ .unwrap_or(""),+ content_encoding = %headers.get("content-encoding")+ .and_then(|v| v.to_str().ok())+ .unwrap_or("")))+]+pub async fn export_metrics_http(+ State(service): State<Service>,+ Query(query_params): Query<QueryParams>,+ headers: HeaderMap,+ body: Bytes,+) -> Result<Json<serde_json::Value>, (StatusCode, Json<serde_json::Value>)> {+ if !headers.contains_key("Authorization") && query_params.token.is_none() {+ error!("No token provided");+ return Err((+ StatusCode::UNAUTHORIZED,+ Json(json!({"error": "No token provided"})),+ ));+ }++ let token = if headers.contains_key("Authorization") {+ match headers["Authorization"]+ .to_str()+ .unwrap_or("")+ .split("Bearer ")+ .last()+ {+ Some(token) if !token.is_empty() => token,+ _ => {+ error!("No token provided");+ return Err((+ StatusCode::UNAUTHORIZED,+ Json(json!({"error": "No token provided"})),+ ));+ }+ }+ } else {+ match query_params.token {+ Some(ref token) if !token.is_empty() => token,+ _ => {+ error!("No token provided");+ return Err((+ StatusCode::UNAUTHORIZED,+ Json(json!({"error": "No token provided"})),+ ));+ }+ }+ };++ if service.token_dropper.should_drop(token, "") {+ return Err((+ StatusCode::UNAUTHORIZED,+ Json(json!({"error": "Invalid token"})),+ ));+ }++ tracing::Span::current().record("token", token);++ let export_request = match ExportMetricsServiceRequest::decode(body.as_ref()) {+ Ok(request) => request,+ Err(proto_err) => match parse_otel_metrics_message(&body) {+ Ok(request) => request,+ Err(json_err) => {+ if let Err(e) =+ File::create("/tmp/last_failed_metric_event.txt").and_then(|mut file| {+ file.write_all(token.as_bytes())+ .and_then(|_| file.write_all(&body))+ })+ {+ error!("Failed to write last failed metric event to file: {}", e);+ }+ error!(+ "Failed to decode JSON: {} or Protobuf: {}",+ json_err, proto_err+ );+ return Err((+ StatusCode::BAD_REQUEST,+ Json(+ json!({"error": format!("Failed to decode JSON: {} or Protobuf: {}", json_err, proto_err)}),+ ),+ ));+ }+ },+ };++ let mut rows: Vec<KafkaMetricRow> = Vec::new();+ let mut timestamps_overridden: u64 = 0;++ for resource_metrics in &export_request.resource_metrics {+ for scope_metrics in &resource_metrics.scope_metrics {+ for metric in &scope_metrics.metrics {+ let (metric_rows, overridden) = match flatten_metric(+ metric.clone(),+ resource_metrics.resource.as_ref(),+ scope_metrics.scope.as_ref(),+ ) {+ Ok(result) => result,+ Err(e) => {+ error!("Failed to flatten metric: {e}");+ return Err((+ StatusCode::BAD_REQUEST,+ Json(json!({"error": "Bad input format provided"})),+ ));+ }+ };+ timestamps_overridden += overridden;+ rows.extend(metric_rows);+ }+ }+ }++ let row_count = rows.len();+ if let Err(e) = service+ .sink+ .write_metrics(token, rows, body.len() as u64, timestamps_overridden)+ .await+ {+ error!("Failed to send metrics to Kafka: {}", e);+ return Err((+ StatusCode::INTERNAL_SERVER_ERROR,+ Json(json!({"error": "Internal server error"})),+ ));+ } else {+ debug!(+ "Successfully sent {} metric data points to Kafka",+ row_count+ );+ }++ Ok(Json(json!({})))+}diff --git a/rust/capture/src/config.rs b/rust/capture/src/config.rsindex 5a1a9ce1988c..80243d725fba 100644--- a/rust/capture/src/config.rs+++ b/rust/capture/src/config.rs@@ -273,6 +273,8 @@ pub struct KafkaConfig {pub kafka_topic: String,#[envconfig(default = "ingestion-traces")]pub kafka_traces_topic: String,+ #[envconfig(default = "ingestion-metrics")]+ pub kafka_metrics_topic: String,#[envconfig(default = "events_plugin_ingestion_overflow")]pub kafka_overflow_topic: String,#[envconfig(default = "events_plugin_ingestion_historical")]@@ -342,4 +344,19 @@ pub struct KafkaConfig {pub kafka_traces_producer_max_retries: Option<u32>,pub kafka_traces_topic_metadata_refresh_interval_ms: Option<u32>,pub kafka_traces_metadata_max_age_ms: Option<u32>,++ // Metrics-cluster overrides (consumed by capture-logs). When unset, the+ // metrics producer reuses the corresponding `kafka_*` value above.+ pub kafka_metrics_hosts: Option<String>,+ pub kafka_metrics_tls: Option<bool>,+ pub kafka_metrics_client_id: Option<String>,+ pub kafka_metrics_compression_codec: Option<String>,+ pub kafka_metrics_producer_acks: Option<String>,+ pub kafka_metrics_producer_linger_ms: Option<u32>,+ pub kafka_metrics_producer_queue_mib: Option<u32>,+ pub kafka_metrics_message_timeout_ms: Option<u32>,+ pub kafka_metrics_producer_message_max_bytes: Option<u32>,+ pub kafka_metrics_producer_max_retries: Option<u32>,+ pub kafka_metrics_topic_metadata_refresh_interval_ms: Option<u32>,+ pub kafka_metrics_metadata_max_age_ms: Option<u32>,}diff --git a/rust/capture/src/sinks/kafka.rs b/rust/capture/src/sinks/kafka.rsindex 30a870eb9047..5d406b5633f1 100644--- a/rust/capture/src/sinks/kafka.rs+++ b/rust/capture/src/sinks/kafka.rs@@ -786,6 +786,7 @@ mod tests {kafka_replay_overflow_topic: "session_recording_snapshot_item_overflow".to_string(),kafka_dlq_topic: "events_plugin_ingestion_dlq".to_string(),kafka_traces_topic: "traces_ingestion".to_string(),+ kafka_metrics_topic: "metrics_ingestion".to_string(),kafka_tls: false,kafka_client_id: "".to_string(),kafka_metadata_max_age_ms: 60000,@@ -816,6 +817,18 @@ mod tests {kafka_traces_producer_max_retries: None,kafka_traces_topic_metadata_refresh_interval_ms: None,kafka_traces_metadata_max_age_ms: None,+ kafka_metrics_hosts: None,+ kafka_metrics_tls: None,+ kafka_metrics_client_id: None,+ kafka_metrics_compression_codec: None,+ kafka_metrics_producer_acks: None,+ kafka_metrics_producer_linger_ms: None,+ kafka_metrics_producer_queue_mib: None,+ kafka_metrics_message_timeout_ms: None,+ kafka_metrics_producer_message_max_bytes: None,+ kafka_metrics_producer_max_retries: None,+ kafka_metrics_topic_metadata_refresh_interval_ms: None,+ kafka_metrics_metadata_max_age_ms: None,};let sink = KafkaSink::new(config, handle).awaitdiff --git a/rust/capture/src/v1/quota_limiter_shim.rs b/rust/capture/src/v1/quota_limiter_shim.rsindex 824d9d371253..e2772dda69b4 100644--- a/rust/capture/src/v1/quota_limiter_shim.rs+++ b/rust/capture/src/v1/quota_limiter_shim.rs@@ -161,6 +161,7 @@ mod tests {kafka_replay_overflow_topic: "session_recording_snapshot_item_overflow".to_string(),kafka_dlq_topic: "events_plugin_ingestion_dlq".to_string(),kafka_traces_topic: "ingestion_traces".to_string(),+ kafka_metrics_topic: "ingestion_metrics".to_string(),kafka_tls: false,kafka_client_id: String::new(),kafka_metadata_max_age_ms: 60000,@@ -191,6 +192,18 @@ mod tests {kafka_traces_producer_max_retries: None,kafka_traces_topic_metadata_refresh_interval_ms: None,kafka_traces_metadata_max_age_ms: None,+ kafka_metrics_hosts: None,+ kafka_metrics_tls: None,+ kafka_metrics_client_id: None,+ kafka_metrics_compression_codec: None,+ kafka_metrics_producer_acks: None,+ kafka_metrics_producer_linger_ms: None,+ kafka_metrics_producer_queue_mib: None,+ kafka_metrics_message_timeout_ms: None,+ kafka_metrics_producer_message_max_bytes: None,+ kafka_metrics_producer_max_retries: None,+ kafka_metrics_topic_metadata_refresh_interval_ms: None,+ kafka_metrics_metadata_max_age_ms: None,},otel_url: None,otel_sampling_rate: 0.0,diff --git a/rust/capture/tests/common/utils.rs b/rust/capture/tests/common/utils.rsindex 595b9352c14d..aa478e3d8684 100644--- a/rust/capture/tests/common/utils.rs+++ b/rust/capture/tests/common/utils.rs@@ -84,6 +84,7 @@ pub static DEFAULT_CONFIG: Lazy<Config> = Lazy::new(|| Config {kafka_replay_overflow_topic: "session_recording_snapshot_item_overflow".to_string(),kafka_dlq_topic: "events_plugin_ingestion_dlq".to_string(),kafka_traces_topic: "ingestion_traces".to_string(),+ kafka_metrics_topic: "ingestion_metrics".to_string(),kafka_tls: false,kafka_client_id: "".to_string(),kafka_metadata_max_age_ms: 60000,@@ -114,6 +115,18 @@ pub static DEFAULT_CONFIG: Lazy<Config> = Lazy::new(|| Config {kafka_traces_producer_max_retries: None,kafka_traces_topic_metadata_refresh_interval_ms: None,kafka_traces_metadata_max_age_ms: None,+ kafka_metrics_hosts: None,+ kafka_metrics_tls: None,+ kafka_metrics_client_id: None,+ kafka_metrics_compression_codec: None,+ kafka_metrics_producer_acks: None,+ kafka_metrics_producer_linger_ms: None,+ kafka_metrics_producer_queue_mib: None,+ kafka_metrics_message_timeout_ms: None,+ kafka_metrics_producer_message_max_bytes: None,+ kafka_metrics_producer_max_retries: None,+ kafka_metrics_topic_metadata_refresh_interval_ms: None,+ kafka_metrics_metadata_max_age_ms: None,},otel_url: None,otel_sampling_rate: 0.0,