: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
chore(personhog): metric improvements (#59958)
Nick Best356523bf96b5
diff --git a/rust/personhog-common/src/grpc.rs b/rust/personhog-common/src/grpc.rsindex 585553956ba3..e99f0dbab1fc 100644--- a/rust/personhog-common/src/grpc.rs+++ b/rust/personhog-common/src/grpc.rs@@ -7,7 +7,7 @@ use std::task::{Context, Poll};use std::time::Instant;use futures::stream::unfold;-use http::{Request, Response};+use http::{HeaderValue, Request, Response};use metrics::{counter, gauge, histogram};use pin_project::{pin_project, pinned_drop};use tokio::io::{AsyncRead, AsyncWrite, ReadBuf};@@ -193,6 +193,12 @@ fn is_fatal_accept_error(e: &io::Error) -> bool {// Request metrics layer// ============================================================+/// Header name for the replica's processing time, set on responses when+/// `emit_processing_time_header` is enabled. The router reads this to+/// compute per-request transport overhead without subtracting independent+/// histogram quantiles.+pub const PROCESSING_TIME_HEADER: &str = "x-processing-time-ms";+/// Tower layer that instruments gRPC requests with timing and concurrency metrics.////// Records:@@ -203,19 +209,33 @@ fn is_fatal_accept_error(e: &io::Error) -> bool {/// Also sets the `CLIENT_NAME` task-local so downstream code can read/// the client name via `current_client_name()`.#[derive(Clone, Default)]-pub struct GrpcMetricsLayer;+pub struct GrpcMetricsLayer {+ emit_processing_time_header: bool,+}++impl GrpcMetricsLayer {+ pub fn with_processing_time_header(self) -> Self {+ Self {+ emit_processing_time_header: true,+ }+ }+}impl<S> Layer<S> for GrpcMetricsLayer {type Service = GrpcMetricsService<S>;fn layer(&self, service: S) -> Self::Service {- GrpcMetricsService { inner: service }+ GrpcMetricsService {+ inner: service,+ emit_processing_time_header: self.emit_processing_time_header,+ }}}#[derive(Clone)]pub struct GrpcMetricsService<S> {inner: S,+ emit_processing_time_header: bool,}impl<S, ReqBody, ResBody> Service<Request<ReqBody>> for GrpcMetricsService<S>@@ -249,6 +269,7 @@ wheremethod,client,start,+ emit_processing_time_header: self.emit_processing_time_header,}}}@@ -266,6 +287,7 @@ pub struct GrpcMetricsFuture<F> {method: String,client: Arc<str>,start: Instant,+ emit_processing_time_header: bool,}impl<F, ResBody, E> Future for GrpcMetricsFuture<F>@@ -277,7 +299,7 @@ wherefn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {let this = self.project();match this.inner.poll(cx) {- Poll::Ready(result) => {+ Poll::Ready(mut result) => {let duration_ms = this.start.elapsed().as_secs_f64() * 1000.0;counter!("grpc_server_requests_total","method" => this.method.clone(),@@ -287,6 +309,15 @@ where"method" => this.method.clone(),"client" => this.client.clone()).record(duration_ms);++ if *this.emit_processing_time_header {+ if let Ok(ref mut response) = result {+ if let Ok(hv) = HeaderValue::from_str(&format!("{duration_ms:.3}")) {+ response.headers_mut().insert(PROCESSING_TIME_HEADER, hv);+ }+ }+ }+Poll::Ready(result)}Poll::Pending => Poll::Pending,diff --git a/rust/personhog-replica/src/main.rs b/rust/personhog-replica/src/main.rsindex 15b8737f1b12..5600a60f9cb0 100644--- a/rust/personhog-replica/src/main.rs+++ b/rust/personhog-replica/src/main.rs@@ -316,7 +316,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {server = server.max_connection_age(age);}if let Err(e) = server- .layer(GrpcMetricsLayer)+ .layer(GrpcMetricsLayer::default().with_processing_time_header()).layer(GrpcLoadShedLayer::new(max_concurrent_requests)).add_service(PersonHogReplicaServer::new(service)diff --git a/rust/personhog-router/src/main.rs b/rust/personhog-router/src/main.rsindex a1172a2c7167..0acac01d65a2 100644--- a/rust/personhog-router/src/main.rs+++ b/rust/personhog-router/src/main.rs@@ -110,10 +110,20 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {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] = &[+ 64.0, 256.0, 1024.0, 4096.0, 16384.0, 65536.0, 262144.0, 1048576.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().install_recorder().expect("Failed to install metrics recorder");@@ -304,7 +314,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {Server::builder().http2_keepalive_interval(keepalive_interval).http2_keepalive_timeout(keepalive_timeout)- .layer(GrpcMetricsLayer)+ .layer(GrpcMetricsLayer::default()).add_service(proxy).serve_with_incoming_shutdown(incoming, grpc_handle.shutdown_signal()).await@@ -318,7 +328,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {Server::builder().http2_keepalive_interval(keepalive_interval).http2_keepalive_timeout(keepalive_timeout)- .layer(GrpcMetricsLayer)+ .layer(GrpcMetricsLayer::default()).add_service(PersonHogServiceServer::new(service).max_encoding_message_size(max_send)diff --git a/rust/personhog-router/src/proxy.rs b/rust/personhog-router/src/proxy.rsindex 1c3b31de4533..5e4e70ed6200 100644--- a/rust/personhog-router/src/proxy.rs+++ b/rust/personhog-router/src/proxy.rs@@ -9,7 +9,7 @@ use http::{HeaderMap, HeaderValue};use http_body::Frame;use http_body_util::{BodyExt, Empty, Full};use metrics::{counter, histogram};-use personhog_common::grpc::{current_client_name, ClientInFlightGuard};+use personhog_common::grpc::{current_client_name, ClientInFlightGuard, PROCESSING_TIME_HEADER};use personhog_proto::personhog::types::v1::{GetPersonRequest, UpdatePersonPropertiesRequest};use prost::Message;use rand::Rng;@@ -144,7 +144,7 @@ impl RawProxyInner {let client = current_client_name();let start = Instant::now();- let (response, backend) = match method_name {+ let (mut response, backend) = match method_name {"UpdatePersonProperties" => (self.handle_update_person_properties(req).await, "leader"),"GetPerson" => {let is_strong = req@@ -180,17 +180,35 @@ impl RawProxyInner {).record(duration_ms);+ if let Some(processing_ms) = response+ .headers()+ .get(PROCESSING_TIME_HEADER)+ .and_then(|v| v.to_str().ok())+ .and_then(|s| s.parse::<f64>().ok())+ {+ histogram!(+ "personhog_router_transport_overhead_ms",+ "method" => method.clone(),+ "backend" => backend,+ "client" => client.clone(),+ )+ .record((duration_ms - processing_ms).max(0.0));+ response.headers_mut().remove(PROCESSING_TIME_HEADER);+ }+if is_grpc_error_response(&response) {counter!("personhog_router_backend_errors_total",- "method" => method,+ "method" => method.clone(),"backend" => backend,- "client" => client,+ "client" => client.clone(),).increment(1);}- response+ let (parts, body) = response.into_parts();+ let counted = ByteCountedBody::new(body, method, backend, client);+ http::Response::from_parts(parts, BoxBody::new(counted))}async fn raw_proxy_to_replica(@@ -447,6 +465,59 @@ fn percent_encode_grpc(s: &str) -> String {out}+/// Response body wrapper that counts bytes from DATA frames and records+/// the total to a histogram on drop.+struct ByteCountedBody {+ inner: BoxBody,+ bytes_counted: usize,+ method: String,+ backend: &'static str,+ client: Arc<str>,+}++impl ByteCountedBody {+ fn new(inner: BoxBody, method: String, backend: &'static str, client: Arc<str>) -> Self {+ Self {+ inner,+ bytes_counted: 0,+ method,+ backend,+ client,+ }+ }+}++impl http_body::Body for ByteCountedBody {+ type Data = Bytes;+ type Error = tonic::Status;++ fn poll_frame(+ self: Pin<&mut Self>,+ cx: &mut Context<'_>,+ ) -> Poll<Option<Result<Frame<Self::Data>, Self::Error>>> {+ let this = self.get_mut();+ let result = Pin::new(&mut this.inner).poll_frame(cx);+ if let Poll::Ready(Some(Ok(ref frame))) = result {+ if let Some(data) = frame.data_ref() {+ this.bytes_counted += data.len();+ }+ }+ result+ }+}++impl Drop for ByteCountedBody {+ fn drop(&mut self) {+ histogram!(+ "personhog_router_response_size_bytes",+ "method" => self.method.clone(),+ "backend" => self.backend,+ "client" => self.client.clone(),+ )+ .record(self.bytes_counted as f64);+ }+}+/// HTTP body that yields one data frame followed by one trailers frame./// Used for constructing gRPC responses from typed leader calls.struct GrpcResponseBody {