Skip to content

: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.

feat(ingestion-consumer): Wire up Dispatcher and Registry, add e2e tests (#60832)

José Sequeirac6edf443c801
diff --git a/rust/Cargo.lock b/rust/Cargo.lock
index 706e1a3f0001..dec9ed121931 100644
--- a/rust/Cargo.lock
+++ b/rust/Cargo.lock
@@ -4966,6 +4966,7 @@ version = "0.1.0"
dependencies = [
"anyhow",
"axum 0.7.9",
+ "chrono",
"common-alloc",
"envconfig",
"futures",
@@ -4976,11 +4977,13 @@ dependencies = [
"rdkafka",
"reqwest 0.12.28",
"serde",
+ "serde_json",
"thiserror 2.0.18",
"tokio",
"tokio-util",
"tracing",
"tracing-subscriber",
+ "uuid",
]
[[package]]
diff --git a/rust/ingestion-consumer/Cargo.toml b/rust/ingestion-consumer/Cargo.toml
index ff20966296e3..46a4ec36d20e 100644
--- a/rust/ingestion-consumer/Cargo.toml
+++ b/rust/ingestion-consumer/Cargo.toml
@@ -6,6 +6,7 @@ edition = "2021"
[dependencies]
anyhow = { workspace = true }
axum = { workspace = true }
+chrono = { workspace = true }
common-alloc = { path = "../common/alloc" }
envconfig = { workspace = true }
futures = { workspace = true }
@@ -21,3 +22,7 @@ tokio = { workspace = true }
tokio-util = { workspace = true }
tracing = { workspace = true }
tracing-subscriber = { workspace = true, features = ["env-filter", "json"] }
+
+[dev-dependencies]
+serde_json = { workspace = true }
+uuid = { workspace = true }
diff --git a/rust/ingestion-consumer/src/consumer.rs b/rust/ingestion-consumer/src/consumer.rs
index f0bf0f0afe1f..9dd81d8981b2 100644
--- a/rust/ingestion-consumer/src/consumer.rs
+++ b/rust/ingestion-consumer/src/consumer.rs
@@ -11,28 +11,88 @@ use rdkafka::TopicPartitionList;
use tracing::{error, info, warn};
use crate::config::Config;
-use crate::router::MessageRouter;
+use crate::dispatcher::Dispatcher;
use crate::transport::HttpTransport;
use crate::types::SerializedKafkaMessage;
-/// The main consumer loop: reads from Kafka, routes messages by distinct_id,
-/// dispatches sub-batches to workers via HTTP, and commits offsets on ACK.
-///
-/// This is the single-in-flight-batch version (Stage 2). It processes one
-/// batch at a time — no concurrent batch tracking or in-flight stickiness.
+/// Statistics gathered while collecting a batch, used to emit parity metrics.
+struct BatchStats {
+ /// Max Kafka message timestamp (ms) per (topic, partition) — for `latestOffsetTimestampGauge`.
+ latest_kafka_ts: HashMap<(String, i32), i64>,
+ /// Max ingestion lag (ms) per (topic, partition) — for `ingestionLagGauge`.
+ max_lag_ms: HashMap<(String, i32), i64>,
+ /// Per-message (partition, lag_ms) pairs — for `ingestionLagHistogram`.
+ message_lags_ms: Vec<(i32, i64)>,
+ /// Total byte size of message payloads — for `consumerBatchSizeKb`.
+ total_bytes: usize,
+}
+
+impl BatchStats {
+ fn new() -> Self {
+ Self {
+ latest_kafka_ts: HashMap::new(),
+ max_lag_ms: HashMap::new(),
+ message_lags_ms: Vec::new(),
+ total_bytes: 0,
+ }
+ }
+}
+
+/// Output of `collect_batch`.
+struct CollectedBatch {
+ messages: Vec<SerializedKafkaMessage>,
+ offsets: HashMap<(String, i32), i64>,
+ stats: BatchStats,
+}
+
+/// 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 group_id: String,
+}
+
+/// The main consumer loop: reads from Kafka, routes messages by distinct_id
+/// via the health-aware Dispatcher, dispatches sub-batches to workers over
+/// HTTP, and commits offsets only after all workers ACK.
pub struct IngestionConsumer {
consumer: StreamConsumer,
- router: MessageRouter,
+ dispatcher: Arc<Dispatcher>,
transport: Arc<HttpTransport>,
worker_urls: Vec<String>,
batch_size: usize,
batch_timeout: Duration,
handle: Handle,
+ group_id: String,
}
impl IngestionConsumer {
+ /// Constructs a consumer from pre-built parts. Useful in integration tests
+ /// where the Kafka consumer is created and subscribed externally.
+ pub fn from_parts(
+ consumer: StreamConsumer,
+ dispatcher: Arc<Dispatcher>,
+ transport: Arc<HttpTransport>,
+ worker_urls: Vec<String>,
+ options: IngestionConsumerOptions,
+ handle: Handle,
+ ) -> Self {
+ Self {
+ consumer,
+ dispatcher,
+ transport,
+ worker_urls,
+ batch_size: options.batch_size,
+ batch_timeout: options.batch_timeout,
+ handle,
+ group_id: options.group_id,
+ }
+ }
+
pub fn new(
config: &Config,
+ dispatcher: Arc<Dispatcher>,
transport: Arc<HttpTransport>,
handle: Handle,
) -> anyhow::Result<Self> {
@@ -41,8 +101,6 @@ impl IngestionConsumer {
anyhow::bail!("No worker addresses configured");
}
- let router = MessageRouter::new(worker_urls.len());
-
let client_config = config.build_consumer_config();
let consumer: StreamConsumer = client_config.create()?;
consumer.subscribe(&[&config.ingestion_consumer_consume_topic])?;
@@ -57,12 +115,13 @@ impl IngestionConsumer {
Ok(Self {
consumer,
- router,
+ dispatcher,
transport,
worker_urls,
batch_size: config.consumer_batch_size,
batch_timeout: Duration::from_millis(config.consumer_batch_timeout_ms),
handle,
+ group_id: config.ingestion_consumer_group_id.clone(),
})
}
@@ -112,35 +171,88 @@ impl IngestionConsumer {
info!("Consumer loop stopped");
}
- /// Collect a batch, route it, scatter to workers, gather ACKs, commit offsets.
+ /// 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 (messages, offsets) = self.collect_batch().await?;
- if messages.is_empty() {
+ let collected = self.collect_batch().await?;
+ if collected.messages.is_empty() {
return Ok(0);
}
- let batch_size = messages.len();
+ 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);
- // Route messages to workers
- let groups = self.router.route_batch(messages);
+ // 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);
+ }
+
+ // Per-partition ingestion lag gauge — matches Node.js `ingestionLagGauge`.
+ for ((topic, partition), max_lag) in &collected.stats.max_lag_ms {
+ gauge!(
+ "ingestionLagGauge",
+ "topic" => topic.clone(),
+ "partition" => partition.to_string(),
+ "groupId" => self.group_id.clone()
+ )
+ .set(*max_lag as f64);
+ }
+
+ // Per-message lag histogram — matches Node.js `ingestionLagHistogram`.
+ for (partition, lag_ms) in &collected.stats.message_lags_ms {
+ histogram!(
+ "ingestionLagHistogram",
+ "groupId" => self.group_id.clone(),
+ "partition" => partition.to_string()
+ )
+ .record(*lag_ms as f64);
+ }
+
+ // Health-aware assignment: groups by routing key, honors stickiness,
+ // skips unhealthy/dead workers.
+ let sub_batches = self.dispatcher.assign(collected.messages);
- // Scatter: send sub-batches to workers in parallel
- let mut handles = Vec::with_capacity(groups.len());
- for (worker_idx, sub_batch) in groups {
- let transport = self.transport.clone();
- let url = self.worker_urls[worker_idx].clone();
+ if sub_batches.is_empty() {
+ counter!("ingestion_consumer_no_healthy_workers_total").increment(1);
+ anyhow::bail!("No healthy workers available to route batch");
+ }
+
+ // 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 bid = batch_id.clone();
+ let worker_idx = sub_batch.worker_idx;
+ let routing_keys = sub_batch.routing_keys.clone();
+
handles.push(tokio::spawn(async move {
- transport.send_batch(&url, &bid, sub_batch).await
+ let result = transport.send_batch(&url, &bid, sub_batch.messages).await;
+ let is_error = result.is_err();
+
+ dispatcher.on_sub_batch_resolved(worker_idx, &routing_keys);
+ dispatcher.record_send_outcome(worker_idx, is_error);
+
+ result
}));
}
- // Gather: wait for all workers to ACK
+ // Gather: wait for all workers to ACK.
let mut total_accepted = 0u32;
for handle in handles {
let result = handle.await??;
@@ -153,8 +265,8 @@ impl IngestionConsumer {
);
}
- // All workers ACK'd all messages — commit offsets
- self.commit_offsets(&offsets)?;
+ // All workers ACK'd — commit offsets.
+ self.commit_offsets(&collected.offsets)?;
let elapsed = start.elapsed();
histogram!("ingestion_consumer_batch_processing_duration_seconds")
@@ -165,12 +277,12 @@ impl IngestionConsumer {
}
/// Collect messages from Kafka up to batch_size or batch_timeout.
- async fn collect_batch(
- &self,
- ) -> anyhow::Result<(Vec<SerializedKafkaMessage>, HashMap<(String, i32), i64>)> {
+ async fn collect_batch(&self) -> anyhow::Result<CollectedBatch> {
let mut messages = Vec::with_capacity(self.batch_size);
let mut offsets: HashMap<(String, i32), i64> = HashMap::new();
+ let mut stats = BatchStats::new();
let deadline = Instant::now() + self.batch_timeout;
+ let batch_start_ms = current_time_ms();
let mut stream = self.consumer.stream();
@@ -199,6 +311,20 @@ impl IngestionConsumer {
})
.or_insert(offset);
+ let kafka_ts = borrowed_message.timestamp().to_millis().unwrap_or(0);
+ stats
+ .latest_kafka_ts
+ .entry((topic.clone(), partition))
+ .and_modify(|t| {
+ if kafka_ts > *t {
+ *t = kafka_ts;
+ }
+ })
+ .or_insert(kafka_ts);
+
+ let payload_bytes = borrowed_message.payload().map(|v| v.len()).unwrap_or(0);
+ stats.total_bytes += payload_bytes;
+
let mut headers = HashMap::new();
if let Some(rdkafka_headers) = borrowed_message.headers() {
use rdkafka::message::Headers;
@@ -212,11 +338,25 @@ impl IngestionConsumer {
}
}
+ if let Some(capture_ms) = headers.get("now").and_then(|v| parse_now_ms(v)) {
+ let lag_ms = (batch_start_ms - capture_ms).max(0);
+ stats
+ .max_lag_ms
+ .entry((topic.clone(), partition))
+ .and_modify(|l| {
+ if lag_ms > *l {
+ *l = lag_ms;
+ }
+ })
+ .or_insert(lag_ms);
+ stats.message_lags_ms.push((partition, lag_ms));
+ }
+
let serialized = SerializedKafkaMessage {
topic,
partition,
offset,
- timestamp: borrowed_message.timestamp().to_millis().unwrap_or(0),
+ timestamp: kafka_ts,
key: borrowed_message
.key()
.and_then(|k| std::str::from_utf8(k).ok())
@@ -240,7 +380,11 @@ impl IngestionConsumer {
}
}
- Ok((messages, offsets))
+ Ok(CollectedBatch {
+ messages,
+ offsets,
+ stats,
+ })
}
/// Commit the max offset for each topic-partition.
@@ -270,3 +414,18 @@ fn make_batch_id() -> String {
let rand: u32 = rand::random();
format!("{ts:x}-{rand:08x}")
}
+
+fn current_time_ms() -> i64 {
+ std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)
+ .unwrap_or_default()
+ .as_millis() as i64
+}
+
+/// Parse an ISO 8601 / RFC 3339 timestamp string into milliseconds since epoch.
+/// Returns `None` if the string is missing or unparseable.
+fn parse_now_ms(value: &str) -> Option<i64> {
+ chrono::DateTime::parse_from_rfc3339(value)
+ .ok()
+ .map(|dt| dt.timestamp_millis())
+}
diff --git a/rust/ingestion-consumer/src/dispatcher.rs b/rust/ingestion-consumer/src/dispatcher.rs
index b034cd41ed48..b7ba82fdc884 100644
--- a/rust/ingestion-consumer/src/dispatcher.rs
+++ b/rust/ingestion-consumer/src/dispatcher.rs
@@ -307,6 +307,12 @@ impl Dispatcher {
gauge!("ingestion_consumer_dispatcher_pins_total").set(table.pins.len() as f64);
}
+
+ /// Record the outcome of a send attempt for passive health tracking.
+ /// Delegates to the underlying WorkerRegistry.
+ pub fn record_send_outcome(&self, worker_idx: usize, is_error: bool) {
+ self.registry.record_outcome(worker_idx, is_error);
+ }
}
struct GroupedMessages {
diff --git a/rust/ingestion-consumer/src/lib.rs b/rust/ingestion-consumer/src/lib.rs
index af4d1b11bf1d..d68e268faed2 100644
--- a/rust/ingestion-consumer/src/lib.rs
+++ b/rust/ingestion-consumer/src/lib.rs
@@ -2,7 +2,6 @@ pub mod config;
pub mod consumer;
pub mod dispatcher;
pub mod kafka_config;
-pub mod router;
pub mod transport;
pub mod types;
pub mod worker_registry;
diff --git a/rust/ingestion-consumer/src/main.rs b/rust/ingestion-consumer/src/main.rs
index eb376a2a99c5..c1cf88ecd173 100644
--- a/rust/ingestion-consumer/src/main.rs
+++ b/rust/ingestion-consumer/src/main.rs
@@ -8,8 +8,9 @@ use axum::Router;
use envconfig::Envconfig;
use futures::future::ready;
use lifecycle::{ComponentOptions, Manager};
-use metrics_exporter_prometheus::PrometheusBuilder;
+use metrics_exporter_prometheus::{Matcher, PrometheusBuilder};
use tokio::net::TcpListener;
+use tokio_util::sync::CancellationToken;
use tracing::info;
use tracing_subscriber::fmt;
use tracing_subscriber::layer::SubscriberExt;
@@ -18,7 +19,9 @@ use tracing_subscriber::{EnvFilter, Layer};
use ingestion_consumer::config::Config;
use ingestion_consumer::consumer::IngestionConsumer;
+use ingestion_consumer::dispatcher::Dispatcher;
use ingestion_consumer::transport::HttpTransport;
+use ingestion_consumer::worker_registry::{WorkerRegistry, WorkerRegistryConfig};
common_alloc::used!();
@@ -86,10 +89,34 @@ async fn async_main(config: Config) -> Result<()> {
let readiness = manager.readiness_handler();
let liveness = manager.liveness_handler();
- // Install Prometheus recorder
+ // Install Prometheus recorder with custom histogram buckets matching the
+ // Node.js ingestion consumer, so existing dashboards and alerts work during switchover.
let recorder_handle = if config.export_prometheus {
Some(
PrometheusBuilder::new()
+ .set_buckets_for_metric(
+ Matcher::Full("ingestionLagHistogram".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")
+ .set_buckets_for_metric(
+ Matcher::Full("consumerBatchSize".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")
+ .set_buckets_for_metric(
+ Matcher::Full("consumerBatchSizeKb".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")
.install_recorder()
.expect("failed to install Prometheus recorder"),
)
@@ -99,13 +126,32 @@ async fn async_main(config: Config) -> Result<()> {
let guard = manager.monitor_background();
- // Spawn the consumer task
+ let worker_urls = config.worker_urls();
+
+ // Build the worker health registry and start background probe tasks.
+ let registry_config = WorkerRegistryConfig {
+ probe_interval: Duration::from_millis(config.worker_probe_interval_ms),
+ dead_declaration: Duration::from_millis(config.worker_dead_declaration_ms),
+ passive_window: Duration::from_millis(config.worker_passive_window_ms),
+ passive_error_threshold: config.worker_passive_error_threshold,
+ passive_min_samples: config.worker_passive_min_samples,
+ degraded_hold: Duration::from_millis(config.worker_degraded_hold_ms),
+ min_state_duration: Duration::from_millis(config.worker_min_state_duration_ms),
+ probe_failure_threshold: config.worker_probe_failure_threshold,
+ };
+ let registry = Arc::new(WorkerRegistry::new(&worker_urls, registry_config));
+
+ // Probe tasks run until the consumer shuts down.
+ let probe_token = CancellationToken::new();
+ Arc::clone(&registry).start_probing(probe_token.clone());
+
+ let dispatcher = Arc::new(Dispatcher::new(Arc::clone(&registry)));
+
let api_secret = if config.internal_api_secret.is_empty() {
None
} else {
Some(config.internal_api_secret.clone())
};
- let worker_urls = config.worker_urls();
let transport = Arc::new(HttpTransport::new(
Duration::from_millis(config.http_timeout_ms),
config.max_retries,
@@ -114,11 +160,13 @@ async fn async_main(config: Config) -> Result<()> {
config.ingestion_worker_concurrent_batches,
));
- let consumer = IngestionConsumer::new(&config, transport, consumer_handle)
+ let consumer = IngestionConsumer::new(&config, dispatcher, transport, consumer_handle)
.context("Failed to create Kafka consumer")?;
tokio::spawn(async move {
consumer.process().await;
+ // Cancel probe tasks once the consumer loop exits.
+ probe_token.cancel();
});
// Build and serve the health/metrics HTTP server
diff --git a/rust/ingestion-consumer/src/router.rs b/rust/ingestion-consumer/src/router.rs
deleted file mode 100644
index 440e5586900a..000000000000
--- a/rust/ingestion-consumer/src/router.rs
+++ /dev/null
@@ -1,157 +0,0 @@
-use std::collections::HashMap;
-use std::hash::{Hash, Hasher};
-
-use metrics::{counter, histogram};
-
-use crate::types::SerializedKafkaMessage;
-
-/// Routes messages to workers using hash-based assignment on `token:distinct_id`.
-///
-/// All messages for the same distinct_id go to the same worker within a batch,
-/// preserving person batching semantics. Stage 4 replaces this with least-loaded
-/// assignment for better load distribution on skewed workloads.
-pub struct MessageRouter {
- worker_count: usize,
-}
-
-impl MessageRouter {
- pub fn new(worker_count: usize) -> Self {
- assert!(worker_count > 0, "worker_count must be > 0");
- Self { worker_count }
- }
-
- /// Extract the routing key from a message's headers (`token:distinct_id`).
- fn routing_key(message: &SerializedKafkaMessage) -> String {
- let token = message
- .headers
- .get("token")
- .map(|s| s.as_str())
- .unwrap_or("");
- let distinct_id = message
- .headers
- .get("distinct_id")
- .map(|s| s.as_str())
- .unwrap_or("");
- format!("{token}:{distinct_id}")
- }
-
- /// Assign a routing key to a worker index.
- fn assign(&self, key: &str) -> usize {
- let mut hasher = std::collections::hash_map::DefaultHasher::new();
- key.hash(&mut hasher);
- (hasher.finish() as usize) % self.worker_count
- }
-
- /// Route a batch of messages, grouping them by assigned worker index.
- pub fn route_batch(
- &self,
- messages: Vec<SerializedKafkaMessage>,
- ) -> HashMap<usize, Vec<SerializedKafkaMessage>> {
- let mut groups: HashMap<usize, Vec<SerializedKafkaMessage>> = HashMap::new();
- let mut unique_keys: std::collections::HashSet<String> = std::collections::HashSet::new();
- let mut missing_headers: u64 = 0;
-
- for message in messages {
- let key = Self::routing_key(&message);
- if key == ":" {
- missing_headers += 1;
- }
- unique_keys.insert(key.clone());
- let worker_idx = self.assign(&key);
- groups.entry(worker_idx).or_default().push(message);
- }
-
- // Record per-worker message distribution
- for (worker_idx, msgs) in &groups {
- counter!("ingestion_consumer_messages_routed_total", "worker" => worker_idx.to_string())
- .increment(msgs.len() as u64);
- }
-
- histogram!("ingestion_consumer_distinct_ids_per_batch").record(unique_keys.len() as f64);
-
- if missing_headers > 0 {
- counter!("ingestion_consumer_missing_routing_headers_total").increment(missing_headers);
- }
-
- groups
- }
-}
-
-#[cfg(test)]
-mod tests {
- use super::*;
-
- fn make_message(token: &str, distinct_id: &str) -> SerializedKafkaMessage {
- let mut headers = HashMap::new();
- headers.insert("token".to_string(), token.to_string());
- headers.insert("distinct_id".to_string(), distinct_id.to_string());
- SerializedKafkaMessage {
- topic: "test".to_string(),
- partition: 0,
- offset: 0,
- timestamp: 0,
- key: None,
- value: None,
- headers,
- }
- }
-
- #[test]
- fn same_distinct_id_routes_to_same_worker() {
- let router = MessageRouter::new(4);
- let m1 = make_message("tok", "user-1");
- let m2 = make_message("tok", "user-1");
-
- let key1 = MessageRouter::routing_key(&m1);
- let key2 = MessageRouter::routing_key(&m2);
- assert_eq!(router.assign(&key1), router.assign(&key2));
- }
-
- #[test]
- fn route_batch_groups_by_worker() {
- let router = MessageRouter::new(4);
- let messages = vec![
- make_message("tok", "user-1"),
- make_message("tok", "user-2"),
- make_message("tok", "user-1"),
- ];
-
- let groups = router.route_batch(messages);
-
- let total: usize = groups.values().map(|v| v.len()).sum();
- assert_eq!(total, 3);
-
- // user-1 messages should be in the same group
- let user1_worker = router.assign("tok:user-1");
- let user1_msgs = &groups[&user1_worker];
- assert!(user1_msgs.len() >= 2);
- }
-
- #[test]
- fn empty_headers_produce_consistent_routing() {
- let router = MessageRouter::new(4);
- let m1 = SerializedKafkaMessage {
- topic: "test".to_string(),
- partition: 0,
- offset: 0,
- timestamp: 0,
- key: None,
- value: None,
- headers: HashMap::new(),
- };
- let m2 = SerializedKafkaMessage {
- topic: "test".to_string(),
- partition: 0,
- offset: 1,
- timestamp: 0,
- key: None,
- value: None,
- headers: HashMap::new(),
- };
-
- let key1 = MessageRouter::routing_key(&m1);
- let key2 = MessageRouter::routing_key(&m2);
- assert_eq!(key1, ":");
- assert_eq!(router.assign(&key1), router.assign(&key2));
- }
-}
diff --git a/rust/ingestion-consumer/tests/e2e_integration_test.rs b/rust/ingestion-consumer/tests/e2e_integration_test.rs
new file mode 100644
index 000000000000..94dd948ba964
--- /dev/null
+++ b/rust/ingestion-consumer/tests/e2e_integration_test.rs
@@ -0,0 +1,408 @@
+//! End-to-end integration tests for the ingestion consumer pipeline.
+//!
+//! Requires Kafka on localhost:9092 (available via docker-compose).
+//! Each test creates a uniquely-named topic to avoid cross-test interference.
+
+use std::sync::atomic::{AtomicBool, Ordering};
+use std::sync::{Arc, Mutex};
+use std::time::Duration;
+
+use axum::extract::Json as AxumJson;
+use axum::routing::{get, post};
+use axum::Router;
+use lifecycle::{ComponentOptions, Manager};
+use rdkafka::admin::{AdminClient, AdminOptions, NewTopic, TopicReplication};
+use rdkafka::client::DefaultClientContext;
+use rdkafka::config::ClientConfig;
+use rdkafka::consumer::{Consumer, StreamConsumer};
+use rdkafka::message::{Header, OwnedHeaders};
+use rdkafka::producer::{FutureProducer, FutureRecord};
+use rdkafka::util::Timeout;
+use tokio::net::TcpListener;
+use tokio_util::sync::CancellationToken;
+use uuid::Uuid;
+
+use ingestion_consumer::consumer::{IngestionConsumer, IngestionConsumerOptions};
+use ingestion_consumer::dispatcher::Dispatcher;
+use ingestion_consumer::transport::HttpTransport;
+use ingestion_consumer::types::{IngestBatchRequest, IngestBatchResponse};
+use ingestion_consumer::worker_registry::{WorkerRegistry, WorkerRegistryConfig};
+
+const KAFKA_BROKERS: &str = "localhost:9092";
+
+// ── Kafka helpers ──────────────────────────────────────────────────────────
+
+async fn create_topic(name: &str, partitions: i32) {
+ let admin: AdminClient<DefaultClientContext> = ClientConfig::new()
+ .set("bootstrap.servers", KAFKA_BROKERS)
+ .create()
+ .expect("admin client");
+ let topic = NewTopic::new(name, partitions, TopicReplication::Fixed(1));
+ let opts = AdminOptions::new().operation_timeout(Some(Duration::from_secs(10)));
+ for result in admin.create_topics(&[topic], &opts).await.unwrap() {
+ match result {
+ Ok(_) | Err((_, rdkafka::types::RDKafkaErrorCode::TopicAlreadyExists)) => {}
+ Err((name, err)) => panic!("failed to create topic {name}: {err:?}"),
+ }
+ }
+ tokio::time::sleep(Duration::from_millis(300)).await;
+}
+
+fn make_producer() -> FutureProducer {
+ ClientConfig::new()
+ .set("bootstrap.servers", KAFKA_BROKERS)
+ .set("message.timeout.ms", "5000")
+ .create()
+ .expect("producer")
+}
+
+async fn produce(
+ producer: &FutureProducer,
+ topic: &str,
+ partition: i32,
+ token: &str,
+ distinct_id: &str,
+ seq: usize,
+) {
+ let value = format!(r#"{{"seq":{seq}}}"#);
+ let key = format!("{token}:{distinct_id}:{seq}");
+ let headers = OwnedHeaders::new()
+ .insert(Header {
+ key: "token",
+ value: Some(token),
+ })
+ .insert(Header {
+ key: "distinct_id",
+ value: Some(distinct_id),
+ });
+
+ producer
+ .send(
+ FutureRecord::to(topic)
+ .key(&key)
+ .payload(&value)
+ .partition(partition)
+ .headers(headers),
+ Timeout::After(Duration::from_secs(5)),
+ )
+ .await
+ .expect("produce failed");
+}
+
+// ── Fake worker ────────────────────────────────────────────────────────────
+
+struct FakeWorker {
+ pub url: String,
+ /// (distinct_id, seq) pairs in arrival order.
+ pub received: Arc<Mutex<Vec<(String, usize)>>>,
+ pub healthy: Arc<AtomicBool>,
+ _task: tokio::task::JoinHandle<()>,
+}
+
+impl FakeWorker {
+ async fn start() -> Self {
+ let received: Arc<Mutex<Vec<(String, usize)>>> = Arc::new(Mutex::new(Vec::new()));
+ let healthy = Arc::new(AtomicBool::new(true));
+
+ let app = Router::new()
+ .route(
+ "/_ready",
+ get({
+ let h = Arc::clone(&healthy);
+ move || {
+ let h = h.clone();
+ async move {
+ if h.load(Ordering::Relaxed) {
+ axum::http::StatusCode::OK
+ } else {
+ axum::http::StatusCode::SERVICE_UNAVAILABLE
+ }
+ }
+ }
+ }),
+ )
+ .route(
+ "/ingest",
+ post({
+ let recv = Arc::clone(&received);
+ let h = Arc::clone(&healthy);
+ move |AxumJson(req): AxumJson<IngestBatchRequest>| {
+ let recv = recv.clone();
+ let h = h.clone();
+ async move {
+ if !h.load(Ordering::Relaxed) {
+ return (
+ axum::http::StatusCode::INTERNAL_SERVER_ERROR,
+ AxumJson(IngestBatchResponse {
+ batch_id: req.batch_id,
+ status: "error".to_string(),
+ accepted: 0,
+ error: Some("worker unhealthy".to_string()),
+ }),
+ );
+ }
+ let accepted = req.messages.len() as u32;
+ let mut g = recv.lock().unwrap();
+ for msg in &req.messages {
+ let did =
+ msg.headers.get("distinct_id").cloned().unwrap_or_default();
+ let seq = msg
+ .value
+ .as_deref()
+ .and_then(|v| serde_json::from_str::<serde_json::Value>(v).ok())
+ .and_then(|v| v["seq"].as_u64())
+ .unwrap_or(0)
+ as usize;
+ g.push((did, seq));
+ }
+ (
+ axum::http::StatusCode::OK,
+ AxumJson(IngestBatchResponse {
+ batch_id: req.batch_id,
+ status: "ok".to_string(),
+ accepted,
+ error: None,
+ }),
+ )
+ }
+ }
+ }),
+ );
+
+ let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let addr = listener.local_addr().unwrap();
+ let url = format!("http://127.0.0.1:{}", addr.port());
+ let task = tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
+
+ Self {
+ url,
+ received,
+ healthy,
+ _task: task,
+ }
+ }
+
+ fn count(&self) -> usize {
+ self.received.lock().unwrap().len()
+ }
+
+ fn seqs_for(&self, distinct_id: &str) -> Vec<usize> {
+ self.received
+ .lock()
+ .unwrap()
+ .iter()
+ .filter(|(did, _)| did == distinct_id)
+ .map(|(_, seq)| *seq)
+ .collect()
+ }
+}
+
+// ── Test harness ───────────────────────────────────────────────────────────
+
+struct Harness {
+ pub workers: Vec<FakeWorker>,
+ pub shutdown: CancellationToken,
+ _task: tokio::task::JoinHandle<()>,
+ _probe_token: CancellationToken,
+}
+
+impl Harness {
+ async fn start(
+ topic: &str,
+ partitions: i32,
+ worker_count: usize,
+ registry_config: WorkerRegistryConfig,
+ ) -> Self {
+ create_topic(topic, partitions).await;
+
+ let mut workers = Vec::new();
+ for _ in 0..worker_count {
+ workers.push(FakeWorker::start().await);
+ }
+ let worker_urls: Vec<String> = workers.iter().map(|w| w.url.clone()).collect();
+
+ let registry = Arc::new(WorkerRegistry::new(&worker_urls, registry_config));
+ let probe_token = CancellationToken::new();
+ Arc::clone(&registry).start_probing(probe_token.clone());
+
+ let dispatcher = Arc::new(Dispatcher::new(Arc::clone(&registry)));
+ let transport = Arc::new(HttpTransport::new(
+ Duration::from_secs(5),
+ 0, // no retries — errors surface immediately for health tracking
+ None,
+ &worker_urls,
+ 1,
+ ));
+
+ let mut manager = Manager::builder("e2e-test")
+ .with_trap_signals(false)
+ .build();
+ let handle = manager.register("consumer", ComponentOptions::new());
+ let shutdown = handle.shutdown_token();
+
+ let kafka_consumer: StreamConsumer = ClientConfig::new()
+ .set("bootstrap.servers", KAFKA_BROKERS)
+ .set("group.id", format!("e2e-{}", Uuid::new_v4()))
+ .set("auto.offset.reset", "earliest")
+ .set("enable.auto.commit", "false")
+ .set("enable.auto.offset.store", "false")
+ .set("socket.timeout.ms", "5000")
+ .create()
+ .expect("kafka consumer");
+ kafka_consumer.subscribe(&[topic]).expect("subscribe");
+
+ let consumer = IngestionConsumer::from_parts(
+ kafka_consumer,
+ dispatcher,
+ transport,
+ worker_urls,
+ IngestionConsumerOptions {
+ batch_size: 50,
+ batch_timeout: Duration::from_millis(100),
+ group_id: "e2e-test".to_string(),
+ },
+ handle,
+ );
+
+ let task = tokio::spawn(async move { consumer.process().await });
+
+ // Give the consumer time to connect and enter the poll loop.
+ tokio::time::sleep(Duration::from_millis(300)).await;
+
+ Self {
+ workers,
+ shutdown,
+ _task: task,
+ _probe_token: probe_token,
+ }
+ }
+
+ async fn wait_for(&self, total: usize, timeout: Duration) {
+ let deadline = tokio::time::Instant::now() + timeout;
+ loop {
+ let got: usize = self.workers.iter().map(|w| w.count()).sum();
+ if got >= total {
+ return;
+ }
+ assert!(
+ tokio::time::Instant::now() < deadline,
+ "timed out waiting for {total} messages (got {got})"
+ );
+ tokio::time::sleep(Duration::from_millis(25)).await;
+ }
+ }
+
+ async fn stop(self) {
+ self.shutdown.cancel();
+ let _ = tokio::time::timeout(Duration::from_secs(3), self._task).await;
+ }
+}
+
+fn fast_registry_config() -> WorkerRegistryConfig {
+ WorkerRegistryConfig {
+ probe_interval: Duration::from_millis(50),
+ dead_declaration: Duration::from_millis(200),
+ passive_window: Duration::from_secs(30),
+ passive_error_threshold: 0.5,
+ passive_min_samples: 1,
+ degraded_hold: Duration::from_millis(100),
+ min_state_duration: Duration::ZERO,
+ probe_failure_threshold: 2,
+ }
+}
+
+// ── Tests ──────────────────────────────────────────────────────────────────
+
+/// Kafka partition order is preserved per distinct_id on each worker.
+///
+/// With concurrent_batches=1 (sequential processing), pins are evicted after
+/// each batch resolves, so the same distinct_id can be assigned to different
+/// workers across batches. The guarantee is narrower: wherever a distinct_id's
+/// messages land, they arrive in Kafka sequence order on that worker.
+///
+/// Cross-batch stickiness (all distinct_id events always to the same pod) is
+/// the responsibility of the concurrent-batches layer: when concurrent_batches>1,
+/// the Dispatcher's ref-counted pins keep the assignment alive across overlapping
+/// in-flight batches. That invariant is tested in the concurrent-batches suite.
+#[tokio::test]
+async fn messages_per_distinct_id_arrive_in_order() {
+ let topic = format!("e2e-ordering-{}", Uuid::new_v4());
+ let harness = Harness::start(&topic, 3, 2, fast_registry_config()).await;
+
+ let producer = make_producer();
+ for seq in 0..8usize {
+ produce(&producer, &topic, 0, "tok", "user-1", seq).await;
+ produce(&producer, &topic, 1, "tok", "user-2", seq).await;
+ produce(&producer, &topic, 2, "tok", "user-3", seq).await;
+ }
+
+ harness.wait_for(24, Duration::from_secs(15)).await;
+
+ // All messages must arrive.
+ let total: usize = harness.workers.iter().map(|w| w.count()).sum();
+ assert_eq!(total, 24, "expected 24 messages total, got {total}");
+
+ // On whichever worker(s) a distinct_id's messages land, they must be in
+ // ascending sequence order — no reordering within a single worker's delivery.
+ for worker in &harness.workers {
+ for user in ["user-1", "user-2", "user-3"] {
+ let seqs = worker.seqs_for(user);
+ assert!(
+ seqs.windows(2).all(|w| w[0] < w[1]),
+ "{user} arrived out of order on a worker: {seqs:?}"
+ );
+ }
+ }
+
+ harness.stop().await;
+}
+
+/// When a worker becomes unhealthy, its sticky pins are dropped and subsequent
+/// messages for the same distinct_id are rerouted to a healthy worker.
+#[tokio::test]
+async fn failing_worker_triggers_rerouting() {
+ let topic = format!("e2e-failover-{}", Uuid::new_v4());
+ let harness = Harness::start(&topic, 2, 2, fast_registry_config()).await;
+
+ let producer = make_producer();
+
+ // Batch 1: 4 messages for user-1 (partition 0) and user-2 (partition 1).
+ for seq in 0..4usize {
+ produce(&producer, &topic, 0, "tok", "user-1", seq).await;
+ produce(&producer, &topic, 1, "tok", "user-2", seq).await;
+ }
+ harness.wait_for(8, Duration::from_secs(10)).await;
+
+ // Identify which worker owns user-1 and take it down.
+ let dead_idx = if !harness.workers[0].seqs_for("user-1").is_empty() {
+ 0
+ } else {
+ 1
+ };
+ let live_idx = 1 - dead_idx;
+
+ harness.workers[dead_idx]
+ .healthy
+ .store(false, Ordering::Relaxed);
+
+ // Wait for probe failures → Unhealthy → dead declaration.
+ // probe_interval*probe_failure_threshold + dead_declaration ≈ 300ms; use 600ms to be safe.
+ tokio::time::sleep(Duration::from_millis(600)).await;
+
+ // Batch 2: 4 more messages for user-1. The pin was dropped; should route to the live worker.
+ for seq in 4..8usize {
+ produce(&producer, &topic, 0, "tok", "user-1", seq).await;
+ }
+ harness.wait_for(12, Duration::from_secs(10)).await;
+
+ // Batch-2 messages (seq 4–7) must all be on the live worker and in order.
+ let live_seqs = harness.workers[live_idx].seqs_for("user-1");
+ let batch2_seqs: Vec<usize> = live_seqs.iter().copied().filter(|&s| s >= 4).collect();
+ assert_eq!(
+ batch2_seqs,
+ vec![4, 5, 6, 7],
+ "batch-2 messages for user-1 missing or out-of-order on live worker: {live_seqs:?}"
+ );
+
+ harness.stop().await;
+}
diff --git a/rust/ingestion-consumer/tests/transport_integration_test.rs b/rust/ingestion-consumer/tests/transport_integration_test.rs
index ebb7e6952c50..b1a475de86a4 100644
--- a/rust/ingestion-consumer/tests/transport_integration_test.rs
+++ b/rust/ingestion-consumer/tests/transport_integration_test.rs
@@ -10,9 +10,10 @@ use axum::Router;
use tokio::net::TcpListener;
use tokio::time::sleep;
-use ingestion_consumer::router::MessageRouter;
+use ingestion_consumer::dispatcher::Dispatcher;
use ingestion_consumer::transport::{HttpTransport, TransportError};
use ingestion_consumer::types::{IngestBatchRequest, IngestBatchResponse, SerializedKafkaMessage};
+use ingestion_consumer::worker_registry::{WorkerRegistry, WorkerRegistryConfig};
fn make_message(
token: &str,
@@ -369,7 +370,7 @@ async fn transport_parallelizes_across_different_workers() {
}
#[tokio::test]
-async fn router_and_transport_end_to_end() {
+async fn dispatcher_and_transport_end_to_end() {
// Start 2 mock workers
let received_1 = Arc::new(Mutex::new(Vec::new()));
let received_2 = Arc::new(Mutex::new(Vec::new()));
@@ -377,7 +378,20 @@ async fn router_and_transport_end_to_end() {
let (url_2, _h2) = start_mock_worker(received_2.clone()).await;
let worker_urls = [url_1.clone(), url_2.clone()];
- let router = MessageRouter::new(worker_urls.len());
+ let registry = Arc::new(WorkerRegistry::new(
+ &worker_urls,
+ WorkerRegistryConfig {
+ probe_interval: Duration::from_secs(60),
+ dead_declaration: Duration::from_secs(60),
+ passive_window: Duration::from_secs(30),
+ passive_error_threshold: 0.5,
+ passive_min_samples: 1000,
+ degraded_hold: Duration::from_secs(10),
+ min_state_duration: Duration::ZERO,
+ probe_failure_threshold: 2,
+ },
+ ));
+ let dispatcher = Arc::new(Dispatcher::new(Arc::clone(&registry)));
let transport = Arc::new(HttpTransport::new(
Duration::from_secs(5),
0,
@@ -386,7 +400,7 @@ async fn router_and_transport_end_to_end() {
1,
));
- // Create messages for multiple distinct_ids
+ // Create messages for multiple distinct_ids — user-1 appears twice
let messages = vec![
make_message("tok", "user-1", 0, r#"{"event":"a"}"#),
make_message("tok", "user-2", 1, r#"{"event":"b"}"#),
@@ -394,16 +408,23 @@ async fn router_and_transport_end_to_end() {
make_message("tok", "user-3", 3, r#"{"event":"d"}"#),
];
- // Route
- let groups = router.route_batch(messages);
+ let sub_batches = dispatcher.assign(messages);
// Scatter to workers
let mut handles = Vec::new();
- for (worker_idx, sub_batch) in groups {
+ for sub_batch in sub_batches {
let t = transport.clone();
- let url = worker_urls[worker_idx].clone();
+ let url = worker_urls[sub_batch.worker_idx].clone();
+ let routing_keys = sub_batch.routing_keys.clone();
+ let worker_idx = sub_batch.worker_idx;
+ let d = Arc::clone(&dispatcher);
handles.push(tokio::spawn(async move {
- t.send_batch(&url, "batch-e2e", sub_batch).await.unwrap()
+ let result = t
+ .send_batch(&url, "batch-e2e", sub_batch.messages)
+ .await
+ .unwrap();
+ d.on_sub_batch_resolved(worker_idx, &routing_keys);
+ result
}));
}
@@ -412,10 +433,9 @@ async fn router_and_transport_end_to_end() {
for h in handles {
total_accepted += h.await.unwrap();
}
-
assert_eq!(total_accepted, 4);
- // Verify all messages for the same distinct_id landed on the same worker
+ // user-1 messages (offsets 0 and 2) must have landed on the same worker
let batches_1 = received_1.lock().unwrap();
let batches_2 = received_2.lock().unwrap();
@@ -426,7 +446,6 @@ async fn router_and_transport_end_to_end() {
.collect();
assert_eq!(all_messages.len(), 4);
- // user-1 messages (offsets 0, 2) must be on the same worker
let user1_workers: Vec<usize> = all_messages
.iter()
.filter(|m| m.headers.get("distinct_id").map(|s| s.as_str()) == Some("user-1"))