Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

fix(capture-apm-metrics): serve probes from a dedicated runtime thread (#98240)

Frank Hamand960c2d80d85e
diff --git a/rust/capture-apm-metrics/src/lib.rs b/rust/capture-apm-metrics/src/lib.rs
index c344319596f9..0aabd3547633 100644
--- a/rust/capture-apm-metrics/src/lib.rs
+++ b/rust/capture-apm-metrics/src/lib.rs
@@ -1,4 +1,5 @@
pub mod config;
+pub mod management;
pub mod prometheus;
pub mod series_label_gate;
pub mod service;
diff --git a/rust/capture-apm-metrics/src/main.rs b/rust/capture-apm-metrics/src/main.rs
index 887cd7aab7a2..e0a978d0ea3f 100644
--- a/rust/capture-apm-metrics/src/main.rs
+++ b/rust/capture-apm-metrics/src/main.rs
@@ -9,6 +9,7 @@ use std::time::Duration;
use axum::{extract::DefaultBodyLimit, http::Method, routing::get, routing::post, Router};
use capture::metrics_middleware::track_metrics;
use capture_apm_metrics::config::Config;
+use capture_apm_metrics::management;
use capture_apm_metrics::prometheus;
use capture_apm_metrics::series_label_gate::{spawn_redis_writer, CacheLimits, SeriesLabelGate};
use capture_apm_metrics::service::{export_metrics_http, MetricsService};
@@ -130,8 +131,7 @@ async fn start_series_label_gate(config: &Config) -> Arc<SeriesLabelGate> {
gate
}
-#[tokio::main]
-async fn main() {
+fn main() {
// Without this, the first TLS handshake to Valkey panics the task that made it.
rustls::crypto::aws_lc_rs::default_provider()
.install_default()
@@ -142,6 +142,46 @@ async fn main() {
let config = Config::init_with_defaults().unwrap();
+ let management_runtime = management::build_runtime();
+
+ // The registry spawns its status task on the current runtime. The task
+ // must live on the management runtime, so the probe result stays current
+ // when the data plane is busy.
+ let health_registry = {
+ let _guard = management_runtime.enter();
+ HealthRegistry::new("liveness")
+ };
+
+ // Bind here so a port conflict still stops the process at startup.
+ let management_bind = format!(
+ "{}:{}",
+ config.base.management_host, config.base.management_port
+ );
+ let management_listener = management_runtime
+ .block_on(tokio::net::TcpListener::bind(&management_bind))
+ .expect("could not bind management port");
+
+ let data_runtime = tokio::runtime::Builder::new_multi_thread()
+ .enable_all()
+ .build()
+ .expect("failed to build data-plane runtime");
+
+ data_runtime.block_on(run(
+ config,
+ health_registry,
+ management_runtime.handle().clone(),
+ management_listener,
+ management_bind,
+ ));
+}
+
+async fn run(
+ config: Config,
+ health_registry: HealthRegistry,
+ management_runtime: tokio::runtime::Handle,
+ management_listener: tokio::net::TcpListener,
+ management_bind: String,
+) {
// Start continuous profiling if enabled (keep _agent alive for the duration of the program)
let _profiling_agent = match config.base.continuous_profiling.start_agent() {
Ok(agent) => agent,
@@ -151,8 +191,6 @@ async fn main() {
}
};
- 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.
@@ -183,14 +221,6 @@ async fn main() {
get(move || ready(health_registry.get_status())),
);
let management_router = setup_metrics_routes(management_router);
- let management_bind = format!(
- "{}:{}",
- config.base.management_host, config.base.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 series_label_gate = start_series_label_gate(&config).await;
let token_dropper =
@@ -265,16 +295,13 @@ async fn main() {
}
});
- 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);
- }
- });
+ info!("Healthcheck and metrics listening on {}", management_bind);
+
+ // Serve the probes only once the data plane listens. `/_readiness` answers
+ // 200 unconditionally, so an earlier start would put the pod in service
+ // while its ingestion port still refuses connections.
+ let mgmt_server =
+ management::serve(&management_runtime, management_listener, management_router);
// Wait for any server to finish
tokio::select! {
diff --git a/rust/capture-apm-metrics/src/management.rs b/rust/capture-apm-metrics/src/management.rs
new file mode 100644
index 000000000000..6bc92522f648
--- /dev/null
+++ b/rust/capture-apm-metrics/src/management.rs
@@ -0,0 +1,106 @@
+//! The management plane: probes and `/metrics` on a runtime the data plane
+//! never shares.
+
+use std::net::SocketAddr;
+
+use axum::Router;
+use tokio::net::TcpListener;
+use tokio::runtime::{Builder, Handle, Runtime};
+use tokio::task::JoinHandle;
+use tracing::error;
+
+/// Build the runtime that serves the probes and `/metrics`. It owns one OS
+/// thread that the data plane never uses. When request decoding saturates the
+/// data-plane workers, the kernel still schedules this thread, so the probes
+/// answer inside the kubelet timeout.
+pub fn build_runtime() -> Runtime {
+ Builder::new_multi_thread()
+ .worker_threads(1)
+ .thread_name("management")
+ .enable_all()
+ .build()
+ .expect("failed to build management runtime")
+}
+
+/// Serve `router` on `listener` from the management runtime. The connection
+/// tasks never wait behind the data-plane handlers. The handle resolves when
+/// the server stops.
+pub fn serve(runtime: &Handle, listener: TcpListener, router: Router) -> JoinHandle<()> {
+ runtime.spawn(async move {
+ if let Err(e) = axum::serve(
+ listener,
+ router.into_make_service_with_connect_info::<SocketAddr>(),
+ )
+ .await
+ {
+ error!("Management server failed: {}", e);
+ }
+ })
+}
+
+#[cfg(test)]
+mod tests {
+ use std::io::{Read, Write};
+ use std::net::TcpStream;
+ use std::sync::mpsc;
+ use std::time::Duration;
+
+ use axum::routing::get;
+
+ use super::*;
+
+ fn get_readiness(addr: SocketAddr) -> String {
+ let mut stream = TcpStream::connect(addr).unwrap();
+ stream
+ .set_read_timeout(Some(Duration::from_secs(5)))
+ .unwrap();
+ stream
+ .write_all(b"GET /_readiness HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n")
+ .unwrap();
+ let mut response = String::new();
+ stream.read_to_string(&mut response).unwrap();
+ response
+ }
+
+ /// A probe must answer while the only data-plane worker is held by
+ /// synchronous work, as a large protobuf decode holds it in production.
+ #[test]
+ fn probe_answers_while_data_plane_worker_is_blocked() {
+ let management = build_runtime();
+ let listener = management
+ .block_on(TcpListener::bind("127.0.0.1:0"))
+ .unwrap();
+ let addr = listener.local_addr().unwrap();
+ let router = Router::new().route("/_readiness", get(|| async { "ok" }));
+ let _server = serve(management.handle(), listener, router);
+
+ let data_plane = Builder::new_multi_thread()
+ .worker_threads(1)
+ .enable_all()
+ .build()
+ .unwrap();
+ let (blocked_tx, blocked_rx) = mpsc::channel::<()>();
+ let (release_tx, release_rx) = mpsc::channel::<()>();
+ data_plane.spawn(async move {
+ blocked_tx.send(()).unwrap();
+ release_rx.recv().unwrap();
+ });
+ blocked_rx.recv().unwrap();
+
+ // Confirm the worker is held: a second data-plane task does not run.
+ let (ran_tx, ran_rx) = mpsc::channel::<()>();
+ data_plane.spawn(async move {
+ ran_tx.send(()).unwrap();
+ });
+ assert!(
+ ran_rx.recv_timeout(Duration::from_millis(200)).is_err(),
+ "data-plane worker was not blocked"
+ );
+
+ let response = get_readiness(addr);
+ assert!(response.starts_with("HTTP/1.1 200"), "{response}");
+
+ release_tx.send(()).unwrap();
+ ran_rx.recv_timeout(Duration::from_secs(5)).unwrap();
+ }
+}