: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(flags): close instrumentation gaps (#57692)
Matheus Batista7d1aa7595f8f
diff --git a/rust/common/metrics/src/lib.rs b/rust/common/metrics/src/lib.rsindex d147a65121d6..65fe7b496c7a 100644--- a/rust/common/metrics/src/lib.rs+++ b/rust/common/metrics/src/lib.rs@@ -4,6 +4,7 @@ use axum::{body::Body, extract::MatchedPath, http::Request, middleware::Next, response::IntoResponse,routing::get, Router,};+pub use metrics_exporter_prometheus::Matcher;use metrics_exporter_prometheus::PrometheusBuilder;use std::sync::OnceLock;@@ -36,7 +37,7 @@ pub async fn serve(router: Router, bind: &str) -> Result<(), std::io::Error> {/// Use [`setup_metrics_routes_for_product`] when you want a `product` global/// label for cost attribution.pub fn setup_metrics_routes(router: Router) -> Router {- install_metrics_routes(router, None)+ install_metrics_routes(router, None, &[])}/// Like [`setup_metrics_routes`], but emits a static `product="<value>"` global@@ -47,13 +48,36 @@ pub fn setup_metrics_routes(router: Router) -> Router {/// the Python `posthog.clickhouse.query_tagging.Product` enum values — e.g./// `feature_flags`, `experiments`, `product_analytics`.pub fn setup_metrics_routes_for_product(router: Router, product: impl Into<String>) -> Router {- install_metrics_routes(router, Some(product.into()))+ install_metrics_routes(router, Some(product.into()), &[])}-fn install_metrics_routes(router: Router, product: Option<String>) -> Router {- let recorder_handle = build_prometheus_builder(product)- .install_recorder()- .unwrap();+/// Like [`setup_metrics_routes_for_product`], but applies per-metric histogram+/// bucket overrides on top of the default bucket configuration. Each entry in+/// `overrides` is a `(Matcher, &[f64])` pair: the matcher (Full / Prefix /+/// Suffix) selects metric names and the slice provides ascending bucket+/// boundaries (in the metric's native unit). Bucket values must be non-empty;+/// invalid configuration panics at startup, matching the existing+/// `set_buckets(...).unwrap()` style here.+pub fn setup_metrics_routes_for_product_with_overrides(+ router: Router,+ product: impl Into<String>,+ overrides: &[(Matcher, &[f64])],+) -> Router {+ install_metrics_routes(router, Some(product.into()), overrides)+}++fn install_metrics_routes(+ router: Router,+ product: Option<String>,+ overrides: &[(Matcher, &[f64])],+) -> Router {+ let mut builder = build_prometheus_builder(product);+ for (matcher, buckets) in overrides {+ builder = builder+ .set_buckets_for_metric(matcher.clone(), buckets)+ .unwrap();+ }+ let recorder_handle = builder.install_recorder().unwrap();router.route(@@ -231,9 +255,54 @@ impl<'a> TimingGuardLabels<'a> {}}+/// Like [`TimingGuard`], but records elapsed time as `as_secs_f64() * 1000.0`+/// (sub-millisecond precision) instead of truncating to integer milliseconds.+/// Pair with histogram bucket overrides containing sub-ms boundaries (e.g.+/// 0.05, 0.1, 0.5, ...) — without matching overrides, sub-ms values still+/// round to whatever buckets the recorder is configured with.+pub struct TimingGuardHighPrecision<'a> {+ name: &'static str,+ labels: TimingGuardLabels<'a>,+ start: Instant,+}++/// Constructs a [`TimingGuardHighPrecision`]. Use for fast operations (sub-ms+/// pool acquires, governor rate-limit checks) where integer-millisecond+/// resolution would collapse the distribution into the lowest bucket.+pub fn timing_guard_high_precision<'a>(+ name: &'static str,+ labels: &'a [(String, String)],+) -> TimingGuardHighPrecision<'a> {+ TimingGuardHighPrecision {+ name,+ labels: TimingGuardLabels::new(labels),+ start: Instant::now(),+ }+}++impl TimingGuardHighPrecision<'_> {+ pub fn label(mut self, key: &str, value: &str) -> Self {+ self.labels.push_label(key, value);+ self+ }++ pub fn fin(self) {}+}++impl Drop for TimingGuardHighPrecision<'_> {+ fn drop(&mut self) {+ let labels = self.labels.as_slice();+ let filtered_labels = apply_label_filter(labels);+ metrics::histogram!(self.name, &filtered_labels)+ .record(self.start.elapsed().as_secs_f64() * 1000.0);+ }+}+#[cfg(test)]mod tests {- use super::{build_prometheus_builder, normalize_unmatched_path};+ use super::{+ build_prometheus_builder, normalize_unmatched_path, timing_guard_high_precision, Matcher,+ };#[test]fn test_product_global_label_emission() {@@ -290,4 +359,50 @@ mod tests {assert_eq!(normalize_unmatched_path(input), expected, "input: {input}");}}++ #[test]+ fn test_set_buckets_for_metric_full_match_overrides_default() {+ // Apply a per-metric override and confirm a custom bucket boundary+ // (well outside the default ladder) is rendered for that metric.+ let builder = build_prometheus_builder(None)+ .set_buckets_for_metric(Matcher::Full("custom_metric_ms".into()), &[30000.0])+ .unwrap();+ let recorder = builder.build_recorder();+ let handle = recorder.handle();++ metrics::with_local_recorder(&recorder, || {+ metrics::histogram!("custom_metric_ms").record(15.0);+ });++ let rendered = handle.render();+ assert!(+ rendered.contains("custom_metric_ms_bucket{le=\"30000\"}"),+ "expected override bucket le=30000 in rendered output:\n{rendered}"+ );+ }++ #[test]+ fn test_timing_guard_high_precision_records_sub_ms_value() {+ // With a sub-ms bucket override and an immediate guard drop, the+ // recorded value rounds into the smallest sub-ms bucket. The default+ // (integer-ms) guard would record 0.0 and could not distinguish this.+ let builder = build_prometheus_builder(None)+ .set_buckets_for_metric(Matcher::Full("hp_metric_ms".into()), &[0.05, 0.5, 1.0])+ .unwrap();+ let recorder = builder.build_recorder();+ let handle = recorder.handle();++ metrics::with_local_recorder(&recorder, || {+ let _g = timing_guard_high_precision("hp_metric_ms", &[]);+ // Drop immediately — elapsed will be a tiny fraction of a ms.+ });++ let rendered = handle.render();+ // The value should land in the 0.05 bucket (or the +Inf bucket if the+ // host is heavily loaded). Just verify the override was applied.+ assert!(+ rendered.contains("hp_metric_ms_bucket{le=\"0.05\"}"),+ "expected sub-ms override bucket le=0.05 in rendered output:\n{rendered}"+ );+ }}diff --git a/rust/feature-flags/src/api/endpoint.rs b/rust/feature-flags/src/api/endpoint.rsindex b799dadc10ef..c567954c0c1a 100644--- a/rust/feature-flags/src/api/endpoint.rs+++ b/rust/feature-flags/src/api/endpoint.rs@@ -10,7 +10,7 @@ use crate::{decoding, process_request, run_with_canonical_log, with_canonical_log,FlagsCanonicalLogLine, RequestContext,},- metrics::consts::FLAG_QUEUE_TIME_MS,+ metrics::consts::{FLAG_RATE_LIMIT_CHECK_TIME_MS, FLAG_TOKEN_EXTRACT_TIME_MS},router,utils::user_agent::UserAgentInfo,};@@ -258,6 +258,13 @@ pub async fn flags(// Convert IP to string once and reuse throughout the requestlet ip_string = ip.to_string();+ // Anchor for `flags_pre_handler_time_ms` — placed before UA parse so+ // that synchronous pre-handler work (UA parse → token rate-limit) is+ // included end-to-end, matching the metric's documented scope. The+ // actual emission happens inside the canonical-log scope so the metric+ // carries a `team_id` label once it's resolved.+ let pre_handler_start = std::time::Instant::now();+// Parse User-Agent and extract SDK info for logginglet user_agent = headers.get("user-agent").and_then(|v| v.to_str().ok());let ua_info = UserAgentInfo::parse(user_agent);@@ -344,8 +351,18 @@ pub async fn flags(let mut rate_limit_warned = false;- // Check IP-based rate limit first- match state.ip_rate_limiter.allow_request(&ip_string) {+ // Check IP-based rate limit first.+ // Time the governor `allow_request` call (sharded DashMap + sync+ // mutex) — Mutex contention on a hot token is a known source of+ // pre-handler latency spikes. Guard records on drop, before the+ // match arm runs.+ let ip_rl_result = {+ let _t =+ common_metrics::timing_guard_high_precision(FLAG_RATE_LIMIT_CHECK_TIME_MS, &[])+ .label("kind", "ip");+ state.ip_rate_limiter.allow_request(&ip_string)+ };+ match ip_rl_result {RateLimitResult::Blocked => {return Err(rate_limit_error(FlagError::ClientFacing(ClientFacingError::IpRateLimited,@@ -356,10 +373,21 @@ pub async fn flags(}// Check token-based rate limit- // Extract token from body, use IP as fallback if extraction fails- let rate_limit_key =- decoding::extract_token(&context.body).unwrap_or_else(|| ip_string.clone());- match state.flags_rate_limiter.allow_request(&rate_limit_key) {+ // Extract token from body, use IP as fallback if extraction fails.+ // Time the JSON DOM scan separately — pathological large bodies+ // are the suspected outlier driver here.+ let rate_limit_key = {+ let _t = common_metrics::timing_guard_high_precision(FLAG_TOKEN_EXTRACT_TIME_MS, &[]);+ decoding::extract_token(&context.body)+ }+ .unwrap_or_else(|| ip_string.clone());+ let token_rl_result = {+ let _t =+ common_metrics::timing_guard_high_precision(FLAG_RATE_LIMIT_CHECK_TIME_MS, &[])+ .label("kind", "token");+ state.flags_rate_limiter.allow_request(&rate_limit_key)+ };+ match token_rl_result {RateLimitResult::Blocked => {return Err(rate_limit_error(FlagError::ClientFacing(ClientFacingError::TokenRateLimited,@@ -373,6 +401,13 @@ pub async fn flags(with_canonical_log(|l| l.rate_limit_warned = true);}+ // Stamp pre-handler duration into the canonical log just before we+ // hand off to async processing. `Instant::now()` is monotonic, so+ // this is robust to wall-clock jumps. Emission of the histogram is+ // deferred to `emit_timing_metrics` once `team_id` is resolved.+ let pre_handler_duration_ms = pre_handler_start.elapsed().as_millis() as u64;+ with_canonical_log(|l| l.pre_handler_duration_ms = Some(pre_handler_duration_ms));+process_request(context).await}).instrument(_span)@@ -380,11 +415,9 @@ pub async fn flags(// Emit DB operations metrics before the canonical loglog.emit_db_operations_metrics();-- // Emit queue time histogram for proxy-to-app latency dashboards- if let Some(delta) = log.queue_time_ms {- common_metrics::histogram(FLAG_QUEUE_TIME_MS, &[], delta as f64);- }+ // Emit queue/pre-handler/concurrency-wait histograms with team_id labels.+ // Must run after `process_request` returns so `log.team_id` is populated.+ log.emit_timing_metrics();match result {Ok(response) => {diff --git a/rust/feature-flags/src/database/connection.rs b/rust/feature-flags/src/database/connection.rsindex eb2875041daf..44830d0b61b4 100644--- a/rust/feature-flags/src/database/connection.rs+++ b/rust/feature-flags/src/database/connection.rs@@ -104,9 +104,14 @@ pub async fn get_connection_with_metrics(gauge(FLAG_POOL_UTILIZATION_GAUGE, &labels[..1], utilization);}- // Time connection acquisition (guard records on drop)+ // Time connection acquisition (guard records on drop). Use the+ // sub-ms-precision variant: warm pool acquires complete in tens of+ // microseconds; the integer-ms variant rounds them all to the 1ms+ // bucket and hides tail behavior. Bucket overrides for this metric+ // (`flags_db_connection_time`) start at 0.05ms — see metrics::buckets.let result = {- let _conn_timer = common_metrics::timing_guard(FLAG_DB_CONNECTION_TIME, &labels);+ let _conn_timer =+ common_metrics::timing_guard_high_precision(FLAG_DB_CONNECTION_TIME, &labels);client.get_connection().await};diff --git a/rust/feature-flags/src/handler/canonical_log.rs b/rust/feature-flags/src/handler/canonical_log.rsindex 4ee7c5f993a7..fd3ce08849cd 100644--- a/rust/feature-flags/src/handler/canonical_log.rs+++ b/rust/feature-flags/src/handler/canonical_log.rs@@ -1,6 +1,9 @@use crate::api::errors::FlagError;use crate::flags::flag_matching::EvaluationType;-use crate::metrics::consts::FLAG_DB_OPERATIONS_PER_REQUEST;+use crate::metrics::consts::{+ FLAG_CONCURRENCY_LIMIT_WAIT_TIME_MS, FLAG_DB_OPERATIONS_PER_REQUEST, FLAG_PRE_HANDLER_TIME_MS,+ FLAG_QUEUE_TIME_MS,+};use std::cell::RefCell;use std::future::Future;use std::time::Instant;@@ -255,6 +258,17 @@ pub struct FlagsCanonicalLogLine {/// None when the header is missing or the computed delta is negative.pub queue_time_ms: Option<i64>,+ /// Synchronous pre-handler work in milliseconds: covers UA parse, IP+ /// rate-limit, token extract, and token rate-limit. Subdivides+ /// `queue_time_ms` so we can attribute spikes to the right tier. None+ /// when the request was rejected before reaching the pre-handler stamp.+ pub pre_handler_duration_ms: Option<u64>,++ /// Time spent waiting for a permit on the tower+ /// `ConcurrencyLimitLayer` (Phase F instrumentation). None until that+ /// phase ships; while None, `emit_timing_metrics` skips emission.+ pub concurrency_limit_wait_ms: Option<u64>,+/// Duration of the Redis HINCRBY billing increment call in milliseconds./// Only populated from endpoints that run inside a canonical log scope/// (currently `/flags` and `/decide`). `None` when billing was skipped@@ -309,6 +323,8 @@ impl Default for FlagsCanonicalLogLine {rate_limited: false,rate_limit_warned: false,queue_time_ms: None,+ pre_handler_duration_ms: None,+ concurrency_limit_wait_ms: None,billing_duration_ms: None,team_cache_source: None,http_status: 200,@@ -375,6 +391,8 @@ impl FlagsCanonicalLogLine {rate_limited = self.rate_limited,rate_limit_warned = self.rate_limit_warned,queue_time_ms = self.queue_time_ms,+ pre_handler_duration_ms = self.pre_handler_duration_ms,+ concurrency_limit_wait_ms = self.concurrency_limit_wait_ms,billing_duration_ms = self.billing_duration_ms,team_cache_source = self.team_cache_source,error_code = self.error_code,@@ -443,6 +461,45 @@ impl FlagsCanonicalLogLine {}}+ /// Emit queue/pre-handler/concurrency-wait histograms with `team_id` labels.+ ///+ /// Owns the `flags_queue_time_ms` emission (replaces a previously-unlabeled+ /// emission in `endpoint::flags`). Sibling metrics share the same label+ /// shape so a dashboard can subtract them safely:+ ///+ /// queue_time = pre_handler + concurrency_wait + (envoy + axum + non-tower)+ ///+ /// `concurrency_limit_wait_ms` intentionally omits `team_id` — permit-wait+ /// is a property of pod-level load, not of any one team, and labeling+ /// would mislead readers of the dashboard.+ ///+ /// Call once per request, after `team_id` has been resolved (i.e. after+ /// `process_request` returns) and before `emit()`.+ pub fn emit_timing_metrics(&self) {+ let team_id_label = self+ .team_id+ .map(|id| id.to_string())+ .unwrap_or_else(|| "unknown".to_string());+ let team_id_labels = [("team_id".to_string(), team_id_label)];++ if let Some(delta) = self.queue_time_ms {+ // Filter out negative deltas defensively. The endpoint already+ // filters them, but the field is i64 to preserve the original+ // calculation; negative values would break the histogram.+ if delta >= 0 {+ common_metrics::histogram(FLAG_QUEUE_TIME_MS, &team_id_labels, delta as f64);+ }+ }++ if let Some(duration) = self.pre_handler_duration_ms {+ common_metrics::histogram(FLAG_PRE_HANDLER_TIME_MS, &team_id_labels, duration as f64);+ }++ if let Some(wait) = self.concurrency_limit_wait_ms {+ common_metrics::histogram(FLAG_CONCURRENCY_LIMIT_WAIT_TIME_MS, &[], wait as f64);+ }+ }+/// Merge evaluation counters accumulated on a rayon thread back into this log.////// Delegates to [`EvalCounters::merge`], which uses an exhaustive destructuring@@ -516,6 +573,8 @@ mod tests {assert_eq!(log.http_status, 200);assert!(log.error_code.is_none());assert!(log.queue_time_ms.is_none());+ assert!(log.pre_handler_duration_ms.is_none());+ assert!(log.concurrency_limit_wait_ms.is_none());}#[test]@@ -562,6 +621,161 @@ mod tests {log.emit();}+ mod emit_timing_metrics_tests {+ use super::*;+ use metrics_util::debugging::{DebugValue, DebuggingRecorder};+ use rstest::rstest;++ struct MetricSample {+ name: String,+ labels: Vec<(String, String)>,+ #[allow(dead_code)]+ value: DebugValue,+ }++ fn snapshot_metrics(recorder: &DebuggingRecorder) -> Vec<MetricSample> {+ recorder+ .snapshotter()+ .snapshot()+ .into_vec()+ .into_iter()+ .map(|(ckey, _, _, value)| {+ let key = ckey.key();+ let mut labels: Vec<(String, String)> = key+ .labels()+ .map(|l| (l.key().to_string(), l.value().to_string()))+ .collect();+ labels.sort();+ MetricSample {+ name: key.name().to_string(),+ labels,+ value,+ }+ })+ .collect()+ }++ fn set_queue_time(log: &mut FlagsCanonicalLogLine) {+ log.queue_time_ms = Some(150);+ }++ fn set_pre_handler(log: &mut FlagsCanonicalLogLine) {+ log.pre_handler_duration_ms = Some(3);+ }++ #[rstest]+ #[case::queue_time(set_queue_time, "flags_queue_time_ms", 42)]+ #[case::pre_handler(set_pre_handler, "flags_pre_handler_time_ms", 7)]+ fn test_emits_timing_metric_with_team_id_label(+ #[case] set_field: fn(&mut FlagsCanonicalLogLine),+ #[case] metric_name: &str,+ #[case] team_id: i32,+ ) {+ let recorder = DebuggingRecorder::new();+ metrics::with_local_recorder(&recorder, || {+ let mut log = FlagsCanonicalLogLine::new(Uuid::new_v4(), "10.0.0.1".to_string());+ log.team_id = Some(team_id);+ set_field(&mut log);+ log.emit_timing_metrics();+ });++ let metrics = snapshot_metrics(&recorder);+ let sample = metrics+ .iter()+ .find(|s| s.name == metric_name)+ .unwrap_or_else(|| panic!("{metric_name} not emitted"));+ let expected = team_id.to_string();+ assert!(+ sample+ .labels+ .iter()+ .any(|(k, v)| k == "team_id" && v == &expected),+ "expected team_id={expected} label on {metric_name}, got {:?}",+ sample.labels+ );+ }++ #[test]+ fn test_concurrency_wait_emitted_without_team_id_label() {+ let recorder = DebuggingRecorder::new();+ metrics::with_local_recorder(&recorder, || {+ let mut log = FlagsCanonicalLogLine::new(Uuid::new_v4(), "10.0.0.1".to_string());+ log.team_id = Some(99);+ log.concurrency_limit_wait_ms = Some(12);+ log.emit_timing_metrics();+ });++ let metrics = snapshot_metrics(&recorder);+ let cw = metrics+ .iter()+ .find(|s| s.name == "flags_concurrency_limit_wait_ms")+ .expect("flags_concurrency_limit_wait_ms not emitted");+ // Must NOT carry team_id — permit-wait is pod-level, not per-team.+ assert!(+ !cw.labels.iter().any(|(k, _)| k == "team_id"),+ "concurrency_limit_wait_ms should not carry team_id, got {:?}",+ cw.labels+ );+ }++ #[test]+ fn test_unknown_team_id_when_team_unresolved() {+ let recorder = DebuggingRecorder::new();+ metrics::with_local_recorder(&recorder, || {+ let mut log = FlagsCanonicalLogLine::new(Uuid::new_v4(), "10.0.0.1".to_string());+ // team_id stays None — e.g. token extraction failed before auth.+ log.queue_time_ms = Some(20);+ log.emit_timing_metrics();+ });++ let metrics = snapshot_metrics(&recorder);+ let queue = metrics+ .iter()+ .find(|s| s.name == "flags_queue_time_ms")+ .expect("flags_queue_time_ms not emitted");+ assert!(queue+ .labels+ .iter()+ .any(|(k, v)| k == "team_id" && v == "unknown"));+ }++ #[test]+ fn test_no_emission_when_field_is_none() {+ let recorder = DebuggingRecorder::new();+ metrics::with_local_recorder(&recorder, || {+ let log = FlagsCanonicalLogLine::new(Uuid::new_v4(), "10.0.0.1".to_string());+ // All three timing fields default to None.+ log.emit_timing_metrics();+ });++ let metrics = snapshot_metrics(&recorder);+ for name in [+ "flags_queue_time_ms",+ "flags_pre_handler_time_ms",+ "flags_concurrency_limit_wait_ms",+ ] {+ assert!(+ !metrics.iter().any(|s| s.name == name),+ "did not expect {name} to be emitted with no data"+ );+ }+ }++ #[test]+ fn test_negative_queue_time_is_skipped() {+ // Defensive: the endpoint already filters negative deltas, but+ // belt-and-suspenders since `queue_time_ms` is i64.+ let recorder = DebuggingRecorder::new();+ metrics::with_local_recorder(&recorder, || {+ let mut log = FlagsCanonicalLogLine::new(Uuid::new_v4(), "10.0.0.1".to_string());+ log.queue_time_ms = Some(-5);+ log.emit_timing_metrics();+ });+ let metrics = snapshot_metrics(&recorder);+ assert!(!metrics.iter().any(|s| s.name == "flags_queue_time_ms"));+ }+ }+#[test]fn test_with_canonical_log_no_ops_outside_scope() {// Should not panic when called outside a scopediff --git a/rust/feature-flags/src/metrics/buckets.rs b/rust/feature-flags/src/metrics/buckets.rsnew file mode 100644index 000000000000..a3670c77e262--- /dev/null+++ b/rust/feature-flags/src/metrics/buckets.rs@@ -0,0 +1,73 @@+//! Histogram bucket overrides for `feature-flags` metrics.+//!+//! The default bucket ladder in `common-metrics` tops out at 10s and starts+//! at 1ms — both are wrong for the queue/pre-handler family of metrics+//! (which can spike past 10s during proxy/permit-wait stalls) and for the+//! rate-limit / DB-connection family (which normally completes in well+//! under 1ms and gets bucket-floored otherwise).+//!+//! Wired into the metrics recorder at startup via+//! [`common_metrics::setup_metrics_routes_for_product_with_overrides`].++use common_metrics::Matcher;++// Queue-time class buckets (ms). 30s ceiling = ~6× `request_timeout_ms`+// (4_500 ms) so Envoy retries and proxy stalls remain visible above the+// previous 10s floor used as the "real number" estimate.+const QUEUE_TIME_BUCKETS_MS: &[f64] = &[+ 1.0, 10.0, 50.0, 100.0, 250.0, 500.0, 1000.0, 2000.0, 5000.0, 10000.0, 15000.0, 30000.0,+];++// Sub-ms-aware buckets for DB pool acquire, governor rate-limit checks.+// These operations normally complete in < 1ms; the existing 1ms floor+// collapses the entire distribution into a single bucket.+const DB_CONNECTION_BUCKETS_MS: &[f64] = &[+ 0.05, 0.1, 0.25, 0.5, 1.0, 2.5, 5.0, 10.0, 25.0, 50.0, 100.0, 250.0, 500.0, 1000.0,+];++const RATE_LIMIT_CHECK_BUCKETS_MS: &[f64] = &[+ 0.1, 0.5, 1.0, 2.0, 5.0, 10.0, 50.0, 100.0, 250.0, 500.0, 1000.0,+];++// Token-extract scans the raw POST body. 5s ceiling captures pathological+// inputs without blowing up the bucket count.+const TOKEN_EXTRACT_BUCKETS_MS: &[f64] = &[+ 0.5, 1.0, 2.0, 5.0, 10.0, 25.0, 50.0, 100.0, 250.0, 500.0, 1000.0, 5000.0,+];++/// Returns the bucket-override matrix for the feature-flags recorder.+///+/// `Matcher::Suffix` is used for `_queue_time_ms` / `_pre_handler_time_ms`+/// so future per-component variants pick up the same buckets without an+/// extra entry. Any new metric in the feature-flags binary ending in+/// these suffixes will inherit these bucket boundaries — switch to+/// `Matcher::Full` if that is not desired. The other entries pin a+/// single metric name.+pub fn bucket_overrides() -> Vec<(Matcher, &'static [f64])> {+ vec![+ (+ Matcher::Suffix("_queue_time_ms".into()),+ QUEUE_TIME_BUCKETS_MS,+ ),+ (+ Matcher::Suffix("_pre_handler_time_ms".into()),+ QUEUE_TIME_BUCKETS_MS,+ ),+ (+ Matcher::Full("flags_concurrency_limit_wait_ms".into()),+ QUEUE_TIME_BUCKETS_MS,+ ),+ (+ Matcher::Full("flags_db_connection_time".into()),+ DB_CONNECTION_BUCKETS_MS,+ ),+ (+ Matcher::Full("flags_rate_limit_check_ms".into()),+ RATE_LIMIT_CHECK_BUCKETS_MS,+ ),+ (+ Matcher::Full("flags_token_extract_ms".into()),+ TOKEN_EXTRACT_BUCKETS_MS,+ ),+ ]+}diff --git a/rust/feature-flags/src/metrics/consts.rs b/rust/feature-flags/src/metrics/consts.rsindex ca4e72d3e4bc..7100c13bc2ef 100644--- a/rust/feature-flags/src/metrics/consts.rs+++ b/rust/feature-flags/src/metrics/consts.rs@@ -52,6 +52,29 @@ pub const FLAG_REQUESTS_LATENCY: &str = "flags_requests_duration_ms";pub const FLAG_QUEUE_TIME_MS: &str = "flags_queue_time_ms";pub const FLAG_REQUEST_FAULTS_COUNTER: &str = "flags_request_faults_total";+// Pre-handler timing decomposition for `flags_queue_time_ms`.+// Together these subdivide the "Envoy stamp → handler entry" wall time into+// known synchronous pre-handler work + (residual) proxy/tower wait, so we+// can attribute spikes to the right tier instead of guessing.++// Total time spent in synchronous pre-handler work inside `endpoint::flags`+// (UA parse, IP rate-limit, token extract, token rate-limit). Labeled by+// `team_id` so noisy customers are attributable.+pub const FLAG_PRE_HANDLER_TIME_MS: &str = "flags_pre_handler_time_ms";++// Per-step rate-limit check timing. Labeled by `kind="ip"|"token"` to+// distinguish the two rate-limiter calls inside the endpoint.+pub const FLAG_RATE_LIMIT_CHECK_TIME_MS: &str = "flags_rate_limit_check_ms";++// Time spent inside `decoding::extract_token` (sync JSON DOM scan over the+// raw body). Pathological large bodies are the suspected outlier driver.+pub const FLAG_TOKEN_EXTRACT_TIME_MS: &str = "flags_token_extract_ms";++// Permit-acquisition wait time on the tower `ConcurrencyLimitLayer`.+// Populated by Phase F; emitted only when populated. No `team_id` label+// because permit wait is a property of pod-level load, not of any one team.+pub const FLAG_CONCURRENCY_LIMIT_WAIT_TIME_MS: &str = "flags_concurrency_limit_wait_ms";+// Performance monitoringpub const DB_CONNECTION_POOL_ACTIVE_COUNTER: &str = "flags_db_connection_pool_active_total";pub const DB_CONNECTION_POOL_IDLE_COUNTER: &str = "flags_db_connection_pool_idle_total";diff --git a/rust/feature-flags/src/metrics/mod.rs b/rust/feature-flags/src/metrics/mod.rsindex e39cdefbbbff..9a8b7cb32f39 100644--- a/rust/feature-flags/src/metrics/mod.rs+++ b/rust/feature-flags/src/metrics/mod.rs@@ -1,2 +1,3 @@+pub mod buckets;pub mod consts;pub mod utils;diff --git a/rust/feature-flags/src/router.rs b/rust/feature-flags/src/router.rsindex c887149e00ea..5e2c0fa7247e 100644--- a/rust/feature-flags/src/router.rs+++ b/rust/feature-flags/src/router.rs@@ -18,7 +18,7 @@ use common_cookieless::CookielessManager;use common_geoip::GeoIpClient;use common_hypercache::HyperCacheReader;use common_metrics::inc;-use common_metrics::setup_metrics_routes_for_product;+use common_metrics::setup_metrics_routes_for_product_with_overrides;use common_redis::Client as RedisClient;use lifecycle::{LivenessHandler, ReadinessHandler};use metrics::gauge;@@ -44,6 +44,7 @@ use crate::{flag_group_type_mapping::GroupTypeCacheManager,},metrics::{+ buckets::bucket_overrides,consts::{FLAG_DEFINITIONS_RATE_LIMITED_COUNTER, FLAG_DEFINITIONS_RATE_LIMIT_BYPASSED_COUNTER,FLAG_DEFINITIONS_REQUESTS_COUNTER, FLAG_REQUEST_TIMEOUT_COUNTER,@@ -325,7 +326,11 @@ pub fn router(// In other words, only turn these on in productionif config.enable_metrics {common_metrics::set_label_filter(team_id_label_filter(config.team_ids_to_track.clone()));- setup_metrics_routes_for_product(router, "feature_flags")+ setup_metrics_routes_for_product_with_overrides(+ router,+ "feature_flags",+ &bucket_overrides(),+ )} else {router}