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.

fix(ingestion-consumer): assign batches on the consumer loop in batch order (#84535)

José Sequeira7d6dc69e2c4d
diff --git a/rust/ingestion-consumer/src/consumer.rs b/rust/ingestion-consumer/src/consumer.rs
index 4f439e77a97c..e99f5f95e90d 100644
--- a/rust/ingestion-consumer/src/consumer.rs
+++ b/rust/ingestion-consumer/src/consumer.rs
@@ -308,18 +308,31 @@ impl IngestionConsumer {
info!("Consumer loop stopped");
}
- fn spawn_batch_processing(&self, collected: CollectedBatch) -> InFlightBatch {
+ fn spawn_batch_processing(&self, mut collected: CollectedBatch) -> InFlightBatch {
let batch_size = collected.messages.len();
let batch_id = make_batch_id();
- // Register here, on the consumer loop, so the stash learns batch order
- // before the spawned tasks race: assignment and failed-send deferrals
- // can reach the stash out of batch order.
+ // Register AND assign here, on the consumer loop, so both happen in
+ // true batch order. Registration first, so the stash learns batch
+ // order before failed-send deferrals (which land in gather order) can
+ // reach it. Assignment too: on spawned tasks, batch N+1's assign could
+ // beat batch N's to the pin table and send a key's newer messages
+ // first — per-key send order must be fixed exactly once, in Kafka
+ // order, at assignment.
self.dispatcher.register_batch(&batch_id);
record_if(&self.debug_recorder, || DebugEventKind::BatchDispatched {
batch_id: batch_id.clone(),
messages: batch_size,
partitions: debug_partition_offsets(&collected.offsets, &collected.stats.max_lag_ms),
});
+ let assign_start = Instant::now();
+ let messages = std::mem::take(&mut collected.messages);
+ let sub_batches = self.dispatcher.assign(&batch_id, messages);
+ // Assignment serializes on the consumer loop (it no longer overlaps
+ // batch collection) — watch this stays a small fraction of the batch
+ // collection interval.
+ histogram!("ingestion_consumer_assign_duration_seconds")
+ .record(assign_start.elapsed().as_secs_f64());
+
let task_batch_id = batch_id.clone();
let dispatcher = Arc::clone(&self.dispatcher);
let transport = Arc::clone(&self.transport);
@@ -330,6 +343,8 @@ impl IngestionConsumer {
let handle = tokio::spawn(async move {
Self::process_collected_batch(
collected,
+ sub_batches,
+ batch_size,
task_batch_id,
dispatcher,
transport,
@@ -565,11 +580,15 @@ impl IngestionConsumer {
.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`.
+ /// Scatter a batch's pre-assigned sub-batches to workers, gather results,
+ /// and feed passive health signals. Assignment already happened on the
+ /// consumer loop (see `spawn_batch_processing`); offset commits happen
+ /// later, in Kafka batch order, in `complete_oldest_batch`.
+ #[allow(clippy::too_many_arguments)]
async fn process_collected_batch(
collected: CollectedBatch,
+ sub_batches: Vec<SubBatch>,
+ batch_size: usize,
batch_id: String,
dispatcher: Arc<Dispatcher>,
transport: Arc<HttpTransport>,
@@ -577,7 +596,6 @@ impl IngestionConsumer {
max_batch_size: usize,
max_batch_bytes: usize,
) -> anyhow::Result<ProcessedBatch> {
- let batch_size = collected.messages.len();
let start = Instant::now();
counter!("ingestion_consumer_messages_received_total").increment(batch_size as u64);
@@ -627,11 +645,6 @@ impl IngestionConsumer {
.record(*lag_ms as f64);
}
- // Health-aware assignment: groups by routing key, honors stickiness,
- // skips unhealthy/dead workers, and defers keys whose worker is
- // draining/dead (held in the dispatcher's stash, flushed at completion).
- let sub_batches = dispatcher.assign(&batch_id, collected.messages);
-
// Nothing to send and no flush-path activity (deferred, in-flight
// eager, or already eagerly accepted) → no usable workers.
if sub_batches.is_empty() && !dispatcher.batch_has_flush_activity(&batch_id) {
diff --git a/rust/ingestion-consumer/src/dispatcher.rs b/rust/ingestion-consumer/src/dispatcher.rs
index 0f1d126eb7f7..9cd85fc0e8e7 100644
--- a/rust/ingestion-consumer/src/dispatcher.rs
+++ b/rust/ingestion-consumer/src/dispatcher.rs
@@ -9,7 +9,7 @@ use crate::aperture;
use crate::debug_recorder::{
record_if, DebugEventKind, DebugRecorder, DispatcherLoad, LoadEntry, RoutingDebug, SubBatchInfo,
};
-use crate::order_sentinel::KeyOrderSentinel;
+use crate::order_sentinel::{KeyOrderSentinel, SendKind};
use crate::routing::{Router, RoutingStrategy, WorkerLoad};
use crate::stash::{DeferredGroup, Stash};
use crate::types::SerializedKafkaMessage;
@@ -381,8 +381,11 @@ impl Dispatcher {
// ahead of it — honor it.
table.pins.get_mut(&group.routing_key).unwrap().ref_count += 1;
bump_load(&mut working_load, &worker, group.messages.len());
- self.key_sentinel
- .note_sent(&group.routing_key, &group.messages);
+ self.key_sentinel.note_sent(
+ &group.routing_key,
+ &group.messages,
+ SendKind::Fresh,
+ );
assignments.add_group(worker, group);
}
Some(_) => {
@@ -482,7 +485,7 @@ impl Dispatcher {
},
);
self.key_sentinel
- .note_sent(&group.routing_key, &group.messages);
+ .note_sent(&group.routing_key, &group.messages, SendKind::Fresh);
assignments.add_group(worker, group);
}
drop(router);
@@ -559,9 +562,9 @@ impl Dispatcher {
}
/// Record a batch's arrival order for the stash. Must be called from the
- /// consumer loop in true batch order, before the batch is processed —
- /// per-batch assignment runs on spawned tasks and failed sends re-defer in
- /// gather order, so no later call site can establish the order reliably.
+ /// consumer loop in true batch order, before `assign` — failed sends
+ /// re-defer in gather order, so no later call site can establish the
+ /// order reliably.
pub fn register_batch(&self, batch_id: &str) {
self.pin_table
.lock()
@@ -763,7 +766,7 @@ impl Dispatcher {
}
}
self.key_sentinel
- .note_sent(&group.routing_key, &group.messages);
+ .note_sent(&group.routing_key, &group.messages, SendKind::Resend);
assignments.add_group(
worker,
MessageGroup {
@@ -972,7 +975,8 @@ impl Dispatcher {
);
}
}
- self.key_sentinel.note_sent(key, &messages);
+ self.key_sentinel
+ .note_sent(key, &messages, SendKind::Resend);
let mut assignments = WorkerAssignments::new();
assignments.add_group(
worker.clone(),
diff --git a/rust/ingestion-consumer/src/order_sentinel.rs b/rust/ingestion-consumer/src/order_sentinel.rs
index b389e8546ff4..ad1920bc0cc1 100644
--- a/rust/ingestion-consumer/src/order_sentinel.rs
+++ b/rust/ingestion-consumer/src/order_sentinel.rs
@@ -13,9 +13,11 @@
//! **Per-key send order** ([`KeyOrderSentinel`]): for every routing key
//! (`token:distinct_id`), messages must be handed to workers in Kafka offset
//! order, and a message must never be re-sent after it was ACKed. Replays of
-//! un-ACKed messages (send failure → deferred flush) are legal at-least-once
-//! behavior and are counted separately (`ingestion_consumer_key_replays_total`)
-//! rather than flagged. Checked in the dispatcher at assignment time — the
+//! un-ACKed messages on the retry paths ([`SendKind::Resend`]: send failure →
+//! deferred flush) are legal at-least-once behavior and are counted separately
+//! (`ingestion_consumer_key_replays_total`) rather than flagged; the same
+//! regression on a fresh assignment is a `send_below_last_sent` violation.
+//! Checked in the dispatcher at assignment time — the
//! point that defines the intended per-key order — under the pin-table lock.
//! Only messages produced with a Kafka key participate: null-key production
//! (e.g. overflow rerouting) spreads a routing key across partitions,
@@ -309,6 +311,9 @@ pub enum KeyOrderViolationKind {
/// A message at or below the key's highest ACKed offset was sent again —
/// duplicate processing of an already-acknowledged message.
ResendAfterAck,
+ /// A fresh (non-retry) send at or below the key's highest sent offset —
+ /// a newer batch's send overtook an older batch's for the same key.
+ SendBelowLastSent,
}
impl KeyOrderViolationKind {
@@ -316,10 +321,24 @@ impl KeyOrderViolationKind {
match self {
KeyOrderViolationKind::IntraGroupDisorder => "intra_group_disorder",
KeyOrderViolationKind::ResendAfterAck => "resend_after_ack",
+ KeyOrderViolationKind::SendBelowLastSent => "send_below_last_sent",
}
}
}
+/// Whether a send may legitimately repeat offsets the key has already sent.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum SendKind {
+ /// A first-time assignment. Fresh sends run in batch order over a key's
+ /// single partition, so their offsets must only move forward; a regression
+ /// is a [`KeyOrderViolationKind::SendBelowLastSent`] violation.
+ Fresh,
+ /// A retry path (deferred flush or eager release) that re-routes messages
+ /// whose earlier send failed — repeating un-ACKed offsets is expected
+ /// at-least-once behavior, not a violation.
+ Resend,
+}
+
/// One detected per-key order violation, returned for tests and logged.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct KeyOrderViolation {
@@ -375,16 +394,19 @@ impl KeyOrderSentinel {
}
}
- /// Record that `messages` for `routing_key` are being handed to a worker
- /// (fresh assignment or deferred flush). Call at assignment time, under the
- /// dispatcher's pin-table lock, so the check order matches the intended
- /// per-key send order. Null-key messages are skipped — they carry no
- /// per-key order promise (see module docs). Emits metrics and logs;
- /// returns violations for tests.
+ /// Record that `messages` for `routing_key` are being handed to a worker.
+ /// `kind` distinguishes a fresh assignment (offsets must only move
+ /// forward) from a retry-path resend (repeating un-ACKed offsets is
+ /// legal). Call at assignment time, under the dispatcher's pin-table
+ /// lock, so the check order matches the intended per-key send order.
+ /// Null-key messages are skipped — they carry no per-key order promise
+ /// (see module docs). Emits metrics and logs; returns violations for
+ /// tests.
pub fn note_sent(
&self,
routing_key: &str,
messages: &[SerializedKafkaMessage],
+ kind: SendKind,
) -> Vec<KeyOrderViolation> {
if !self.enabled.load(Ordering::Relaxed) {
return Vec::new();
@@ -450,11 +472,24 @@ impl KeyOrderSentinel {
offset: first.offset,
});
state.last_sent = state.last_sent.max(last.offset);
- } else {
+ } else if kind == SendKind::Resend {
// Replay of a not-yet-ACKed range: the legal retry path
// (send failure → defer → flush re-routes the same messages).
counter!("ingestion_consumer_key_replays_total").increment(1);
state.last_sent = state.last_sent.max(last.offset);
+ } else {
+ // A fresh send regressed: a newer batch's assignment for
+ // this key overtook an older batch's. (A rebalance racing
+ // an in-flight batch can produce a rare false positive
+ // until epoch-scoped baselines land — treat as near-zero,
+ // not hard-zero.)
+ violations.push(KeyOrderViolation {
+ kind: KeyOrderViolationKind::SendBelowLastSent,
+ routing_key: routing_key.to_string(),
+ partition: first.partition,
+ offset: first.offset,
+ });
+ state.last_sent = state.last_sent.max(last.offset);
}
}
}
@@ -739,17 +774,17 @@ mod tests {
fn forward_sends_pass() {
let sentinel = KeyOrderSentinel::new();
assert!(sentinel
- .note_sent("t:a", &[msg_at(0, 1), msg_at(0, 2)])
+ .note_sent("t:a", &[msg_at(0, 1), msg_at(0, 2)], SendKind::Fresh)
.is_empty());
assert!(sentinel
- .note_sent("t:a", &[msg_at(0, 3), msg_at(0, 4)])
+ .note_sent("t:a", &[msg_at(0, 3), msg_at(0, 4)], SendKind::Fresh)
.is_empty());
}
#[test]
fn intra_group_disorder_is_detected() {
let sentinel = KeyOrderSentinel::new();
- let violations = sentinel.note_sent("t:a", &[msg_at(0, 2), msg_at(0, 1)]);
+ let violations = sentinel.note_sent("t:a", &[msg_at(0, 2), msg_at(0, 1)], SendKind::Fresh);
assert_eq!(violations.len(), 1);
assert_eq!(
violations[0].kind,
@@ -760,19 +795,36 @@ mod tests {
#[test]
fn replay_of_unacked_range_is_not_a_violation() {
let sentinel = KeyOrderSentinel::new();
- sentinel.note_sent("t:a", &[msg_at(0, 1), msg_at(0, 2)]);
+ sentinel.note_sent("t:a", &[msg_at(0, 1), msg_at(0, 2)], SendKind::Fresh);
// Send failed (no ACK) → deferred flush re-sends the same messages.
assert!(sentinel
- .note_sent("t:a", &[msg_at(0, 1), msg_at(0, 2)])
+ .note_sent("t:a", &[msg_at(0, 1), msg_at(0, 2)], SendKind::Resend)
+ .is_empty());
+ }
+
+ #[test]
+ fn fresh_send_below_last_sent_is_a_violation() {
+ // A fresh assignment regressing below the key's sent watermark means a
+ // newer batch's send overtook an older batch's — the race the
+ // consumer-loop assignment ordering exists to prevent.
+ let sentinel = KeyOrderSentinel::new();
+ sentinel.note_sent("t:a", &[msg_at(0, 3), msg_at(0, 4)], SendKind::Fresh);
+ let violations = sentinel.note_sent("t:a", &[msg_at(0, 1), msg_at(0, 2)], SendKind::Fresh);
+ assert_eq!(violations.len(), 1);
+ assert_eq!(violations[0].kind, KeyOrderViolationKind::SendBelowLastSent);
+ // The watermark still advanced: the next in-order send is clean.
+ assert!(sentinel
+ .note_sent("t:a", &[msg_at(0, 5)], SendKind::Fresh)
.is_empty());
}
#[test]
fn resend_after_ack_is_a_violation() {
let sentinel = KeyOrderSentinel::new();
- sentinel.note_sent("t:a", &[msg_at(0, 1), msg_at(0, 2)]);
+ sentinel.note_sent("t:a", &[msg_at(0, 1), msg_at(0, 2)], SendKind::Fresh);
sentinel.note_acked("t:a", 2);
- let violations = sentinel.note_sent("t:a", &[msg_at(0, 2)]);
+ // Even the legal retry path must never repeat an ACKed offset.
+ let violations = sentinel.note_sent("t:a", &[msg_at(0, 2)], SendKind::Resend);
assert_eq!(violations.len(), 1);
assert_eq!(violations[0].kind, KeyOrderViolationKind::ResendAfterAck);
}
@@ -783,9 +835,9 @@ mod tests {
// newer messages were sent and ACKed while its older ones were still
// deferred — flushing the older ones now is out-of-order processing.
let sentinel = KeyOrderSentinel::new();
- sentinel.note_sent("t:a", &[msg_at(0, 4), msg_at(0, 5)]);
+ sentinel.note_sent("t:a", &[msg_at(0, 4), msg_at(0, 5)], SendKind::Fresh);
sentinel.note_acked("t:a", 5);
- let violations = sentinel.note_sent("t:a", &[msg_at(0, 1), msg_at(0, 2)]);
+ let violations = sentinel.note_sent("t:a", &[msg_at(0, 1), msg_at(0, 2)], SendKind::Resend);
assert_eq!(violations.len(), 1);
assert_eq!(violations[0].kind, KeyOrderViolationKind::ResendAfterAck);
}
@@ -793,15 +845,17 @@ mod tests {
#[test]
fn out_of_order_acks_only_advance_the_watermark() {
let sentinel = KeyOrderSentinel::new();
- sentinel.note_sent("t:a", &[msg_at(0, 1), msg_at(0, 2)]);
- sentinel.note_sent("t:a", &[msg_at(0, 3), msg_at(0, 4)]);
+ sentinel.note_sent("t:a", &[msg_at(0, 1), msg_at(0, 2)], SendKind::Fresh);
+ sentinel.note_sent("t:a", &[msg_at(0, 3), msg_at(0, 4)], SendKind::Fresh);
// Sub-batch ACKs arrive in reverse HTTP-completion order.
sentinel.note_acked("t:a", 4);
sentinel.note_acked("t:a", 2);
// Forward progress from the true high-water mark is still clean.
- assert!(sentinel.note_sent("t:a", &[msg_at(0, 5)]).is_empty());
+ assert!(sentinel
+ .note_sent("t:a", &[msg_at(0, 5)], SendKind::Fresh)
+ .is_empty());
// …and re-sending below it still fires.
- let violations = sentinel.note_sent("t:a", &[msg_at(0, 3)]);
+ let violations = sentinel.note_sent("t:a", &[msg_at(0, 3)], SendKind::Resend);
assert_eq!(violations.len(), 1);
assert_eq!(violations[0].kind, KeyOrderViolationKind::ResendAfterAck);
}
@@ -809,23 +863,27 @@ mod tests {
#[test]
fn eviction_drops_state_and_rebaselines() {
let sentinel = KeyOrderSentinel::new();
- sentinel.note_sent("t:a", &[msg_at(0, 5)]);
+ sentinel.note_sent("t:a", &[msg_at(0, 5)], SendKind::Fresh);
sentinel.note_acked("t:a", 5);
sentinel.evict("t:a");
assert_eq!(sentinel.key_count(), 0);
// A rebaselined key doesn't compare against evicted history.
- assert!(sentinel.note_sent("t:a", &[msg_at(0, 6)]).is_empty());
+ assert!(sentinel
+ .note_sent("t:a", &[msg_at(0, 6)], SendKind::Fresh)
+ .is_empty());
}
#[test]
fn clear_resets_all_keys() {
let sentinel = KeyOrderSentinel::new();
- sentinel.note_sent("t:a", &[msg_at(0, 5)]);
- sentinel.note_sent("t:b", &[msg_at(1, 7)]);
+ sentinel.note_sent("t:a", &[msg_at(0, 5)], SendKind::Fresh);
+ sentinel.note_sent("t:b", &[msg_at(1, 7)], SendKind::Fresh);
sentinel.clear();
assert_eq!(sentinel.key_count(), 0);
// Post-rebalance redelivery of uncommitted offsets must not fire.
- assert!(sentinel.note_sent("t:a", &[msg_at(0, 3)]).is_empty());
+ assert!(sentinel
+ .note_sent("t:a", &[msg_at(0, 3)], SendKind::Fresh)
+ .is_empty());
}
#[test]
@@ -838,9 +896,9 @@ mod tests {
let keys = KeyOrderSentinel::new();
keys.set_enabled(false);
- keys.note_sent("t:a", &[msg_at(0, 5)]);
+ keys.note_sent("t:a", &[msg_at(0, 5)], SendKind::Fresh);
assert!(keys
- .note_sent("t:a", &[msg_at(0, 2), msg_at(0, 1)])
+ .note_sent("t:a", &[msg_at(0, 2), msg_at(0, 1)], SendKind::Fresh)
.is_empty());
assert_eq!(keys.key_count(), 0, "no state accumulates while disabled");
}
@@ -848,20 +906,24 @@ mod tests {
#[test]
fn disabling_key_sentinel_clears_stale_watermarks() {
let keys = KeyOrderSentinel::new();
- keys.note_sent("t:a", &[msg_at(0, 5)]);
+ keys.note_sent("t:a", &[msg_at(0, 5)], SendKind::Fresh);
keys.note_acked("t:a", 5);
keys.set_enabled(false);
keys.set_enabled(true);
// Re-enable rebaselines: no comparison against pre-disable history.
- assert!(keys.note_sent("t:a", &[msg_at(0, 3)]).is_empty());
+ assert!(keys
+ .note_sent("t:a", &[msg_at(0, 3)], SendKind::Fresh)
+ .is_empty());
}
#[test]
fn partition_move_rebaselines() {
let sentinel = KeyOrderSentinel::new();
- sentinel.note_sent("t:a", &[msg_at(0, 100)]);
+ sentinel.note_sent("t:a", &[msg_at(0, 100)], SendKind::Fresh);
// Same key on a different partition: offsets aren't comparable.
- assert!(sentinel.note_sent("t:a", &[msg_at(3, 1)]).is_empty());
+ assert!(sentinel
+ .note_sent("t:a", &[msg_at(3, 1)], SendKind::Fresh)
+ .is_empty());
}
#[test]
@@ -870,11 +932,11 @@ mod tests {
// Null-key production round-robins a key across partitions; there is
// no per-key order to check, even when offsets regress across sends.
assert!(sentinel
- .note_sent("t:a", &[unkeyed_msg_at(1, 5000)])
+ .note_sent("t:a", &[unkeyed_msg_at(1, 5000)], SendKind::Fresh)
.is_empty());
assert_eq!(sentinel.key_count(), 0, "unkeyed sends hold no state");
assert!(sentinel
- .note_sent("t:a", &[unkeyed_msg_at(0, 3)])
+ .note_sent("t:a", &[unkeyed_msg_at(0, 3)], SendKind::Fresh)
.is_empty());
}
@@ -886,9 +948,15 @@ mod tests {
// send would fire a false resend_after_ack.
let sentinel = KeyOrderSentinel::new();
assert!(sentinel
- .note_sent("t:a", &[msg_at(0, 100), unkeyed_msg_at(1, 5000)])
+ .note_sent(
+ "t:a",
+ &[msg_at(0, 100), unkeyed_msg_at(1, 5000)],
+ SendKind::Fresh
+ )
.is_empty());
sentinel.note_acked("t:a", 100);
- assert!(sentinel.note_sent("t:a", &[msg_at(0, 101)]).is_empty());
+ assert!(sentinel
+ .note_sent("t:a", &[msg_at(0, 101)], SendKind::Fresh)
+ .is_empty());
}
}