: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(personhog): warm pools before serving, fix histogram fidelity (#79748)
Zach Brown71a5092755d7
diff --git a/rust/personhog-common/src/lib.rs b/rust/personhog-common/src/lib.rsindex b8b2e722a22f..f8f8e5734aa9 100644--- a/rust/personhog-common/src/lib.rs+++ b/rust/personhog-common/src/lib.rs@@ -1,6 +1,7 @@pub mod async_gzip;pub mod client;pub mod grpc;+pub mod metrics;pub mod partitioning;pub mod persons;mod pool_monitor;diff --git a/rust/personhog-common/src/metrics.rs b/rust/personhog-common/src/metrics.rsnew file mode 100644index 000000000000..61d5ea42da3f--- /dev/null+++ b/rust/personhog-common/src/metrics.rs@@ -0,0 +1,23 @@+//! Histogram bucket ladders shared by the personhog binaries.+//!+//! The exporter's default ladder steps 10 → 50 → 100 ms, which blurs the+//! write path — produce cycles, fence waits, and lock waits all live in+//! 1–50 ms — and pins interpolated quantiles to bucket edges. These+//! ladders give the spans we tune against honest resolution; binaries+//! apply them per metric so coarse, seconds-scale histograms keep the+//! cheap default.++/// Millisecond buckets for write-path spans: produce cycles, fence+/// send/commit waits, lock waits, and per-request server and transport+/// spans.+pub const WRITE_PATH_LATENCY_BUCKETS_MS: &[f64] = &[+ 1.0, 2.5, 5.0, 7.5, 10.0, 15.0, 20.0, 25.0, 30.0, 40.0, 50.0, 75.0, 100.0, 250.0, 500.0,+ 1000.0, 2000.0, 5000.0,+];++/// Millisecond buckets for partition warms: sub-second once consumer+/// pools are warm, with enough headroom above to see a cold-pool+/// regression rather than collapsing it into +Inf.+pub const WARM_LATENCY_BUCKETS_MS: &[f64] = &[+ 50.0, 100.0, 250.0, 500.0, 750.0, 1000.0, 1500.0, 2000.0, 3000.0, 5000.0, 10000.0, 30000.0,+];diff --git a/rust/personhog-leader/src/main.rs b/rust/personhog-leader/src/main.rsindex 90731193cab9..1f898dcd83da 100644--- a/rust/personhog-leader/src/main.rs+++ b/rust/personhog-leader/src/main.rs@@ -4,7 +4,7 @@ use std::time::Duration;use assignment_coordination::store::{EtcdStore, StoreConfig};use axum::{routing::get, Router};use common_kafka::kafka_producer::create_kafka_producer;-use common_metrics::setup_metrics_routes;+use common_metrics::{setup_metrics_routes_with_overrides, Matcher};use dashmap::DashMap;use envconfig::Envconfig;use k8s_awareness::{K8sAwareness, PodInfo};@@ -12,6 +12,7 @@ use kube::Client;use lifecycle::{ComponentOptions, Manager};use personhog_common::async_gzip::{AsyncGzipConfig, AsyncGzipLayer};use personhog_common::grpc::{tracked_tcp_incoming, GrpcLoadShedLayer, GrpcMetricsLayer};+use personhog_common::metrics::{WARM_LATENCY_BUCKETS_MS, WRITE_PATH_LATENCY_BUCKETS_MS};use personhog_coordination::authority::AuthorityClock;use personhog_coordination::pod::{PodConfig, PodHandle};use personhog_coordination::store::PersonhogStore;@@ -133,9 +134,9 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {let monitor_guard = manager.monitor_background();// Metrics/health HTTP server. The router is built here rather than- // inside the task because `setup_metrics_routes` is what installs the- // process-wide recorder: anything preregistered before it lands in a- // no-op recorder and never becomes a series.+ // inside the task because `setup_metrics_routes_with_overrides` is+ // what installs the process-wide recorder: anything preregistered+ // before it lands in a no-op recorder and never becomes a series.let metrics_port = config.metrics_port;let health_router = Router::new().route(@@ -146,7 +147,56 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {}),).route("/_liveness", get(move || async move { liveness.check() }));- let metrics_router = setup_metrics_routes(health_router);+ // The write path and warms are tuned in single-digit milliseconds;+ // the default ladder's 10 → 50 ms step blurs exactly the spans the+ // fencing and warm work steers by, and pins interpolated quantiles+ // to bucket edges. Overridden per metric so seconds-scale histograms+ // keep the cheap default ladder.+ let metrics_router = setup_metrics_routes_with_overrides(+ health_router,+ &[+ (+ Matcher::Full("personhog_leader_kafka_produce_duration_ms".into()),+ WRITE_PATH_LATENCY_BUCKETS_MS,+ ),+ (+ Matcher::Full("personhog_leader_fence_send_ms".into()),+ WRITE_PATH_LATENCY_BUCKETS_MS,+ ),+ (+ Matcher::Full("personhog_leader_fence_ack_wait_ms".into()),+ WRITE_PATH_LATENCY_BUCKETS_MS,+ ),+ (+ Matcher::Full("personhog_leader_fence_window_wait_ms".into()),+ WRITE_PATH_LATENCY_BUCKETS_MS,+ ),+ (+ Matcher::Full("personhog_leader_fence_commit_ms".into()),+ WRITE_PATH_LATENCY_BUCKETS_MS,+ ),+ (+ Matcher::Full("personhog_leader_fence_init_ms".into()),+ WRITE_PATH_LATENCY_BUCKETS_MS,+ ),+ (+ Matcher::Full("personhog_leader_person_lock_wait_ms".into()),+ WRITE_PATH_LATENCY_BUCKETS_MS,+ ),+ (+ Matcher::Full("grpc_server_request_duration_ms".into()),+ WRITE_PATH_LATENCY_BUCKETS_MS,+ ),+ (+ Matcher::Full("personhog_leader_warm_duration_ms".into()),+ WARM_LATENCY_BUCKETS_MS,+ ),+ (+ Matcher::Full("personhog_coordination_partition_warm_ms".into()),+ WARM_LATENCY_BUCKETS_MS,+ ),+ ],+ );preregister_metrics();// The refusals the gate can emit: rare by design, and a burst is// exactly what a deploy-window scrape would otherwise miss.@@ -475,18 +525,32 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {// cold pool would make every burst's first operations pay the client// setup the pool exists to amortize. Sized from the pod's actual// configured warm concurrency — the bound the semaphore enforces —- // so the pool and the concurrency limit cannot drift apart; the- // offsets pool also serves the dirty-index prune tick. Best-effort:- // a failure only defers the cost.+ // so the pool and the concurrency limit cannot drift apart.+ // Committed-offset queries run one per concurrent warm, so the+ // offsets pool needs the same depth; it also serves the dirty-index+ // prune tick.+ //+ // Awaited before the pod registers for partitions: a deploy burst+ // hands this pod partitions immediately, and a warm that finds the+ // pool empty builds its clients cold inside the handoff — seconds of+ // connection setup on the path the pool exists to keep off. The+ // deadline keeps a broker outage from wedging boot; past it,+ // registration proceeds and the remaining slots are built cold, so+ // this stays best-effort.{- let pools = Arc::clone(&warm_pools);let warm_slots = pod_config.warm_concurrency;- tokio::spawn(async move {- // Committed-offset queries run one per concurrent warm, so- // the offsets pool needs the same depth as the warm slots.- pools.offsets.warm_up(warm_slots).await;- pools.warming.warm_up(warm_slots).await;- });+ let warm_up = async {+ tokio::join!(+ warm_pools.offsets.warm_up(warm_slots),+ warm_pools.warming.warm_up(warm_slots),+ );+ };+ if timeout(POOL_WARM_UP_DEADLINE, warm_up).await.is_err() {+ tracing::warn!(+ deadline_secs = POOL_WARM_UP_DEADLINE.as_secs(),+ "consumer pool warm-up hit its deadline; continuing with a partially cold pool"+ );+ }}let pod = PodHandle::new(@@ -678,6 +742,11 @@ async fn run_dirty_index_prune_loop(/// tight against an unresponsive one, which must not delay serving.const K8S_DISCOVERY_TIMEOUT: Duration = Duration::from_secs(5);+/// Upper bound on the pre-registration consumer-pool warm-up. Generous+/// against MSK connection setup (~1–2s per client, run concurrently),+/// tight enough that a broker outage delays boot rather than blocking it.+const POOL_WARM_UP_DEADLINE: Duration = Duration::from_secs(10);+/// Build a K8s awareness client and discover this pod's owning controller/// and generation. The awareness handle is returned alongside so the pod/// can also classify its own departure at drain time.diff --git a/rust/personhog-leader/src/warming.rs b/rust/personhog-leader/src/warming.rsindex aadd1678de48..23b338e40e5c 100644--- a/rust/personhog-leader/src/warming.rs+++ b/rust/personhog-leader/src/warming.rs@@ -218,29 +218,35 @@ impl ConsumerPool {/// only means the first operations pay the setup they would have/// paid anyway.pub async fn warm_up(&self, n: usize) {- // Hold every connected client outside the pool until the end:- // returning them as we go would make the next checkout pop the- // client we just returned, connecting one client n times and- // leaving the other n-1 slots to be built cold on the hot path.- let mut connected = Vec::with_capacity(n);+ // Create every client before connecting any: returning them as we+ // go would make the next checkout pop the client we just returned,+ // connecting one client n times and leaving the other n-1 slots to+ // be built cold on the hot path. The connects then run+ // concurrently — a deploy burst needs the pool populated in one+ // connect's time, not n of them in sequence.+ let mut clients = Vec::with_capacity(n);for _ in 0..n {let Ok(consumer) = self.checkout() else {break;};- let timeout = Duration::from_secs(5);- let outcome = tokio::task::spawn_blocking(move || {- let ok = consumer.fetch_metadata(None, timeout).is_ok();- (consumer, ok)+ clients.push(consumer);+ }+ let connects: Vec<_> = clients+ .into_iter()+ .map(|consumer| {+ tokio::task::spawn_blocking(move || {+ let ok = consumer+ .fetch_metadata(None, Duration::from_secs(5))+ .is_ok();+ (consumer, ok)+ })})- .await;- match outcome {- Ok((consumer, true)) => connected.push(consumer),- _ => break,+ .collect();+ for connect in connects {+ if let Ok((consumer, true)) = connect.await {+ self.give_back(consumer);}}- for consumer in connected {- self.give_back(consumer);- }}}diff --git a/rust/personhog-router/src/main.rs b/rust/personhog-router/src/main.rsindex 6ebe36144577..d03a9d7fc066 100644--- a/rust/personhog-router/src/main.rs+++ b/rust/personhog-router/src/main.rs@@ -6,8 +6,9 @@ use axum::{routing::get, Router};use envconfig::Envconfig;use k8s_awareness::K8sAwareness;use lifecycle::{ComponentOptions, Manager};-use metrics_exporter_prometheus::PrometheusBuilder;+use metrics_exporter_prometheus::{Matcher, PrometheusBuilder, PrometheusHandle};use personhog_common::grpc::{tracked_tcp_incoming, GrpcMetricsLayer};+use personhog_common::metrics::WRITE_PATH_LATENCY_BUCKETS_MS;use personhog_coordination::coordinator::{Coordinator, CoordinatorConfig};use personhog_coordination::routing_table::{RoutingTable, RoutingTableConfig, StashHandler};use personhog_coordination::store::PersonhogStore;@@ -39,6 +40,10 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {if let Err(e) = config.validate_lease_timescales() {panic!("invalid lease configuration: {e}");}+ // Install the process-wide recorder before anything records: metrics+ // emitted ahead of it land in a no-op recorder and are dropped, and+ // preregistered series never materialize.+ let recorder_handle = install_metrics_recorder();preregister_metrics();// Initialize tracing@@ -188,52 +193,6 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {tokio::spawn(async move {let _guard = metrics_handle.process_scope();- const BUCKETS: &[f64] = &[- 1.0, 5.0, 10.0, 50.0, 100.0, 250.0, 500.0, 1000.0, 2000.0, 5000.0, 10000.0,- ];- const RESPONSE_SIZE_BUCKETS: &[f64] = &[- 256.0, 1024.0, 4096.0, 16384.0, 65536.0, 262144.0, 1048576.0, 4194304.0, 8388608.0,- 16777216.0, 33554432.0, 67108864.0,- ];- let recorder_handle = PrometheusBuilder::new()- .add_global_label("service", "personhog-router")- .set_buckets(BUCKETS)- .unwrap()- .set_buckets_for_metric(- metrics_exporter_prometheus::Matcher::Prefix(- "personhog_router_response_size".into(),- ),- RESPONSE_SIZE_BUCKETS,- )- .unwrap()- // Handoff phase timings are a stall detector: healthy phases- // complete in seconds, and the interesting tail is minutes.- // Sub-second buckets at the bottom because the source is- // millisecond-precise; the top still reaches far past the- // handoff deadline so a stall is never collapsed into +Inf.- .set_buckets_for_metric(- metrics_exporter_prometheus::Matcher::Full(- "personhog_coordination_handoff_phase_reached_ms".into(),- ),- &[- 50.0, 250.0, 1000.0, 2000.0, 5000.0, 10000.0, 30000.0, 60000.0, 120000.0,- 300000.0, 600000.0,- ],- )- .unwrap()- .set_buckets_for_metric(- metrics_exporter_prometheus::Matcher::Full(- "personhog_coordination_handoff_phase_duration_ms".into(),- ),- &[- 50.0, 250.0, 1000.0, 2000.0, 5000.0, 10000.0, 30000.0, 60000.0, 120000.0,- 300000.0, 600000.0,- ],- )- .unwrap()- .install_recorder()- .expect("Failed to install metrics recorder");-let health_router = Router::new().route("/_readiness",@@ -453,6 +412,83 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {Ok(())}+/// Build and install the process-wide Prometheus recorder. Runs in+/// `main` before anything records — including `preregister_metrics` —+/// because everything emitted ahead of the install lands in the default+/// no-op recorder and is silently dropped.+fn install_metrics_recorder() -> PrometheusHandle {+ const BUCKETS: &[f64] = &[+ 1.0, 5.0, 10.0, 50.0, 100.0, 250.0, 500.0, 1000.0, 2000.0, 5000.0, 10000.0,+ ];+ const RESPONSE_SIZE_BUCKETS: &[f64] = &[+ 256.0, 1024.0, 4096.0, 16384.0, 65536.0, 262144.0, 1048576.0, 4194304.0, 8388608.0,+ 16777216.0, 33554432.0, 67108864.0,+ ];+ // Handoff phase timings are a stall detector: healthy phases+ // complete in seconds, and the interesting tail is minutes.+ // Sub-second buckets at the bottom because the source is+ // millisecond-precise; the top still reaches far past the+ // handoff deadline so a stall is never collapsed into +Inf.+ const HANDOFF_PHASE_BUCKETS: &[f64] = &[+ 50.0, 250.0, 1000.0, 2000.0, 5000.0, 10000.0, 30000.0, 60000.0, 120000.0, 300000.0,+ 600000.0,+ ];+ PrometheusBuilder::new()+ .add_global_label("service", "personhog-router")+ .set_buckets(BUCKETS)+ .unwrap()+ .set_buckets_for_metric(+ Matcher::Prefix("personhog_router_response_size".into()),+ RESPONSE_SIZE_BUCKETS,+ )+ .unwrap()+ .set_buckets_for_metric(+ Matcher::Full("personhog_coordination_handoff_phase_reached_ms".into()),+ HANDOFF_PHASE_BUCKETS,+ )+ .unwrap()+ .set_buckets_for_metric(+ Matcher::Full("personhog_coordination_handoff_phase_duration_ms".into()),+ HANDOFF_PHASE_BUCKETS,+ )+ .unwrap()+ // Per-request forwarding spans live in single-digit milliseconds;+ // the default ladder's 10 → 50 ms step blurs them and pins+ // interpolated quantiles to bucket edges.+ .set_buckets_for_metric(+ Matcher::Prefix("personhog_router_channel_".into()),+ WRITE_PATH_LATENCY_BUCKETS_MS,+ )+ .unwrap()+ .set_buckets_for_metric(+ Matcher::Full("personhog_router_backend_duration_ms".into()),+ WRITE_PATH_LATENCY_BUCKETS_MS,+ )+ .unwrap()+ .set_buckets_for_metric(+ Matcher::Full("personhog_router_network_overhead_ms".into()),+ WRITE_PATH_LATENCY_BUCKETS_MS,+ )+ .unwrap()+ .set_buckets_for_metric(+ Matcher::Full("personhog_router_transport_overhead_ms".into()),+ WRITE_PATH_LATENCY_BUCKETS_MS,+ )+ .unwrap()+ .set_buckets_for_metric(+ Matcher::Full("personhog_router_body_collect_ms".into()),+ WRITE_PATH_LATENCY_BUCKETS_MS,+ )+ .unwrap()+ .set_buckets_for_metric(+ Matcher::Full("grpc_server_request_duration_ms".into()),+ WRITE_PATH_LATENCY_BUCKETS_MS,+ )+ .unwrap()+ .install_recorder()+ .expect("Failed to install metrics recorder")+}+/// Touch the deploy-burst counters so their series exist with zero/// samples before any burst. metrics registration is lazy: a counter/// that first fires between two scrapes materializes with the burstdiff --git a/rust/personhog-test-harness/src/traffic_metrics.rs b/rust/personhog-test-harness/src/traffic_metrics.rsindex c4c11acbddf0..2d47570a9aa6 100644--- a/rust/personhog-test-harness/src/traffic_metrics.rs+++ b/rust/personhog-test-harness/src/traffic_metrics.rs@@ -16,6 +16,7 @@ use axum::routing::get;use axum::Router;use metrics::{counter, histogram};use personhog_common::grpc::{code_as_str, NON_STATUS};+use personhog_common::metrics::WRITE_PATH_LATENCY_BUCKETS_MS;use crate::report::ConsistencyViolation;@@ -106,7 +107,22 @@ pub fn record_read_failed(lane: &'static str, reason: &'static str) {/// Serve liveness + Prometheus metrics; runs for the process lifetime.pub fn spawn_server(port: u16) -> Result<()> {let router = Router::new().route("/_liveness", get(|| async { "ok" }));- let router = common_metrics::setup_metrics_routes(router);+ // Client-observed request latencies live in single-digit+ // milliseconds; the default ladder's 10 → 50 ms step blurs them and+ // pins interpolated quantiles to bucket edges.+ let router = common_metrics::setup_metrics_routes_with_overrides(+ router,+ &[+ (+ common_metrics::Matcher::Full("personhog_traffic_write_duration_ms".into()),+ WRITE_PATH_LATENCY_BUCKETS_MS,+ ),+ (+ common_metrics::Matcher::Full("personhog_traffic_read_duration_ms".into()),+ WRITE_PATH_LATENCY_BUCKETS_MS,+ ),+ ],+ );let bind = format!("0.0.0.0:{port}");tokio::spawn(async move {if let Err(e) = common_metrics::serve(router, &bind).await {