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): add health-aware Dispatcher with sticky pin… (#60618)

José Sequeira6e63a3418cb3
diff --git a/rust/ingestion-consumer/src/dispatcher.rs b/rust/ingestion-consumer/src/dispatcher.rs
new file mode 100644
index 000000000000..b034cd41ed48
--- /dev/null
+++ b/rust/ingestion-consumer/src/dispatcher.rs
@@ -0,0 +1,716 @@
+use std::collections::HashMap;
+use std::sync::{Arc, Mutex};
+
+use metrics::{counter, gauge, histogram};
+
+use crate::types::SerializedKafkaMessage;
+use crate::worker_registry::{WorkerRegistry, WorkerState};
+
+/// A slice of a batch assigned to one worker, carrying the messages and the
+/// routing keys of all distinct_ids included. Routing keys are needed to
+/// decrement pin ref-counts when the sub-batch resolves.
+pub struct SubBatch {
+ pub worker_idx: usize,
+ pub messages: Vec<SerializedKafkaMessage>,
+ /// Unique routing keys contained in this sub-batch. Pass back to
+ /// `Dispatcher::on_sub_batch_resolved` on ACK or DLQ.
+ pub routing_keys: Vec<String>,
+}
+
+/// Sticky pin for one routing key. Tracks which worker owns the key and how
+/// many in-flight batches currently reference it. The pin is evicted when
+/// ref_count reaches 0.
+struct Pin {
+ worker_idx: usize,
+ ref_count: u32,
+}
+
+/// Mutable assignment state, held behind a single Mutex.
+struct PinTable {
+ /// `"{token}:{distinct_id}"` → sticky assignment.
+ pins: HashMap<String, Pin>,
+ /// Number of in-flight sub-batches per worker. Used for bin-packing: new
+ /// key-groups are assigned to whichever healthy worker has the lowest load.
+ in_flight: Vec<usize>,
+}
+
+impl PinTable {
+ fn new(worker_count: usize) -> Self {
+ Self {
+ pins: HashMap::new(),
+ in_flight: vec![0; worker_count],
+ }
+ }
+
+ /// Drop all pins targeting dead workers. Returns the count of evictions.
+ fn drop_dead_pins(&mut self, registry: &WorkerRegistry) -> usize {
+ let before = self.pins.len();
+ self.pins.retain(|_, pin| !registry.is_dead(pin.worker_idx));
+ before - self.pins.len()
+ }
+
+ /// Pick the healthy/degraded worker with the lowest in-flight load.
+ /// Returns None when no healthy workers exist.
+ fn least_loaded_healthy(
+ &self,
+ registry: &WorkerRegistry,
+ provisional: &[usize],
+ ) -> Option<usize> {
+ (0..self.in_flight.len())
+ .filter(|&idx| {
+ matches!(
+ registry.state(idx),
+ WorkerState::Healthy | WorkerState::Degraded
+ )
+ })
+ .min_by_key(|&idx| self.in_flight[idx] + provisional[idx])
+ }
+}
+
+struct MessageGroup {
+ routing_key: String,
+ messages: Vec<SerializedKafkaMessage>,
+}
+
+struct WorkerSubBatchBuilder {
+ messages: Vec<SerializedKafkaMessage>,
+ routing_keys: Vec<String>,
+}
+
+impl WorkerSubBatchBuilder {
+ fn is_empty(&self) -> bool {
+ self.messages.is_empty()
+ }
+
+ fn message_count(&self) -> usize {
+ self.messages.len()
+ }
+}
+
+#[derive(Default)]
+struct WorkerAssignments {
+ by_worker: HashMap<usize, WorkerSubBatchBuilder>,
+ provisional_in_flight: Vec<usize>,
+}
+
+impl WorkerAssignments {
+ fn new(worker_count: usize) -> Self {
+ Self {
+ by_worker: HashMap::new(),
+ provisional_in_flight: vec![0; worker_count],
+ }
+ }
+
+ fn provisional_in_flight(&self) -> &[usize] {
+ &self.provisional_in_flight
+ }
+
+ fn add_group(&mut self, worker_idx: usize, group: MessageGroup) {
+ let builder = self
+ .by_worker
+ .entry(worker_idx)
+ .or_insert_with(|| WorkerSubBatchBuilder {
+ messages: Vec::new(),
+ routing_keys: Vec::new(),
+ });
+
+ if builder.is_empty() {
+ self.provisional_in_flight[worker_idx] =
+ self.provisional_in_flight[worker_idx].saturating_add(1);
+ }
+
+ builder.messages.extend(group.messages);
+ builder.routing_keys.push(group.routing_key);
+ }
+
+ fn routed_counts(&self) -> impl Iterator<Item = (usize, usize)> + '_ {
+ self.by_worker
+ .iter()
+ .filter(|(_, builder)| !builder.is_empty())
+ .map(|(&worker_idx, builder)| (worker_idx, builder.message_count()))
+ }
+
+ fn into_sub_batches(self) -> Vec<SubBatch> {
+ self.by_worker
+ .into_iter()
+ .filter(|(_, builder)| !builder.is_empty())
+ .map(|(worker_idx, builder)| SubBatch {
+ worker_idx,
+ messages: builder.messages,
+ routing_keys: builder.routing_keys,
+ })
+ .collect()
+ }
+}
+
+/// Routes batches to Node.js workers with sticky per-distinct_id assignment.
+///
+/// **Assignment** (`assign`): groups messages by `token:distinct_id`, honors
+/// existing pins for live workers, bin-packs new keys onto the least-loaded
+/// healthy worker, and returns one `SubBatch` per worker.
+///
+/// **Stickiness**: a routing key stays on the same worker across batches
+/// (ref-counted pin). Pins are dropped when a worker is declared dead or
+/// when the last referencing batch resolves.
+///
+/// **Recovery**: `on_sub_batch_resolved` decrements ref-counts and the
+/// per-worker in-flight counter. Zero-count pins are evicted so the key
+/// is re-pinned on its next arrival.
+pub struct Dispatcher {
+ pin_table: Mutex<PinTable>,
+ registry: Arc<WorkerRegistry>,
+}
+
+impl Dispatcher {
+ pub fn new(registry: Arc<WorkerRegistry>) -> Self {
+ let worker_count = registry.worker_count();
+ Self {
+ pin_table: Mutex::new(PinTable::new(worker_count)),
+ registry,
+ }
+ }
+
+ /// Assign a batch of messages to workers.
+ ///
+ /// Steps:
+ /// 1. Drop pins for workers that are now dead.
+ /// 2. Group messages by routing key.
+ /// 3. Honor existing pins for live workers; collect unassigned groups.
+ /// 4. Largest-first bin-pack unassigned groups onto healthy/degraded
+ /// workers by current in-flight load.
+ /// 5. Increment in-flight counters and pin ref-counts.
+ /// 6. Return one `SubBatch` per worker.
+ ///
+ /// Returns an empty vec if all workers are dead/unhealthy.
+ pub fn assign(&self, messages: Vec<SerializedKafkaMessage>) -> Vec<SubBatch> {
+ let mut table = self.pin_table.lock().unwrap();
+
+ // Drop stale pins for dead workers before routing this batch.
+ let evictions = table.drop_dead_pins(&self.registry);
+ if evictions > 0 {
+ counter!("ingestion_consumer_dispatcher_pin_evictions_total", "reason" => "dead_worker")
+ .increment(evictions as u64);
+ }
+
+ let GroupedMessages {
+ groups: key_groups,
+ missing_header_count,
+ } = group_messages_by_routing_key(messages);
+
+ if missing_header_count > 0 {
+ counter!("ingestion_consumer_dispatcher_missing_routing_headers_total")
+ .increment(missing_header_count);
+ }
+
+ histogram!("ingestion_consumer_distinct_ids_per_batch").record(key_groups.len() as f64);
+
+ let worker_count = table.in_flight.len();
+ let mut assignments = WorkerAssignments::new(worker_count);
+
+ let mut unpinned_groups: Vec<MessageGroup> = Vec::new();
+
+ for group in key_groups {
+ match table.pins.get_mut(&group.routing_key) {
+ Some(pin) if !self.registry.is_dead(pin.worker_idx) => {
+ // Existing live pin — honor it.
+ pin.ref_count += 1;
+ let worker_idx = pin.worker_idx;
+ assignments.add_group(worker_idx, group);
+ }
+ _ => {
+ // No pin or pinned to a dead worker — drop stale entry and
+ // queue for bin-packing.
+ table.pins.remove(&group.routing_key);
+ unpinned_groups.push(group);
+ }
+ }
+ }
+
+ // Largest-first bin-pack: assign the biggest key-groups first so
+ // heavy hitters drive the load distribution.
+ unpinned_groups.sort_unstable_by(|a, b| b.messages.len().cmp(&a.messages.len()));
+
+ for group in unpinned_groups {
+ let Some(worker_idx) =
+ table.least_loaded_healthy(&self.registry, assignments.provisional_in_flight())
+ else {
+ // All workers unhealthy — this key cannot be assigned.
+ counter!("ingestion_consumer_dispatcher_unroutable_messages_total")
+ .increment(group.messages.len() as u64);
+ continue;
+ };
+
+ table.pins.insert(
+ group.routing_key.clone(),
+ Pin {
+ worker_idx,
+ ref_count: 1,
+ },
+ );
+
+ assignments.add_group(worker_idx, group);
+ }
+
+ // Increment in-flight counters for workers that got messages.
+ for (worker_idx, message_count) in assignments.routed_counts() {
+ table.in_flight[worker_idx] = table.in_flight[worker_idx].saturating_add(1);
+ counter!(
+ "ingestion_consumer_dispatcher_sub_batches_assigned_total",
+ "worker" => worker_idx.to_string(),
+ )
+ .increment(1);
+ counter!(
+ "ingestion_consumer_dispatcher_messages_routed_total",
+ "worker" => worker_idx.to_string(),
+ )
+ .increment(message_count as u64);
+ }
+
+ gauge!("ingestion_consumer_dispatcher_pins_total").set(table.pins.len() as f64);
+
+ assignments.into_sub_batches()
+ }
+
+ /// Call after a sub-batch resolves (ACK or DLQ). Decrements the worker's
+ /// in-flight counter and the ref-count for each key. Evicts zero-count
+ /// pins so the key is re-assigned on its next arrival.
+ pub fn on_sub_batch_resolved(&self, worker_idx: usize, routing_keys: &[String]) {
+ let mut table = self.pin_table.lock().unwrap();
+
+ table.in_flight[worker_idx] = table.in_flight[worker_idx].saturating_sub(1);
+
+ let mut evictions = 0usize;
+ for key in routing_keys {
+ if let Some(pin) = table.pins.get_mut(key) {
+ // Skip stale resolves: after a worker dies, `drop_dead_pins` evicts the
+ // old pin and `assign` may create a new one for a different worker using
+ // the same key. A DLQ resolve from the original dead sub-batch would
+ // otherwise corrupt the new pin's ref_count.
+ if pin.worker_idx != worker_idx {
+ continue;
+ }
+ pin.ref_count = pin.ref_count.saturating_sub(1);
+ if pin.ref_count == 0 {
+ table.pins.remove(key);
+ evictions += 1;
+ }
+ }
+ }
+
+ if evictions > 0 {
+ counter!(
+ "ingestion_consumer_dispatcher_pin_evictions_total",
+ "reason" => "resolved",
+ )
+ .increment(evictions as u64);
+ }
+
+ gauge!("ingestion_consumer_dispatcher_pins_total").set(table.pins.len() as f64);
+ }
+}
+
+struct GroupedMessages {
+ groups: Vec<MessageGroup>,
+ missing_header_count: u64,
+}
+
+fn group_messages_by_routing_key(messages: Vec<SerializedKafkaMessage>) -> GroupedMessages {
+ let mut grouped_messages: HashMap<String, Vec<SerializedKafkaMessage>> = HashMap::new();
+ let mut missing_header_count = 0u64;
+
+ for message in messages {
+ let routing_key = routing_key(&message).unwrap_or_else(|| {
+ missing_header_count += 1;
+ // Use a synthetic unique key so messages missing routing headers spread
+ // across workers instead of all pinning to one shared fallback key.
+ format!(":{}:{}", message.partition, message.offset)
+ });
+ grouped_messages
+ .entry(routing_key)
+ .or_default()
+ .push(message);
+ }
+
+ GroupedMessages {
+ groups: grouped_messages
+ .into_iter()
+ .map(|(routing_key, messages)| MessageGroup {
+ routing_key,
+ messages,
+ })
+ .collect(),
+ missing_header_count,
+ }
+}
+
+/// Extract the routing key from a message's `token` and `distinct_id` headers.
+fn routing_key(message: &SerializedKafkaMessage) -> Option<String> {
+ let token = message.headers.get("token")?;
+ let distinct_id = message.headers.get("distinct_id")?;
+ Some(format!("{token}:{distinct_id}"))
+}
+
+#[cfg(test)]
+mod tests {
+ use std::collections::HashMap;
+ use std::sync::Arc;
+ use std::time::Duration;
+
+ use super::*;
+ use crate::worker_registry::{WorkerRegistry, WorkerRegistryConfig};
+
+ // ---- helpers ----
+
+ fn make_msg(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,
+ }
+ }
+
+ fn make_msgs(specs: &[(&str, &str)]) -> Vec<SerializedKafkaMessage> {
+ specs.iter().map(|(t, d)| make_msg(t, d)).collect()
+ }
+
+ fn make_msg_with_headers(headers: HashMap<String, String>) -> SerializedKafkaMessage {
+ SerializedKafkaMessage {
+ topic: "test".to_string(),
+ partition: 7,
+ offset: 42,
+ timestamp: 0,
+ key: None,
+ value: None,
+ headers,
+ }
+ }
+
+ /// Registry with N healthy workers and no cooldown. `dead_declaration` is
+ /// very short so tests can drive a worker to dead quickly.
+ fn healthy_registry(n: usize) -> Arc<WorkerRegistry> {
+ let urls: Vec<String> = (0..n)
+ .map(|i| format!("http://worker:{}", 9001 + i))
+ .collect();
+ let config = WorkerRegistryConfig {
+ probe_interval: Duration::from_millis(50),
+ dead_declaration: Duration::from_millis(30),
+ passive_window: Duration::from_millis(500),
+ passive_error_threshold: 0.5,
+ passive_min_samples: 2,
+ degraded_hold: Duration::from_millis(50),
+ min_state_duration: Duration::ZERO,
+ probe_failure_threshold: 2,
+ };
+ Arc::new(WorkerRegistry::new(&urls, config))
+ }
+
+ // ---- routing key ----
+
+ #[test]
+ fn test_routing_key_format() {
+ let msg = make_msg("tok", "user-1");
+ assert_eq!(routing_key(&msg), Some("tok:user-1".to_string()));
+ }
+
+ #[test]
+ fn test_routing_key_missing_headers() {
+ assert_eq!(routing_key(&make_msg_with_headers(HashMap::new())), None);
+ }
+
+ #[test]
+ fn test_routing_key_requires_token_and_distinct_id() {
+ let mut headers = HashMap::new();
+ headers.insert("token".to_string(), "tok".to_string());
+
+ assert_eq!(routing_key(&make_msg_with_headers(headers)), None);
+ }
+
+ #[test]
+ fn test_group_messages_by_routing_key_uses_synthetic_key_for_missing_headers() {
+ let grouped = group_messages_by_routing_key(vec![make_msg_with_headers(HashMap::new())]);
+
+ assert_eq!(grouped.missing_header_count, 1);
+ assert_eq!(grouped.groups.len(), 1);
+ assert_eq!(grouped.groups[0].routing_key, ":7:42");
+ assert_eq!(grouped.groups[0].messages.len(), 1);
+ }
+
+ #[test]
+ fn test_group_messages_by_routing_key_groups_same_routing_key() {
+ let grouped =
+ group_messages_by_routing_key(make_msgs(&[("tok", "user-1"), ("tok", "user-1")]));
+
+ assert_eq!(grouped.missing_header_count, 0);
+ assert_eq!(grouped.groups.len(), 1);
+ assert_eq!(grouped.groups[0].routing_key, "tok:user-1");
+ assert_eq!(grouped.groups[0].messages.len(), 2);
+ }
+
+ // ---- worker assignments ----
+
+ #[test]
+ fn test_worker_assignments_merges_groups_for_same_worker() {
+ let mut assignments = WorkerAssignments::new(2);
+
+ assignments.add_group(
+ 1,
+ MessageGroup {
+ routing_key: "tok:user-1".to_string(),
+ messages: make_msgs(&[("tok", "user-1")]),
+ },
+ );
+ assignments.add_group(
+ 1,
+ MessageGroup {
+ routing_key: "tok:user-2".to_string(),
+ messages: make_msgs(&[("tok", "user-2")]),
+ },
+ );
+
+ assert_eq!(assignments.provisional_in_flight(), &[0, 1]);
+ assert_eq!(
+ assignments.routed_counts().collect::<Vec<_>>(),
+ vec![(1, 2)]
+ );
+
+ let sub_batches = assignments.into_sub_batches();
+ assert_eq!(sub_batches.len(), 1);
+ assert_eq!(sub_batches[0].worker_idx, 1);
+ assert_eq!(sub_batches[0].messages.len(), 2);
+ assert_eq!(
+ sub_batches[0].routing_keys,
+ vec!["tok:user-1".to_string(), "tok:user-2".to_string()]
+ );
+ }
+
+ // ---- basic assignment ----
+
+ #[test]
+ fn test_single_worker_all_messages_go_there() {
+ let registry = healthy_registry(1);
+ let dispatcher = Dispatcher::new(registry);
+
+ let sub_batches = dispatcher.assign(make_msgs(&[("t", "a"), ("t", "b"), ("t", "c")]));
+
+ assert_eq!(sub_batches.len(), 1);
+ assert_eq!(sub_batches[0].worker_idx, 0);
+ assert_eq!(sub_batches[0].messages.len(), 3);
+ }
+
+ #[test]
+ fn test_empty_batch_returns_no_sub_batches() {
+ let registry = healthy_registry(2);
+ let dispatcher = Dispatcher::new(registry);
+ assert!(dispatcher.assign(vec![]).is_empty());
+ }
+
+ #[test]
+ fn test_same_distinct_id_goes_to_same_worker_across_batches() {
+ let registry = healthy_registry(3);
+ let dispatcher = Dispatcher::new(registry);
+
+ let batch1 = dispatcher.assign(make_msgs(&[("t", "user-1")]));
+ assert_eq!(batch1.len(), 1);
+ let worker = batch1[0].worker_idx;
+ dispatcher.on_sub_batch_resolved(worker, &batch1[0].routing_keys);
+
+ // Second batch: same key must go to same worker (pin still alive until resolved).
+ // We resolved already, so the pin was evicted — it will re-pin to the same or
+ // different worker. What we care about is that within a batch, same key → same worker.
+ let batch2 = dispatcher.assign(make_msgs(&[("t", "user-1"), ("t", "user-1")]));
+ assert_eq!(batch2.len(), 1); // both user-1 messages merge into one sub-batch
+ }
+
+ // ---- sticky pins ----
+
+ #[test]
+ fn test_pin_is_sticky_across_batches() {
+ let registry = healthy_registry(3);
+ let dispatcher = Dispatcher::new(registry);
+
+ // First batch pins "t:user-1" to some worker.
+ let b1 = dispatcher.assign(make_msgs(&[("t", "user-1")]));
+ let pinned_worker = b1[0].worker_idx;
+
+ // Do NOT resolve b1 — pin stays alive with ref_count=1.
+
+ // Second batch: same key must hit the same worker.
+ let b2 = dispatcher.assign(make_msgs(&[("t", "user-1")]));
+ assert_eq!(b2.len(), 1);
+ assert_eq!(b2[0].worker_idx, pinned_worker);
+ }
+
+ #[test]
+ fn test_different_keys_may_go_to_different_workers() {
+ let registry = healthy_registry(2);
+ let dispatcher = Dispatcher::new(registry);
+
+ // With 2 workers, bin-packing should spread 2 fresh keys across them.
+ let sub_batches = dispatcher.assign(make_msgs(&[("t", "user-1"), ("t", "user-2")]));
+
+ let total_msgs: usize = sub_batches.iter().map(|b| b.messages.len()).sum();
+ assert_eq!(total_msgs, 2);
+ }
+
+ // ---- ref counting ----
+
+ #[test]
+ fn test_pin_evicted_when_ref_count_reaches_zero() {
+ let registry = healthy_registry(2);
+ let dispatcher = Dispatcher::new(registry);
+
+ let b1 = dispatcher.assign(make_msgs(&[("t", "user-1")]));
+ let worker = b1[0].worker_idx;
+
+ // Pin exists (ref_count = 1).
+ {
+ let table = dispatcher.pin_table.lock().unwrap();
+ assert!(table.pins.contains_key("t:user-1"));
+ }
+
+ dispatcher.on_sub_batch_resolved(worker, &b1[0].routing_keys);
+
+ // Pin evicted (ref_count hit 0).
+ {
+ let table = dispatcher.pin_table.lock().unwrap();
+ assert!(!table.pins.contains_key("t:user-1"));
+ }
+ }
+
+ #[test]
+ fn test_pin_ref_count_accumulates_across_batches() {
+ let registry = healthy_registry(2);
+ let dispatcher = Dispatcher::new(registry);
+
+ let b1 = dispatcher.assign(make_msgs(&[("t", "user-1")]));
+ let worker = b1[0].worker_idx;
+
+ // Second batch, same key, pin not yet resolved: ref_count should be 2.
+ dispatcher.assign(make_msgs(&[("t", "user-1")]));
+
+ {
+ let table = dispatcher.pin_table.lock().unwrap();
+ let pin = table.pins.get("t:user-1").unwrap();
+ assert_eq!(pin.ref_count, 2);
+ }
+
+ // Resolve first sub-batch: ref_count drops to 1, pin stays.
+ dispatcher.on_sub_batch_resolved(worker, &b1[0].routing_keys);
+ {
+ let table = dispatcher.pin_table.lock().unwrap();
+ assert!(table.pins.contains_key("t:user-1"));
+ assert_eq!(table.pins["t:user-1"].ref_count, 1);
+ }
+ }
+
+ // ---- in-flight counter ----
+
+ #[test]
+ fn test_in_flight_incremented_on_assign() {
+ let registry = healthy_registry(2);
+ let dispatcher = Dispatcher::new(registry);
+
+ let b1 = dispatcher.assign(make_msgs(&[("t", "user-1")]));
+ let worker = b1[0].worker_idx;
+
+ let table = dispatcher.pin_table.lock().unwrap();
+ assert_eq!(table.in_flight[worker], 1);
+ }
+
+ #[test]
+ fn test_in_flight_decremented_on_resolve() {
+ let registry = healthy_registry(2);
+ let dispatcher = Dispatcher::new(registry);
+
+ let b1 = dispatcher.assign(make_msgs(&[("t", "user-1")]));
+ let worker = b1[0].worker_idx;
+
+ dispatcher.on_sub_batch_resolved(worker, &b1[0].routing_keys);
+
+ let table = dispatcher.pin_table.lock().unwrap();
+ assert_eq!(table.in_flight[worker], 0);
+ }
+
+ #[test]
+ fn test_multiple_keys_same_worker_one_in_flight_increment() {
+ // All messages in a batch that go to the same worker produce a single
+ // sub-batch, so in_flight should only increment by 1 — not by the
+ // number of distinct keys.
+ let registry = healthy_registry(1);
+ let dispatcher = Dispatcher::new(registry);
+
+ dispatcher.assign(make_msgs(&[("t", "a"), ("t", "b"), ("t", "c")]));
+
+ let table = dispatcher.pin_table.lock().unwrap();
+ assert_eq!(table.in_flight[0], 1);
+ }
+
+ // ---- bin-packing ----
+
+ #[test]
+ fn test_bin_packing_targets_least_loaded_worker() {
+ let registry = healthy_registry(2);
+ let dispatcher = Dispatcher::new(registry);
+
+ // Artificially load worker 0 with 3 in-flight sub-batches.
+ {
+ let mut table = dispatcher.pin_table.lock().unwrap();
+ table.in_flight[0] = 3;
+ }
+
+ // A fresh key should go to worker 1 (load = 0).
+ let b = dispatcher.assign(make_msgs(&[("t", "fresh")]));
+ assert_eq!(b.len(), 1);
+ assert_eq!(b[0].worker_idx, 1);
+ }
+
+ // ---- dead worker handling ----
+
+ #[tokio::test]
+ async fn test_dead_worker_pin_dropped_and_rerouted() {
+ let registry = healthy_registry(2);
+ let dispatcher = Dispatcher::new(Arc::clone(&registry));
+
+ // Pin "user-1" to whichever worker gets it first.
+ let b1 = dispatcher.assign(make_msgs(&[("t", "user-1")]));
+ let original_worker = b1[0].worker_idx;
+ let other_worker = 1 - original_worker;
+
+ // Drive the pinned worker to dead via passive signal.
+ for _ in 0..5 {
+ registry.record_outcome(original_worker, true);
+ }
+ tokio::time::sleep(Duration::from_millis(40)).await;
+ assert!(registry.is_dead(original_worker));
+
+ // Next batch: pin must be dropped and key rerouted to the live worker.
+ let b2 = dispatcher.assign(make_msgs(&[("t", "user-1")]));
+ assert_eq!(b2.len(), 1);
+ assert_eq!(b2[0].worker_idx, other_worker);
+ }
+
+ #[test]
+ fn test_all_workers_dead_returns_empty() {
+ let registry = healthy_registry(2);
+ let dispatcher = Dispatcher::new(Arc::clone(&registry));
+
+ // Force both workers to Unhealthy via passive signal (min_state_duration=0).
+ for idx in 0..2 {
+ for _ in 0..5 {
+ registry.record_outcome(idx, true);
+ }
+ }
+
+ // Both workers are Unhealthy (not yet dead, but Unhealthy).
+ // Dispatcher should not route to Unhealthy workers.
+ let b = dispatcher.assign(make_msgs(&[("t", "user-1")]));
+ assert!(b.is_empty());
+ }
+}
diff --git a/rust/ingestion-consumer/src/lib.rs b/rust/ingestion-consumer/src/lib.rs
index b846b46fadfa..af4d1b11bf1d 100644
--- a/rust/ingestion-consumer/src/lib.rs
+++ b/rust/ingestion-consumer/src/lib.rs
@@ -1,5 +1,6 @@
pub mod config;
pub mod consumer;
+pub mod dispatcher;
pub mod kafka_config;
pub mod router;
pub mod transport;
diff --git a/rust/ingestion-consumer/tests/dispatcher_integration_test.rs b/rust/ingestion-consumer/tests/dispatcher_integration_test.rs
new file mode 100644
index 000000000000..82b01d85f800
--- /dev/null
+++ b/rust/ingestion-consumer/tests/dispatcher_integration_test.rs
@@ -0,0 +1,384 @@
+use std::collections::HashMap;
+use std::sync::atomic::{AtomicBool, Ordering};
+use std::sync::Arc;
+use std::time::Duration;
+
+use axum::extract::{Json, State};
+use axum::response::IntoResponse;
+use axum::routing::{get, post};
+use axum::Router;
+use tokio::net::TcpListener;
+use tokio_util::sync::CancellationToken;
+
+use ingestion_consumer::dispatcher::Dispatcher;
+use ingestion_consumer::types::{IngestBatchRequest, IngestBatchResponse, SerializedKafkaMessage};
+use ingestion_consumer::worker_registry::{WorkerRegistry, WorkerRegistryConfig, WorkerState};
+
+// ---- FakeWorker ----
+
+#[derive(Clone)]
+struct WorkerCtrl {
+ is_healthy: Arc<AtomicBool>,
+}
+
+async fn ready_handler(State(ctrl): State<WorkerCtrl>) -> impl IntoResponse {
+ if ctrl.is_healthy.load(Ordering::Relaxed) {
+ axum::http::StatusCode::OK
+ } else {
+ axum::http::StatusCode::SERVICE_UNAVAILABLE
+ }
+}
+
+async fn ingest_handler(
+ State(_ctrl): State<WorkerCtrl>,
+ Json(req): Json<IngestBatchRequest>,
+) -> Json<IngestBatchResponse> {
+ let accepted = req.messages.len() as u32;
+ Json(IngestBatchResponse {
+ batch_id: req.batch_id,
+ status: "ok".to_string(),
+ accepted,
+ error: None,
+ })
+}
+
+struct FakeWorker {
+ pub url: String,
+ is_healthy: Arc<AtomicBool>,
+ handle: tokio::task::JoinHandle<()>,
+}
+
+impl FakeWorker {
+ async fn start() -> Self {
+ let is_healthy = Arc::new(AtomicBool::new(true));
+ let ctrl = WorkerCtrl {
+ is_healthy: Arc::clone(&is_healthy),
+ };
+
+ let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let addr = listener.local_addr().unwrap();
+
+ let app = Router::new()
+ .route("/_ready", get(ready_handler))
+ .route("/ingest", post(ingest_handler))
+ .with_state(ctrl);
+
+ let handle = tokio::spawn(async move {
+ axum::serve(listener, app)
+ .await
+ .expect("fake worker server error");
+ });
+
+ Self {
+ url: format!("http://{addr}"),
+ is_healthy,
+ handle,
+ }
+ }
+
+ fn set_healthy(&self, healthy: bool) {
+ self.is_healthy.store(healthy, Ordering::Relaxed);
+ }
+}
+
+impl Drop for FakeWorker {
+ fn drop(&mut self) {
+ self.handle.abort();
+ }
+}
+
+// ---- helpers ----
+
+fn fast_config() -> WorkerRegistryConfig {
+ WorkerRegistryConfig {
+ probe_interval: Duration::from_millis(15),
+ dead_declaration: Duration::from_millis(40),
+ passive_window: Duration::from_secs(60),
+ passive_error_threshold: 0.01,
+ passive_min_samples: 1000,
+ degraded_hold: Duration::from_millis(30),
+ min_state_duration: Duration::ZERO,
+ probe_failure_threshold: 2,
+ }
+}
+
+fn make_msg(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,
+ }
+}
+
+async fn wait_for_state(registry: &WorkerRegistry, worker_idx: usize, expected: WorkerState) {
+ let deadline = tokio::time::Instant::now() + Duration::from_secs(3);
+ loop {
+ if registry.state(worker_idx) == expected {
+ return;
+ }
+ assert!(
+ tokio::time::Instant::now() < deadline,
+ "timed out waiting for worker {worker_idx} to become {expected:?}"
+ );
+ tokio::time::sleep(Duration::from_millis(5)).await;
+ }
+}
+
+async fn wait_for_dead(registry: &WorkerRegistry, worker_idx: usize) {
+ let deadline = tokio::time::Instant::now() + Duration::from_secs(3);
+ loop {
+ if registry.is_dead(worker_idx) {
+ return;
+ }
+ assert!(
+ tokio::time::Instant::now() < deadline,
+ "timed out waiting for worker {worker_idx} to be declared dead"
+ );
+ tokio::time::sleep(Duration::from_millis(5)).await;
+ }
+}
+
+async fn wait_for_not_unhealthy(registry: &WorkerRegistry, worker_idx: usize) {
+ let deadline = tokio::time::Instant::now() + Duration::from_secs(3);
+ loop {
+ if registry.state(worker_idx) != WorkerState::Unhealthy {
+ return;
+ }
+ assert!(
+ tokio::time::Instant::now() < deadline,
+ "timed out waiting for worker {worker_idx} to leave Unhealthy"
+ );
+ tokio::time::sleep(Duration::from_millis(5)).await;
+ }
+}
+
+// ---- tests ----
+
+/// Fresh keys must not be assigned to an Unhealthy worker, even though the
+/// worker's server is still up (just returning 503 on /_ready).
+#[tokio::test]
+async fn test_new_keys_skip_unhealthy_worker() {
+ let w0 = FakeWorker::start().await;
+ let w1 = FakeWorker::start().await;
+
+ let urls = vec![w0.url.clone(), w1.url.clone()];
+ let registry = Arc::new(WorkerRegistry::new(&urls, fast_config()));
+ let dispatcher = Dispatcher::new(Arc::clone(&registry));
+
+ let token = CancellationToken::new();
+ Arc::clone(&registry).start_probing(token.clone());
+
+ w1.set_healthy(false);
+ wait_for_state(&registry, 1, WorkerState::Unhealthy).await;
+
+ let keys: Vec<_> = (0..10)
+ .map(|i| make_msg("t", &format!("user-{i}")))
+ .collect();
+ let sub_batches = dispatcher.assign(keys);
+
+ assert!(
+ sub_batches.iter().all(|b| b.worker_idx == 0),
+ "all assignments should go to w0; workers used: {:?}",
+ sub_batches.iter().map(|b| b.worker_idx).collect::<Vec<_>>()
+ );
+
+ token.cancel();
+}
+
+/// A key pinned to a worker while it was healthy must be re-routed to a
+/// healthy worker after the original worker is declared dead.
+#[tokio::test]
+async fn test_pinned_key_rerouted_after_dead_declaration() {
+ let w0 = FakeWorker::start().await;
+ let w1 = FakeWorker::start().await;
+
+ let urls = vec![w0.url.clone(), w1.url.clone()];
+ let registry = Arc::new(WorkerRegistry::new(&urls, fast_config()));
+ let dispatcher = Dispatcher::new(Arc::clone(&registry));
+
+ let token = CancellationToken::new();
+ Arc::clone(&registry).start_probing(token.clone());
+
+ // Pin "t:user-1" to whichever worker gets it first. Hold the sub-batch
+ // open (don't call on_sub_batch_resolved) so the pin stays alive.
+ let b1 = dispatcher.assign(vec![make_msg("t", "user-1")]);
+ assert_eq!(b1.len(), 1);
+ let pinned_to = b1[0].worker_idx;
+ let other = 1 - pinned_to;
+
+ // Kill the pinned worker's health endpoint.
+ if pinned_to == 0 {
+ w0.set_healthy(false);
+ } else {
+ w1.set_healthy(false);
+ }
+
+ // Wait for Unhealthy then dead declaration.
+ wait_for_state(&registry, pinned_to, WorkerState::Unhealthy).await;
+ wait_for_dead(&registry, pinned_to).await;
+
+ // Next assign: the stale pin is evicted and the key re-routes to the live worker.
+ let b2 = dispatcher.assign(vec![make_msg("t", "user-1")]);
+ assert_eq!(b2.len(), 1, "expected exactly one sub-batch");
+ assert_eq!(
+ b2[0].worker_idx, other,
+ "user-1 should reroute to w{other} after w{pinned_to} is dead"
+ );
+
+ token.cancel();
+}
+
+/// When a dead worker's health endpoint starts returning 200 again, the probe
+/// should drive it through Degraded and eventually back to Healthy, at which
+/// point the dispatcher routes new keys to it again.
+#[tokio::test]
+async fn test_worker_recovery_detected_by_probe() {
+ let w0 = FakeWorker::start().await;
+ let w1 = FakeWorker::start().await;
+
+ // w1 starts unhealthy so the probe detects it failing from the beginning.
+ w1.set_healthy(false);
+
+ let urls = vec![w0.url.clone(), w1.url.clone()];
+ let registry = Arc::new(WorkerRegistry::new(&urls, fast_config()));
+ let dispatcher = Dispatcher::new(Arc::clone(&registry));
+
+ let token = CancellationToken::new();
+ Arc::clone(&registry).start_probing(token.clone());
+
+ wait_for_state(&registry, 1, WorkerState::Unhealthy).await;
+
+ // Recover w1.
+ w1.set_healthy(true);
+
+ // Wait until w1 leaves Unhealthy (Degraded or Healthy).
+ wait_for_not_unhealthy(&registry, 1).await;
+
+ // Assign a large set of fresh keys. Both workers should get some, since w1
+ // is now at least Degraded (Healthy | Degraded both receive assignments).
+ let keys: Vec<_> = (0..40)
+ .map(|i| make_msg("t", &format!("user-{i}")))
+ .collect();
+ let sub_batches = dispatcher.assign(keys);
+
+ let workers_used: std::collections::HashSet<usize> =
+ sub_batches.iter().map(|b| b.worker_idx).collect();
+ assert!(
+ workers_used.contains(&1),
+ "w1 should receive new keys after recovery; workers used: {workers_used:?}"
+ );
+
+ token.cancel();
+}
+
+/// With 3 workers, one dying mid-flight:
+/// - Keys pinned to the dead worker are evicted and re-routed to the survivors.
+/// - Keys pinned to the two live workers are unaffected.
+/// - No new keys reach the dead worker.
+#[tokio::test]
+async fn test_three_workers_one_dies_and_load_rebalances() {
+ let w0 = FakeWorker::start().await;
+ let w1 = FakeWorker::start().await;
+ let w2 = FakeWorker::start().await;
+
+ let urls = vec![w0.url.clone(), w1.url.clone(), w2.url.clone()];
+ let registry = Arc::new(WorkerRegistry::new(&urls, fast_config()));
+ let dispatcher = Dispatcher::new(Arc::clone(&registry));
+
+ let token = CancellationToken::new();
+ Arc::clone(&registry).start_probing(token.clone());
+
+ // 3 distinct keys of equal size: bin-packing spreads exactly one key per
+ // worker (provisional load increases by 1 for each pick, breaking all ties).
+ let first = dispatcher.assign(vec![
+ make_msg("t", "key-a"),
+ make_msg("t", "key-b"),
+ make_msg("t", "key-c"),
+ ]);
+ assert_eq!(
+ first.len(),
+ 3,
+ "3 keys across 3 workers must yield 3 sub-batches"
+ );
+ let workers_covered: std::collections::HashSet<usize> =
+ first.iter().map(|b| b.worker_idx).collect();
+ assert_eq!(workers_covered.len(), 3, "all 3 workers must receive a pin");
+
+ // Remember which routing key was pinned to w1 — we'll re-assign it later
+ // to verify it migrates to a live worker.
+ let w1_key = first
+ .iter()
+ .find(|b| b.worker_idx == 1)
+ .unwrap()
+ .routing_keys[0]
+ .clone();
+
+ // Kill w1 and wait for dead declaration (first batch stays open throughout).
+ w1.set_healthy(false);
+ wait_for_state(&registry, 1, WorkerState::Unhealthy).await;
+ wait_for_dead(&registry, 1).await;
+
+ // Fresh keys must only land on w0 or w2.
+ let fresh = dispatcher.assign(vec![
+ make_msg("t", "new-1"),
+ make_msg("t", "new-2"),
+ make_msg("t", "new-3"),
+ ]);
+ assert!(
+ fresh.iter().all(|b| b.worker_idx != 1),
+ "fresh keys must not route to dead w1; workers used: {:?}",
+ fresh.iter().map(|b| b.worker_idx).collect::<Vec<_>>()
+ );
+
+ // The key that was pinned to w1 must re-route to w0 or w2 on its next assign.
+ // The pin was evicted by drop_dead_pins during the fresh-keys assign above.
+ let (_, distinct_id) = w1_key.split_once(':').unwrap();
+ let rerouted = dispatcher.assign(vec![make_msg("t", distinct_id)]);
+ assert_eq!(
+ rerouted.len(),
+ 1,
+ "rerouted key must produce exactly one sub-batch"
+ );
+ assert_ne!(
+ rerouted[0].worker_idx, 1,
+ "key previously pinned to w1 must reroute to a live worker, not w1"
+ );
+
+ token.cancel();
+}
+
+/// When every worker is Unhealthy, assign must return an empty vec — no
+/// messages can be routed and nothing must be dropped silently.
+#[tokio::test]
+async fn test_all_workers_unhealthy_returns_empty() {
+ let w0 = FakeWorker::start().await;
+ let w1 = FakeWorker::start().await;
+
+ w0.set_healthy(false);
+ w1.set_healthy(false);
+
+ let urls = vec![w0.url.clone(), w1.url.clone()];
+ let registry = Arc::new(WorkerRegistry::new(&urls, fast_config()));
+ let dispatcher = Dispatcher::new(Arc::clone(&registry));
+
+ let token = CancellationToken::new();
+ Arc::clone(&registry).start_probing(token.clone());
+
+ wait_for_state(&registry, 0, WorkerState::Unhealthy).await;
+ wait_for_state(&registry, 1, WorkerState::Unhealthy).await;
+
+ let sub_batches = dispatcher.assign(vec![make_msg("t", "user-1")]);
+ assert!(
+ sub_batches.is_empty(),
+ "expected empty assignment when all workers are unhealthy"
+ );
+
+ token.cancel();
+}