: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-v1): isolate kafka produce observability metrics (#63866)
Eli Reisman26d89fa11b6c
diff --git a/rust/capture/src/v1/sinks/DESIGN.md b/rust/capture/src/v1/sinks/DESIGN.mdindex b61bfa6f3b9d..221d598b1ab2 100644--- a/rust/capture/src/v1/sinks/DESIGN.md+++ b/rust/capture/src/v1/sinks/DESIGN.md@@ -522,6 +522,23 @@ for latency measurement.Polling them inline in a single task is strictly cheaper than spawningreal tokio tasks.+#### Single batch deadline vs per-event deadline (head-of-line coupling)++The deadline is **per batch**, not per event: `deadline = now ++produce_timeout` is computed once, after the whole batch is enqueued, and+every event in the batch shares it. Because enqueue is fast and serial, the+last event's clock starts only marginally after the first's, so per-event+`sent_at` (recorded for the ack-latency histogram) and the shared deadline+stay close in practice.++A per-event deadline (`sent_at + produce_timeout`, now feasible since WS3a+threads `sent_at` through) would decouple a slow head-of-line event from the+rest of the batch. It is **deliberately deferred**: the current model is+simpler, matches v0, and `capture_v1_kafka_ack_duration_seconds` (per-event,+including `outcome="timeout"`) now makes any head-of-line coupling directly+observable. Revisit only if load-test tails (WS7) show the shared deadline+materially penalizing fast events behind a slow one.+### Phase 3 — SweepAny keys in `enqueued_keys` not present in `resolved_keys` after the@@ -870,7 +887,9 @@ request.| `capture_v1_kafka_producer_queue_utilization` | gauge | `cluster`, `mode` | `stats()` (`msg_cnt / msg_max`) || `capture_v1_kafka_batch_size_bytes_avg` | gauge | `cluster`, `mode`, `topic` | `stats()` || `capture_v1_kafka_broker_connected` | gauge | `cluster`, `mode`, `broker` | `stats()` |-| `capture_v1_kafka_broker_rtt_us` | gauge | `cluster`, `mode`, `quantile`, `broker` | `stats()` (p50 and p99) |+| `capture_v1_kafka_broker_rtt_us` | gauge | `cluster`, `mode`, `quantile`, `broker` | `stats()` (full window: `min`/`avg`/`max`/`stddev`/`p50`/`p90`/`p95`/`p99`) |+| `capture_v1_kafka_broker_int_latency_us` | gauge | `cluster`, `mode`, `quantile`, `broker` | `stats()` — time in producer internal queue (full window) |+| `capture_v1_kafka_broker_outbuf_latency_us` | gauge | `cluster`, `mode`, `quantile`, `broker` | `stats()` — time in broker output buffer (full window) || `capture_v1_kafka_broker_tx_errors_total` | counter | `cluster`, `mode`, `broker` | `stats()` via `.absolute()` || `capture_v1_kafka_broker_rx_errors_total` | counter | `cluster`, `mode`, `broker` | `stats()` via `.absolute()` |@@ -885,7 +904,8 @@ request-level context (`path`, `attempt`).| Metric | Type | Labels | When ||---|---|---|---|| `capture_v1_kafka_publish_total` | counter | `mode`, `cluster`, `outcome`, `path`, `attempt` (capped at "6+"), `destination` | Every event outcome (success, error, timeout, reject) |-| `capture_v1_kafka_ack_duration_seconds` | histogram | `mode`, `cluster`, `outcome`, `path`, `attempt` (capped at "6+"), `destination` | Successful ack only |+| `capture_v1_kafka_ack_duration_seconds` | histogram | `mode`, `cluster`, `outcome`, `path`, `attempt` (capped at "6+"), `destination` | Per-event broker-ack latency (successful send → ack resolution), including `outcome="timeout"` for acks that miss `produce_timeout` |+| `capture_v1_kafka_enqueue_duration_seconds` | histogram | `mode`, `cluster`, `path`, `attempt` (capped at "6+") | Per-batch enqueue wall-time (the `enqueue_events` call), isolated from broker-ack latency || `capture_v1_kafka_queue_full_retries_total` | counter | `mode`, `cluster`, `result` | QueueFull retry (`result` = `recovered` or `exhausted`) |Cardinality note: the `destination` label is bounded at 9 valuesdiff --git a/rust/capture/src/v1/sinks/kafka/context.rs b/rust/capture/src/v1/sinks/kafka/context.rsindex f495acd54672..c579b8f5bd79 100644--- a/rust/capture/src/v1/sinks/kafka/context.rs+++ b/rust/capture/src/v1/sinks/kafka/context.rs@@ -9,6 +9,36 @@ use crate::v1::sinks::SinkName;const BROKER_STATE_UP: &str = "UP";+/// Emit min/avg/max/stddev + p50/p90/p95/p99 gauges for an rdkafka window+/// stat, tagged by `quantile` and `broker`.+fn emit_window_stats(+ metric: &'static str,+ w: &rdkafka::statistics::Window,+ sink: &'static str,+ mode: &'static str,+ broker: &Arc<str>,+) {+ for (quantile, value) in [+ ("min", w.min),+ ("avg", w.avg),+ ("max", w.max),+ ("stddev", w.stddev),+ ("p50", w.p50),+ ("p90", w.p90),+ ("p95", w.p95),+ ("p99", w.p99),+ ] {+ gauge!(+ metric,+ "cluster" => sink,+ "mode" => mode,+ "quantile" => quantile,+ "broker" => Arc::clone(broker),+ )+ .set(value as f64);+ }+}+// ---------------------------------------------------------------------------// KafkaContext// ---------------------------------------------------------------------------@@ -101,15 +131,29 @@ impl rdkafka::ClientContext for KafkaContext {} else {0.0});+ // Broker round-trip latency.if let Some(rtt) = &bs.rtt {- gauge!("capture_v1_kafka_broker_rtt_us",- "cluster" => sink, "mode" => mode,- "quantile" => "p50", "broker" => Arc::clone(&id))- .set(rtt.p50 as f64);- gauge!("capture_v1_kafka_broker_rtt_us",- "cluster" => sink, "mode" => mode,- "quantile" => "p99", "broker" => Arc::clone(&id))- .set(rtt.p99 as f64);+ emit_window_stats("capture_v1_kafka_broker_rtt_us", rtt, sink, mode, &id);+ }+ // Internal queue time (linger + backlog).+ if let Some(int_latency) = &bs.int_latency {+ emit_window_stats(+ "capture_v1_kafka_broker_int_latency_us",+ int_latency,+ sink,+ mode,+ &id,+ );+ }+ // Output buffer time before wire send.+ if let Some(outbuf_latency) = &bs.outbuf_latency {+ emit_window_stats(+ "capture_v1_kafka_broker_outbuf_latency_us",+ outbuf_latency,+ sink,+ mode,+ &id,+ );}counter!("capture_v1_kafka_broker_tx_errors_total","cluster" => sink, "mode" => mode, "broker" => Arc::clone(&id))diff --git a/rust/capture/src/v1/sinks/kafka/sink.rs b/rust/capture/src/v1/sinks/kafka/sink.rsindex 37c34b72108f..ed3c59d03cf2 100644--- a/rust/capture/src/v1/sinks/kafka/sink.rs+++ b/rust/capture/src/v1/sinks/kafka/sink.rs@@ -2,7 +2,7 @@ use std::collections::HashSet;use std::future::Future;use std::pin::Pin;use std::sync::Arc;-use std::time::Duration;+use std::time::{Duration, Instant};use async_trait::async_trait;use chrono::{DateTime, Utc};@@ -136,6 +136,7 @@ type AckFuture = Pin<Uuid,&'static str,DateTime<Utc>,+ Duration,Result<(), super::producer::ProduceError>,),> + Send,@@ -156,7 +157,7 @@ impl<P: KafkaProducerTrait + 'static> KafkaSink<P> {enqueued_at: DateTime<Utc>,results: &mut Vec<Box<dyn SinkResult>>,pending: &mut FuturesUnordered<AckFuture>,- enqueued_keys: &mut Vec<(Uuid, &'static str)>,+ enqueued_keys: &mut Vec<(Uuid, &'static str, Instant)>,) {let mut payload_buf = String::with_capacity(4096);let mut key_buf = String::with_capacity(128);@@ -243,10 +244,12 @@ impl<P: KafkaProducerTrait + 'static> KafkaSink<P> {).increment(1);}- enqueued_keys.push((uuid, dest_tag));+ let sent_at = Instant::now();+ enqueued_keys.push((uuid, dest_tag, sent_at));pending.push(Box::pin(async move {let result = ack_future.await;- (uuid, dest_tag, Utc::now(), result)+ let ack_latency = sent_at.elapsed();+ (uuid, dest_tag, Utc::now(), ack_latency, result)}));break;}@@ -304,7 +307,7 @@ impl<P: KafkaProducerTrait + 'static> KafkaSink<P> {loop {match tokio::time::timeout_at(deadline, pending.next()).await {- Ok(Some((uuid, dest_tag, completed_at, ack))) => {+ Ok(Some((uuid, dest_tag, completed_at, ack_latency, ack))) => {resolved_keys.insert(uuid);let outcome_tag = match &ack {@@ -329,19 +332,18 @@ impl<P: KafkaProducerTrait + 'static> KafkaSink<P> {).increment(1);- let elapsed = completed_at.signed_duration_since(enqueued_at);- if let Ok(secs) = elapsed.to_std() {- histogram!(- "capture_v1_kafka_ack_duration_seconds",- "mode" => labels.mode,- "cluster" => labels.sink,- "outcome" => outcome_tag,- "path" => labels.path,- "attempt" => labels.attempt,- "destination" => dest_tag,- )- .record(secs.as_secs_f64());- }+ // Per-event broker-ack latency (send → ack), isolated from+ // batch enqueue wall-time.+ histogram!(+ "capture_v1_kafka_ack_duration_seconds",+ "mode" => labels.mode,+ "cluster" => labels.sink,+ "outcome" => outcome_tag,+ "path" => labels.path,+ "attempt" => labels.attempt,+ "destination" => dest_tag,+ )+ .record(ack_latency.as_secs_f64());match ack {Ok(()) => results.push(Box::new(@@ -365,20 +367,20 @@ impl<P: KafkaProducerTrait + 'static> KafkaSink<P> {fn collect_timeouts(labels: &MetricLabels,enqueued_at: DateTime<Utc>,- enqueued_keys: Vec<(Uuid, &'static str)>,+ enqueued_keys: Vec<(Uuid, &'static str, Instant)>,resolved_keys: &HashSet<Uuid>,results: &mut Vec<Box<dyn SinkResult>>,) {let timed_out: Vec<_> = enqueued_keys.into_iter()- .filter(|(k, _)| !resolved_keys.contains(k))+ .filter(|(k, _, _)| !resolved_keys.contains(k)).collect();if timed_out.is_empty() {return;}let mut by_dest: std::collections::HashMap<&'static str, u64> =std::collections::HashMap::new();- for (_, dest_tag) in &timed_out {+ for (_, dest_tag, _) in &timed_out {*by_dest.entry(dest_tag).or_default() += 1;}for (dest_tag, count) in &by_dest {@@ -394,7 +396,19 @@ impl<P: KafkaProducerTrait + 'static> KafkaSink<P> {.increment(*count);}let gave_up_at = Utc::now();- for (uuid, _) in timed_out {+ for (uuid, dest_tag, sent_at) in timed_out {+ // Record timed-out acks so the latency tail (>= produce_timeout)+ // is visible rather than silently dropped.+ histogram!(+ "capture_v1_kafka_ack_duration_seconds",+ "mode" => labels.mode,+ "cluster" => labels.sink,+ "outcome" => Outcome::Timeout.as_tag(),+ "path" => labels.path,+ "attempt" => labels.attempt,+ "destination" => dest_tag,+ )+ .record(sent_at.elapsed().as_secs_f64());results.push(Box::new(KafkaResult::err(uuid, KafkaSinkError::Timeout, enqueued_at).with_completed_at(gave_up_at),@@ -435,8 +449,10 @@ impl<P: KafkaProducerTrait + 'static> Sink for KafkaSink<P> {let enqueued_at = Utc::now();let mut results: Vec<Box<dyn SinkResult>> = Vec::new();let mut pending: FuturesUnordered<AckFuture> = FuturesUnordered::new();- let mut enqueued_keys: Vec<(Uuid, &'static str)> = Vec::new();+ let mut enqueued_keys: Vec<(Uuid, &'static str, Instant)> = Vec::new();+ // Enqueue wall-time, isolated from per-event broker-ack latency.+ let enqueue_start = Instant::now();self.enqueue_events(ctx,events,@@ -447,6 +463,14 @@ impl<P: KafkaProducerTrait + 'static> Sink for KafkaSink<P> {&mut enqueued_keys,).await;+ histogram!(+ "capture_v1_kafka_enqueue_duration_seconds",+ "mode" => labels.mode,+ "cluster" => labels.sink,+ "path" => labels.path,+ "attempt" => labels.attempt,+ )+ .record(enqueue_start.elapsed().as_secs_f64());let resolved_keys = self.drain_acks(&labels, enqueued_at, &mut results, &mut pending)diff --git a/rust/capture/src/v1/sinks/kafka/sink_tests.rs b/rust/capture/src/v1/sinks/kafka/sink_tests.rsindex 62058eb07c73..3d8653d82f88 100644--- a/rust/capture/src/v1/sinks/kafka/sink_tests.rs+++ b/rust/capture/src/v1/sinks/kafka/sink_tests.rs@@ -739,6 +739,37 @@ async fn batch_summary_with_timeouts() {assert_eq!(summary.errors.get("timeout").copied(), Some(2));}+// ---------------------------------------------------------------------------+// Slow-ack path: acks resolve within produce_timeout → all events succeed.+// ---------------------------------------------------------------------------++#[tokio::test]+async fn slow_ack_within_timeout_batch_all_succeed() {+ let h = TestHarness::builder()+ .ack_delay(Duration::from_millis(20))+ .produce_timeout(Duration::from_secs(30))+ .build();+ let e1 = FakeEvent::ok("evt-1");+ let e2 = FakeEvent::ok("evt-2");+ let e3 = FakeEvent::ok("evt-3");+ let events: Vec<&(dyn Event + Send + Sync)> = vec![&e1, &e2, &e3];++ let results = h.sink.publish_batch(&h.ctx, &events).await;++ assert_eq!(results.len(), 3);+ for r in &results {+ assert_eq!(r.outcome(), Outcome::Success);+ assert!(r.cause().is_none());+ assert!(r.elapsed().is_some());+ }+ assert_eq!(h.producer.record_count(), 3);++ let by_key: HashMap<Uuid, _> = results.iter().map(|r| (r.key(), r)).collect();+ assert!(by_key.contains_key(&e1.parsed_uuid));+ assert!(by_key.contains_key(&e2.parsed_uuid));+ assert!(by_key.contains_key(&e3.parsed_uuid));+}+// ===========================================================================// Health heartbeat tests//