: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(capture-apm-metrics): split metrics capture into its own binary (#96726)
Frank Hamand6883cb3e2f9a
diff --git a/.github/rust-images.yml b/.github/rust-images.ymlindex 499cd4806d14..13be47c87630 100644--- a/.github/rust-images.yml+++ b/.github/rust-images.yml@@ -85,9 +85,16 @@dockerfile: ./rust/Dockerfileproject: 4ppc15q4bv+# capture-logs and capture-apm-metrics build the same crates, so they share+# the capture-apm Depot project and its layer cache.- image: capture-logsdockerfile: ./rust/Dockerfile- project: c1bwj4j4qg+ project: 7fzvz4wcsw++# Metrics half of capture-logs: same library, metrics routes only.+- image: capture-apm-metrics+ dockerfile: ./rust/Dockerfile+ project: 7fzvz4wcsw- image: ingestion-consumerdockerfile: ./rust/Dockerfilediff --git a/.github/workflows/ci-rust.yml b/.github/workflows/ci-rust.ymlindex 13748a873c6d..25a966934e72 100644--- a/.github/workflows/ci-rust.yml+++ b/.github/workflows/ci-rust.yml@@ -125,6 +125,7 @@ jobs:"capture": 102,"capture-load-gen": 38,"capture-logs": 87,+ "capture-apm-metrics": 5,"cohort-core": 22,"cohort-event-shuffler": 25,"cohort-seeder": 77,diff --git a/.github/workflows/rust-docker-build.yml b/.github/workflows/rust-docker-build.ymlindex 5aed6d1b5019..e29e17a0de52 100644--- a/.github/workflows/rust-docker-build.yml+++ b/.github/workflows/rust-docker-build.yml@@ -177,6 +177,9 @@ jobs:- release: capture-logsdigest_key: capture-logsvalues_key: image+ - release: capture-apm-metrics+ digest_key: capture-apm-metrics+ values_key: image- release: ingestion-consumerdigest_key: ingestion-consumervalues_key: imagediff --git a/bin/mprocs.yaml b/bin/mprocs.yamlindex 5d1b2bdaefbc..936cad1c5726 100755--- a/bin/mprocs.yaml+++ b/bin/mprocs.yaml@@ -404,6 +404,15 @@ procs:layer: Ingestion pipelinetech: Rust+ capture-apm-metrics:+ shell: |-+ bin/wait-for-docker && \+ bin/start-rust-service capture-apm-metrics+ capability: metrics_ingestion+ groups:+ layer: Ingestion pipeline+ tech: Rust+usage-ingestion:shell: |-bin/wait-for-docker && \diff --git a/bin/send-dev-metrics.sh b/bin/send-dev-metrics.shindex a624e24bf545..7fb0c390cb1b 100755--- a/bin/send-dev-metrics.sh+++ b/bin/send-dev-metrics.sh@@ -1,6 +1,6 @@#!/usr/bin/env bash# Smoke-test the metrics ingest chain by POSTing a synthetic OTLP payload to-# capture-logs. Same shape as nodejs/src/logs-ingestion/sampling-seed-services-curl.sh.+# capture-apm-metrics. Same shape as nodejs/src/logs-ingestion/sampling-seed-services-curl.sh.## Usage:# # Local dev (default — same path logs scripts use):@@ -18,7 +18,7 @@set -euo pipefail# Default to the same local-OTel-collector endpoint the logs seed scripts use.-# `otel-collector-config.dev.yaml` routes /v1/metrics to capture-logs:4320 internally.+# `otel-collector-config.dev.yaml` routes /v1/metrics to capture-apm-metrics:4321 internally.ENDPOINT="${ENDPOINT:-http://localhost:4318/v1/metrics}"TOKEN="${TOKEN:-}"@@ -114,7 +114,7 @@ EOFreturn 1fiif [ "$http" = "000" ] || [ "$http" = "" ]; then- echo " ⚠️ Could not reach $ENDPOINT — is your local OTel collector / capture-logs running? (\`hogli start\`)" >&2+ echo " ⚠️ Could not reach $ENDPOINT — is your local OTel collector / capture-apm-metrics running? (\`hogli start\`)" >&2return 1fiif [ "$http" != "200" ] && [ "$http" != "202" ]; thendiff --git a/bin/start-rust-service b/bin/start-rust-serviceindex 2a9d8fbf4e6c..e450bb824ebd 100755--- a/bin/start-rust-service+++ b/bin/start-rust-service@@ -114,6 +114,17 @@ case "$RS_SVC" inexport KAFKA_METRICS_TOPIC=metrics_ingestion;;+ capture-apm-metrics)+ export RUST_LOG=debug,rdkafka=warn+ export RUST_BACKTRACE=1+ export BIND_HOST=0.0.0.0+ export BIND_PORT=4321 # Next to capture-logs (4320)+ export MANAGEMENT_BIND_PORT=3312+ export KAFKA_HOSTS=localhost:9092+ export KAFKA_TOPIC=logs_ingestion+ export KAFKA_METRICS_TOPIC=metrics_ingestion+ ;;+cymbal)# Only cymbal crates at debug; everything else at info to keep the dev# log readable. rdkafka stays explicitly at warn because its info-leveldiff --git a/devenv/intent-map.yaml b/devenv/intent-map.yamlindex 28f1eeff247b..da342387d659 100644--- a/devenv/intent-map.yaml+++ b/devenv/intent-map.yaml@@ -172,7 +172,12 @@ capabilities:docker_profiles: [observability]logs_ingestion:- description: 'OTEL logs, traces, and metrics capture service'+ description: 'OTEL logs and traces capture service'+ requires: [event_ingestion]+ docker_profiles: [observability]++ metrics_ingestion:+ description: 'OTEL and Prometheus remote-write metrics capture service'requires: [event_ingestion]docker_profiles: [observability]@@ -385,7 +390,7 @@ intents:metrics:description: 'Metric ingestion and viewing'- capabilities: [event_ingestion, property_definitions, property_values, logs_ingestion, nodejs_metrics]+ capabilities: [event_ingestion, property_definitions, property_values, metrics_ingestion, nodejs_metrics]workflows:description: 'Workflow automation and orchestration'diff --git a/docker-compose.dev.yml b/docker-compose.dev.ymlindex af88df61dcf1..13edcfea83ad 100644--- a/docker-compose.dev.yml+++ b/docker-compose.dev.yml@@ -26,6 +26,7 @@ services:- 'capture:host-gateway'- 'capture-ai:host-gateway'- 'capture-logs:host-gateway'+ - 'capture-apm-metrics:host-gateway'- 'replay-capture:host-gateway'- 'feature-flags:host-gateway'- 'hypercache-server:host-gateway'@@ -62,7 +63,12 @@ services:@capture-logs {path /i/v1/logspath /i/v1/traces+ }++ @capture-apm-metrics {path /i/v1/metrics+ path /i/v1/prometheus/write+ path /i/v1/prometheus/write/*}@flags {@@ -104,6 +110,10 @@ services:reverse_proxy capture-logs:4320}+ handle @capture-apm-metrics {+ reverse_proxy capture-apm-metrics:4321+ }+handle @replay-capture {reverse_proxy replay-capture:3306}diff --git a/otel-collector-config.dev.yaml b/otel-collector-config.dev.yamlindex 60839f3c0459..3de7c516706c 100644--- a/otel-collector-config.dev.yaml+++ b/otel-collector-config.dev.yaml@@ -111,7 +111,7 @@ exporters:retry_on_failure:max_elapsed_time: 30sotlphttp/metrics:- endpoint: 'http://host.docker.internal:4320'+ endpoint: 'http://host.docker.internal:4321'compression: nonetls:insecure: truediff --git a/rust/Cargo.lock b/rust/Cargo.lockindex c4cb2cfb809f..438e28f95b4e 100644--- a/rust/Cargo.lock+++ b/rust/Cargo.lock@@ -2223,6 +2223,23 @@ dependencies = ["zstd",]+[[package]]+name = "capture-apm-metrics"+version = "0.1.0"+dependencies = [+ "axum 0.7.9",+ "capture",+ "capture-logs",+ "common-alloc",+ "common-metrics",+ "health",+ "limiters",+ "tokio",+ "tower-http 0.5.2",+ "tracing",+ "tracing-subscriber",+]+[[package]]name = "capture-load-gen"version = "0.1.0"diff --git a/rust/Cargo.toml b/rust/Cargo.tomlindex eb8e63859593..64fdfc162573 100644--- a/rust/Cargo.toml+++ b/rust/Cargo.toml@@ -7,6 +7,7 @@ members = ["capture","capture-load-gen","capture-logs",+ "capture-apm-metrics","cohort-core","cohort-event-shuffler","cohort-seeder",diff --git a/rust/affected-services/tests/integration.rs b/rust/affected-services/tests/integration.rsindex 128763df94a9..dfb732c82cdc 100644--- a/rust/affected-services/tests/integration.rs+++ b/rust/affected-services/tests/integration.rs@@ -250,7 +250,10 @@ fn leaf_service_only_affects_itself_and_dependents() {compute_affected(&["rust/capture/src/main.rs".into()], None, &graph, &images).unwrap();assert!(!result.rebuild_all);assert_eq!(result.directly_changed, vec!["capture"]);- assert_eq!(result.images, vec!["capture", "capture-logs"]);+ assert_eq!(+ result.images,+ vec!["capture", "capture-apm-metrics", "capture-logs"]+ );}#[test]diff --git a/rust/capture-apm-metrics/Cargo.toml b/rust/capture-apm-metrics/Cargo.tomlnew file mode 100644index 000000000000..a1e3e4caccba--- /dev/null+++ b/rust/capture-apm-metrics/Cargo.toml@@ -0,0 +1,21 @@+[package]+name = "capture-apm-metrics"+version = "0.1.0"+edition = "2021"+publish = false++[dependencies]+tokio = { workspace = true }+tracing = { workspace = true }+tracing-subscriber = { workspace = true }+health = { path = "../common/health" }+axum = { workspace = true }+common-metrics = { path = "../common/metrics" }+common-alloc = { path = "../common/alloc" }+limiters = { path = "../common/limiters" }+capture = { path = "../capture" }+capture-logs = { path = "../capture-logs" }+tower-http = { workspace = true }++[lints]+workspace = truediff --git a/rust/capture-apm-metrics/README.md b/rust/capture-apm-metrics/README.mdnew file mode 100644index 000000000000..e751c39d6270--- /dev/null+++ b/rust/capture-apm-metrics/README.md@@ -0,0 +1,13 @@+# PostHog Metrics Capture Service++Receives OTLP metrics (`/i/v1/metrics`) and Prometheus remote-write (`/i/v1/prometheus/write`) and writes them to Kafka.++This binary is the metrics half of [`capture-logs`](../capture-logs/README.md). It links the `capture-logs` library and mounts only the metrics routes, so metrics traffic can scale and deploy on its own. Configuration, authentication, response codes, and the Kafka sink are the ones documented for `capture-logs`.++## Running the service++```bash+cargo run --bin capture-apm-metrics+```++Local dev: `bin/start-rust-service capture-apm-metrics` (HTTP on `4321`, management on `3312`).diff --git a/rust/capture-apm-metrics/src/main.rs b/rust/capture-apm-metrics/src/main.rsnew file mode 100644index 000000000000..0f212971221c--- /dev/null+++ b/rust/capture-apm-metrics/src/main.rs@@ -0,0 +1,215 @@+//! OTLP and Prometheus remote-write metrics capture. This binary serves only+//! the metrics routes of `capture-logs`, so metrics traffic can scale and+//! deploy on its own. All handlers, config, and the Kafka sink come from the+//! `capture-logs` library.++use std::sync::Arc;+use std::time::Duration;++use axum::{extract::DefaultBodyLimit, http::Method, routing::get, routing::post, Router};+use capture::metrics_middleware::track_metrics;+use capture_logs::authorizer::Authorizer;+use capture_logs::config::Config;+use capture_logs::endpoints::prometheus;+use capture_logs::kafka::KafkaSink;+use capture_logs::middleware::translate_compression_query_param;+use capture_logs::service::Service;+use capture_logs::service::{export_metrics_http, options_handler};+use common_metrics::setup_metrics_routes;+use std::future::ready;+use std::net::SocketAddr;++use health::HealthRegistry;+use tokio::signal;+use tower_http::cors::{AllowHeaders, AllowOrigin, CorsLayer};+use tower_http::decompression::RequestDecompressionLayer;+use tracing::level_filters::LevelFilter;+use tracing::{error, info};+use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt, EnvFilter, Layer};++use limiters::token_dropper::TokenDropper;++common_alloc::used!();++async fn shutdown() {+ let mut term = signal::unix::signal(signal::unix::SignalKind::terminate())+ .expect("failed to register SIGTERM handler");++ let mut interrupt = signal::unix::signal(signal::unix::SignalKind::interrupt())+ .expect("failed to register SIGINT handler");++ tokio::select! {+ _ = term.recv() => {},+ _ = interrupt.recv() => {},+ };++ tracing::info!("Shutting down gracefully...");+}++fn setup_tracing() {+ let log_layer = tracing_subscriber::fmt::layer()+ .json()+ .with_span_list(false)+ .with_filter(+ EnvFilter::builder()+ .with_default_directive(LevelFilter::INFO.into())+ .from_env_lossy()+ .add_directive("pyroscope=warn".parse().unwrap()),+ );+ tracing_subscriber::registry().with(log_layer).init();+}++pub async fn index() -> &'static str {+ "metric hog hogs metrics++.|||||||||.+||||||||||||| gimme ur metrics 📈+|||||||||||' .\\+`||||||||||_,__o+"+}++#[tokio::main]+async fn main() {+ setup_tracing();+ info!("Starting up...");++ let config = Config::init_with_defaults().unwrap();++ // Start continuous profiling if enabled (keep _agent alive for the duration of the program)+ let _profiling_agent = match config.continuous_profiling.start_agent() {+ Ok(agent) => agent,+ Err(e) => {+ tracing::warn!("Failed to start continuous profiling agent: {e}");+ None+ }+ };++ let health_registry = HealthRegistry::new("liveness");++ // The shared sink owns one producer per signal. This binary only sends+ // metrics, but the sink constructor is unchanged, so the other producers+ // still connect and report liveness.+ let logs_sink_liveness = health_registry+ .register("rdkafka".to_string(), Duration::from_secs(30))+ .await;+ 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");++ let management_router = Router::new()+ .route("/", get(index))+ .route("/_readiness", get(index))+ .route(+ "/_liveness",+ get(move || ready(health_registry.get_status())),+ );+ let management_router = setup_metrics_routes(management_router);+ let management_bind = format!("{}:{}", config.management_host, config.management_port);+ info!("Healthcheck and metrics listening on {}", management_bind);+ let management_listener = tokio::net::TcpListener::bind(management_bind)+ .await+ .expect("could not bind management port");++ let token_dropper = TokenDropper::new(&config.drop_events_by_token.unwrap_or_default());+ let authorizer = Authorizer::new(Arc::new(token_dropper));+ let metrics_service =+ match Service::new(kafka_sink, authorizer, config.max_request_body_size_bytes).await {+ Ok(service) => service,+ Err(e) => {+ error!("Failed to initialize metrics service: {}", e);+ panic!("Could not start metrics capture service: {e}");+ }+ };+ let http_bind = format!("{}:{}", config.host, config.port);+ info!("Listening on {}", http_bind);+ let http_listener = tokio::net::TcpListener::bind(http_bind)+ .await+ .expect("could not bind http port");++ // Very permissive CORS policy+ let cors = CorsLayer::new()+ .allow_methods([Method::GET, Method::POST, Method::OPTIONS])+ .allow_headers(AllowHeaders::mirror_request())+ .allow_credentials(true)+ .allow_origin(AllowOrigin::mirror_request());++ let http_router = Router::new()+ .route(+ "/v1/metrics",+ post(export_metrics_http).options(options_handler),+ )+ .route(+ "/i/v1/metrics",+ post(export_metrics_http).options(options_handler),+ )+ .with_state(metrics_service.clone())+ .layer(DefaultBodyLimit::max(config.max_request_body_size_bytes))+ .layer(axum::middleware::from_fn(track_metrics))+ .layer(RequestDecompressionLayer::new())+ .layer(axum::middleware::from_fn(translate_compression_query_param));++ // Prometheus remote-write sends `Content-Encoding: snappy`, which+ // RequestDecompressionLayer rejects with 415 before the handler runs. This+ // route is deliberately kept off that layer (and the gzip query-param+ // shim); the handler snappy-decodes the body itself.+ let prometheus_router = Router::new()+ .route(+ "/i/v1/prometheus/write",+ post(prometheus::export_prometheus_remote_write_http).options(options_handler),+ )+ .route(+ "/i/v1/prometheus/write/:token",+ post(prometheus::export_prometheus_remote_write_http).options(options_handler),+ )+ .with_state(metrics_service)+ .layer(DefaultBodyLimit::max(config.max_request_body_size_bytes))+ .layer(axum::middleware::from_fn(track_metrics));++ let http_router = http_router.merge(prometheus_router).layer(cors);++ let http_server = tokio::spawn(async move {+ if let Err(e) = axum::serve(+ http_listener,+ http_router.into_make_service_with_connect_info::<SocketAddr>(),+ )+ .with_graceful_shutdown(shutdown())+ .await+ {+ error!("HTTP server failed: {}", e);+ }+ });++ let mgmt_server = tokio::spawn(async move {+ if let Err(e) = axum::serve(+ management_listener,+ management_router.into_make_service_with_connect_info::<SocketAddr>(),+ )+ .await+ {+ error!("Management server failed: {}", e);+ }+ });++ // Wait for any server to finish+ tokio::select! {+ _ = http_server => {+ error!("HTTP server stopped");+ }+ _ = mgmt_server => {+ error!("Management server stopped");+ }+ }+}