: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
fix(ingestion): preserve rust consumer batch ordering (#62169)
José Sequeira7c5aaf297b2c
diff --git a/rust/ingestion-consumer/src/config.rs b/rust/ingestion-consumer/src/config.rsindex 41ae043a357c..b6fd0187c6d8 100644--- a/rust/ingestion-consumer/src/config.rs+++ b/rust/ingestion-consumer/src/config.rs@@ -108,6 +108,11 @@ pub struct Config {#[envconfig(default = "500")]pub consumer_batch_timeout_ms: u64,+ /// Maximum Kafka batches to process concurrently. Matches the Node.js+ /// CONSUMER_MAX_BACKGROUND_TASKS setting used by the Kafka consumer wrapper.+ #[envconfig(from = "CONSUMER_MAX_BACKGROUND_TASKS", default = "1")]+ pub consumer_max_background_tasks: usize,+// ---- Worker transport ----/// Comma-separated list of worker HTTP URLs#[envconfig(default = "http://localhost:9001")]diff --git a/rust/ingestion-consumer/src/consumer.rs b/rust/ingestion-consumer/src/consumer.rsindex 9dd81d8981b2..49c157769653 100644--- a/rust/ingestion-consumer/src/consumer.rs+++ b/rust/ingestion-consumer/src/consumer.rs@@ -1,4 +1,4 @@-use std::collections::HashMap;+use std::collections::{HashMap, VecDeque};use std::sync::Arc;use std::time::{Duration, Instant};@@ -6,8 +6,9 @@ use futures::StreamExt;use lifecycle::Handle;use metrics::{counter, gauge, histogram};use rdkafka::consumer::{CommitMode, Consumer, StreamConsumer};-use rdkafka::message::Message;+use rdkafka::message::{Headers, Message};use rdkafka::TopicPartitionList;+use tokio::task::JoinHandle;use tracing::{error, info, warn};use crate::config::Config;@@ -17,13 +18,13 @@ use crate::types::SerializedKafkaMessage;/// Statistics gathered while collecting a batch, used to emit parity metrics.struct BatchStats {- /// Max Kafka message timestamp (ms) per (topic, partition) — for `latestOffsetTimestampGauge`.+ /// Max Kafka message timestamp (ms) per (topic, partition) — for `latest_processed_timestamp_ms`.latest_kafka_ts: HashMap<(String, i32), i64>,- /// Max ingestion lag (ms) per (topic, partition) — for `ingestionLagGauge`.+ /// Max ingestion lag (ms) per (topic, partition) — for `ingestion_lag_ms`.max_lag_ms: HashMap<(String, i32), i64>,- /// Per-message (partition, lag_ms) pairs — for `ingestionLagHistogram`.+ /// Per-message (partition, lag_ms) pairs — for `ingestion_lag_ms_histogram`.message_lags_ms: Vec<(i32, i64)>,- /// Total byte size of message payloads — for `consumerBatchSizeKb`.+ /// Total byte size of message payloads — for `consumer_batch_size_kb`.total_bytes: usize,}@@ -45,11 +46,24 @@ struct CollectedBatch {stats: BatchStats,}+struct ProcessedBatch {+ offsets: HashMap<(String, i32), i64>,+ stats: BatchStats,+ total_accepted: u32,+ elapsed: Duration,+}++struct InFlightBatch {+ batch_id: String,+ handle: JoinHandle<anyhow::Result<ProcessedBatch>>,+}+/// Options for constructing an [`IngestionConsumer`] from pre-built parts./// Used in integration tests where the Kafka consumer is created externally.pub struct IngestionConsumerOptions {pub batch_size: usize,pub batch_timeout: Duration,+ pub max_in_flight_batches: usize,pub group_id: String,}@@ -63,6 +77,7 @@ pub struct IngestionConsumer {worker_urls: Vec<String>,batch_size: usize,batch_timeout: Duration,+ max_in_flight_batches: usize,handle: Handle,group_id: String,}@@ -85,6 +100,7 @@ impl IngestionConsumer {worker_urls,batch_size: options.batch_size,batch_timeout: options.batch_timeout,+ max_in_flight_batches: options.max_in_flight_batches.max(1),handle,group_id: options.group_id,}@@ -120,6 +136,7 @@ impl IngestionConsumer {worker_urls,batch_size: config.consumer_batch_size,batch_timeout: Duration::from_millis(config.consumer_batch_timeout_ms),+ max_in_flight_batches: config.consumer_max_background_tasks.max(1),handle,group_id: config.ingestion_consumer_group_id.clone(),})@@ -144,79 +161,173 @@ impl IngestionConsumer {info!("Consumer loop starting");- loop {- tokio::select! {- _ = self.handle.shutdown_recv() => {- info!("Shutdown signal received, draining");- break;- }- result = self.process_batch() => {- match result {- Ok(count) => {- if count > 0 {- self.handle.report_healthy();- counter!("ingestion_consumer_batches_processed_total").increment(1);+ let mut in_flight_batches = VecDeque::new();+ let mut accepting_new_batches = true;++ while accepting_new_batches || !in_flight_batches.is_empty() {+ if accepting_new_batches && in_flight_batches.len() < self.max_in_flight_batches {+ tokio::select! {+ _ = self.handle.shutdown_recv() => {+ info!(+ in_flight = in_flight_batches.len(),+ "Shutdown signal received, draining in-flight batches"+ );+ accepting_new_batches = false;+ }+ result = self.collect_batch() => {+ let collected = match result {+ Ok(collected) => collected,+ Err(err) => {+ self.fail_batch_processing(err);+ return;+ }+ };++ if collected.messages.is_empty() {+ self.handle.report_healthy();+ if in_flight_batches.is_empty() {+ continue;+ }+ } else {+ in_flight_batches.push_back(self.spawn_batch_processing(collected));+ self.handle.report_healthy();++ if in_flight_batches.len() < self.max_in_flight_batches {+ continue;}- }- Err(err) => {- error!(error = %err, "Batch processing failed");- counter!("ingestion_consumer_batch_errors_total").increment(1);- tokio::time::sleep(Duration::from_secs(1)).await;}}}}++ if let Err(err) = self.complete_oldest_batch(&mut in_flight_batches).await {+ self.fail_batch_processing(err);+ return;+ }}info!("Consumer loop stopped");}- /// Collect a batch, assign it via the Dispatcher, scatter to workers,- /// gather results, feed passive health signals, and commit offsets.- async fn process_batch(&self) -> anyhow::Result<usize> {- let collected = self.collect_batch().await?;- if collected.messages.is_empty() {- return Ok(0);+ fn spawn_batch_processing(&self, collected: CollectedBatch) -> InFlightBatch {+ let batch_size = collected.messages.len();+ let batch_id = make_batch_id();+ let task_batch_id = batch_id.clone();+ let dispatcher = Arc::clone(&self.dispatcher);+ let transport = Arc::clone(&self.transport);+ let worker_urls = self.worker_urls.clone();+ let group_id = self.group_id.clone();++ let handle = tokio::spawn(async move {+ Self::process_collected_batch(+ collected,+ task_batch_id,+ dispatcher,+ transport,+ worker_urls,+ group_id,+ )+ .await+ });++ info!(+ batch_id = %batch_id,+ messages = batch_size,+ "Kafka batch dispatched"+ );++ InFlightBatch { batch_id, handle }+ }++ async fn complete_oldest_batch(+ &self,+ in_flight_batches: &mut VecDeque<InFlightBatch>,+ ) -> anyhow::Result<()> {+ let Some(batch) = in_flight_batches.pop_front() else {+ return Ok(());+ };++ let processed = self.await_processed_batch(batch).await?;++ // Commit only the oldest completed batch. Later successful batches stay+ // uncommitted behind any earlier failed batch, preserving at-least-once+ // delivery across worker or pipeline failures.+ self.commit_offsets(&processed.offsets)?;+ emit_latest_processed_timestamp_metrics(&processed.stats, &self.group_id);++ histogram!("ingestion_consumer_batch_processing_duration_seconds")+ .record(processed.elapsed.as_secs_f64());+ counter!("ingestion_consumer_messages_processed_total")+ .increment(processed.total_accepted as u64);+ counter!("ingestion_consumer_batches_processed_total").increment(1);+ self.handle.report_healthy();++ Ok(())+ }++ async fn await_processed_batch(&self, batch: InFlightBatch) -> anyhow::Result<ProcessedBatch> {+ let batch_id = batch.batch_id;+ let mut handle = batch.handle;+ let mut heartbeat = tokio::time::interval(Duration::from_secs(10));++ loop {+ tokio::select! {+ result = &mut handle => {+ let processed = result??;+ info!(batch_id = %batch_id, "Kafka batch processing completed");+ return Ok(processed);+ }+ _ = heartbeat.tick() => {+ self.handle.report_healthy();+ }+ }}+ }++ fn fail_batch_processing(&self, err: anyhow::Error) {+ error!(error = %err, "Batch processing failed");+ counter!("ingestion_consumer_batch_errors_total").increment(1);+ self.handle+ .signal_failure(format!("Batch processing failed: {err:#}"));+ }+ /// Assign a collected batch via the Dispatcher, scatter to workers, gather+ /// results, and feed passive health signals. Offset commits happen later,+ /// in Kafka batch order, in `complete_oldest_batch`.+ async fn process_collected_batch(+ collected: CollectedBatch,+ batch_id: String,+ dispatcher: Arc<Dispatcher>,+ transport: Arc<HttpTransport>,+ worker_urls: Vec<String>,+ group_id: String,+ ) -> anyhow::Result<ProcessedBatch> {let batch_size = collected.messages.len();- let batch_id = make_batch_id();let start = Instant::now();counter!("ingestion_consumer_messages_received_total").increment(batch_size as u64);gauge!("ingestion_consumer_batch_size").set(batch_size as f64);- // Batch size distribution — matches Node.js `consumerBatchSize` histogram.- histogram!("consumerBatchSize").record(batch_size as f64);- histogram!("consumerBatchSizeKb").record(collected.stats.total_bytes as f64 / 1024.0);-- // Per-partition latest committed timestamp — matches Node.js `latestOffsetTimestampGauge`.- for ((topic, partition), ts_ms) in &collected.stats.latest_kafka_ts {- gauge!(- "latestOffsetTimestampGauge",- "topic" => topic.clone(),- "partition" => partition.to_string(),- "groupId" => self.group_id.clone()- )- .set(*ts_ms as f64);- }+ // Batch size distribution — matches Node.js `consumer_batch_size` histogram.+ histogram!("consumer_batch_size").record(batch_size as f64);+ histogram!("consumer_batch_size_kb").record(collected.stats.total_bytes as f64 / 1024.0);- // Per-partition ingestion lag gauge — matches Node.js `ingestionLagGauge`.+ // Per-partition ingestion lag gauge — matches Node.js `ingestion_lag_ms`.for ((topic, partition), max_lag) in &collected.stats.max_lag_ms {gauge!(- "ingestionLagGauge",+ "ingestion_lag_ms","topic" => topic.clone(),"partition" => partition.to_string(),- "groupId" => self.group_id.clone()+ "groupId" => group_id.clone()).set(*max_lag as f64);}- // Per-message lag histogram — matches Node.js `ingestionLagHistogram`.+ // Per-message lag histogram — matches Node.js `ingestion_lag_ms_histogram`.for (partition, lag_ms) in &collected.stats.message_lags_ms {histogram!(- "ingestionLagHistogram",- "groupId" => self.group_id.clone(),+ "ingestion_lag_ms_histogram",+ "groupId" => group_id.clone(),"partition" => partition.to_string()).record(*lag_ms as f64);@@ -224,7 +335,7 @@ impl IngestionConsumer {// Health-aware assignment: groups by routing key, honors stickiness,// skips unhealthy/dead workers.- let sub_batches = self.dispatcher.assign(collected.messages);+ let sub_batches = dispatcher.assign(collected.messages);if sub_batches.is_empty() {counter!("ingestion_consumer_no_healthy_workers_total").increment(1);@@ -234,9 +345,9 @@ impl IngestionConsumer {// Scatter: send sub-batches to workers in parallel.let mut handles = Vec::with_capacity(sub_batches.len());for sub_batch in sub_batches {- let transport = Arc::clone(&self.transport);- let dispatcher = Arc::clone(&self.dispatcher);- let url = self.worker_urls[sub_batch.worker_idx].clone();+ let transport = Arc::clone(&transport);+ let dispatcher = Arc::clone(&dispatcher);+ let url = worker_urls[sub_batch.worker_idx].clone();let bid = batch_id.clone();let worker_idx = sub_batch.worker_idx;let routing_keys = sub_batch.routing_keys.clone();@@ -265,15 +376,12 @@ impl IngestionConsumer {);}- // All workers ACK'd — commit offsets.- self.commit_offsets(&collected.offsets)?;-- let elapsed = start.elapsed();- histogram!("ingestion_consumer_batch_processing_duration_seconds")- .record(elapsed.as_secs_f64());- counter!("ingestion_consumer_messages_processed_total").increment(total_accepted as u64);-- Ok(batch_size)+ Ok(ProcessedBatch {+ offsets: collected.offsets,+ stats: collected.stats,+ total_accepted,+ elapsed: start.elapsed(),+ })}/// Collect messages from Kafka up to batch_size or batch_timeout.@@ -296,7 +404,8 @@ impl IngestionConsumer {break;}- match tokio::time::timeout(remaining, stream.next()).await {+ let poll_wait = remaining.min(Duration::from_secs(10));+ match tokio::time::timeout(poll_wait, stream.next()).await {Ok(Some(Ok(borrowed_message))) => {let topic = borrowed_message.topic().to_string();let partition = borrowed_message.partition();@@ -327,7 +436,6 @@ impl IngestionConsumer {let mut headers = HashMap::new();if let Some(rdkafka_headers) = borrowed_message.headers() {- use rdkafka::message::Headers;for i in 0..rdkafka_headers.count() {let header = rdkafka_headers.get(i);if let Some(value) = header.value {@@ -376,7 +484,12 @@ impl IngestionConsumer {break;}Ok(None) => break,- Err(_) => break, // Timeout+ Err(_) => {+ self.handle.report_healthy();+ if Instant::now() >= deadline {+ break;+ }+ }}}@@ -429,3 +542,17 @@ fn parse_now_ms(value: &str) -> Option<i64> {.ok().map(|dt| dt.timestamp_millis())}++fn emit_latest_processed_timestamp_metrics(stats: &BatchStats, group_id: &str) {+ // Per-partition latest committed timestamp — matches Node.js+ // `latest_processed_timestamp_ms`.+ for ((topic, partition), ts_ms) in &stats.latest_kafka_ts {+ gauge!(+ "latest_processed_timestamp_ms",+ "topic" => topic.clone(),+ "partition" => partition.to_string(),+ "groupId" => group_id.to_string()+ )+ .set(*ts_ms as f64);+ }+}diff --git a/rust/ingestion-consumer/src/main.rs b/rust/ingestion-consumer/src/main.rsindex c1cf88ecd173..1e335bba82c7 100644--- a/rust/ingestion-consumer/src/main.rs+++ b/rust/ingestion-consumer/src/main.rs@@ -95,28 +95,28 @@ async fn async_main(config: Config) -> Result<()> {Some(PrometheusBuilder::new().set_buckets_for_metric(- Matcher::Full("ingestionLagHistogram".into()),+ Matcher::Full("ingestion_lag_ms_histogram".into()),&[1_000.0, 2_000.0, 5_000.0, 10_000.0, 30_000.0, 60_000.0, 120_000.0,300_000.0, 600_000.0, 900_000.0,],)- .expect("ingestionLagHistogram buckets")+ .expect("ingestion_lag_ms_histogram buckets").set_buckets_for_metric(- Matcher::Full("consumerBatchSize".into()),+ Matcher::Full("consumer_batch_size".into()),&[0.0, 50.0, 100.0, 250.0, 500.0, 750.0, 1_000.0, 1_500.0, 2_000.0, 3_000.0,],)- .expect("consumerBatchSize buckets")+ .expect("consumer_batch_size buckets").set_buckets_for_metric(- Matcher::Full("consumerBatchSizeKb".into()),+ Matcher::Full("consumer_batch_size_kb".into()),&[0.0, 128.0, 512.0, 1_024.0, 5_120.0, 10_240.0, 20_480.0, 51_200.0,102_400.0, 204_800.0,],)- .expect("consumerBatchSizeKb buckets")+ .expect("consumer_batch_size_kb buckets").install_recorder().expect("failed to install Prometheus recorder"),)diff --git a/rust/ingestion-consumer/tests/e2e_integration_test.rs b/rust/ingestion-consumer/tests/e2e_integration_test.rsindex 94dd948ba964..e6d0eadc603c 100644--- a/rust/ingestion-consumer/tests/e2e_integration_test.rs+++ b/rust/ingestion-consumer/tests/e2e_integration_test.rs@@ -259,6 +259,7 @@ impl Harness {IngestionConsumerOptions {batch_size: 50,batch_timeout: Duration::from_millis(100),+ max_in_flight_batches: 1,group_id: "e2e-test".to_string(),},handle,