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(kafka-consumer): add shared consumer crate with offset ledger (#91760)

Paweł Ledwoń605b33c9b1b7
diff --git a/rust/Cargo.lock b/rust/Cargo.lock
index 35052c548999..027e70019fa4 100644
--- a/rust/Cargo.lock
+++ b/rust/Cargo.lock
@@ -2904,6 +2904,13 @@ dependencies = [
"uuid",
]
+[[package]]
+name = "common-kafka-consumer"
+version = "0.1.0"
+dependencies = [
+ "rdkafka",
+]
+
[[package]]
name = "common-liveness"
version = "0.1.0"
@@ -6158,6 +6165,7 @@ dependencies = [
"chrono",
"common-alloc",
"common-continuous-profiling",
+ "common-kafka-consumer",
"dashmap 6.1.0",
"envconfig",
"futures",
diff --git a/rust/Cargo.toml b/rust/Cargo.toml
index 0ab087474520..e854bd7b0484 100644
--- a/rust/Cargo.toml
+++ b/rust/Cargo.toml
@@ -21,6 +21,7 @@ members = [
"common/dns",
"common/health",
"common/kafka",
+ "common/kafka-consumer",
"common/liveness",
"common/lifecycle",
"common/limiters",
diff --git a/rust/common/kafka-consumer/Cargo.toml b/rust/common/kafka-consumer/Cargo.toml
new file mode 100644
index 000000000000..5e3630c98dcb
--- /dev/null
+++ b/rust/common/kafka-consumer/Cargo.toml
@@ -0,0 +1,11 @@
+[package]
+name = "common-kafka-consumer"
+version = "0.1.0"
+edition = "2021"
+publish = false
+
+[lints]
+workspace = true
+
+[dependencies]
+rdkafka = { workspace = true }
diff --git a/rust/common/kafka-consumer/README.md b/rust/common/kafka-consumer/README.md
new file mode 100644
index 000000000000..1e293335eb5e
--- /dev/null
+++ b/rust/common/kafka-consumer/README.md
@@ -0,0 +1,10 @@
+# common-kafka-consumer
+
+Kafka consumption primitives shared by stateful services.
+
+## Modules
+
+- `config`: `ConsumerConfigBuilder`, the rdkafka `ClientConfig` builder with PostHog consumer defaults.
+- `types`: `Offset`.
+- `charge`: `Charge`, a message's cost (events and bytes) against consumer admission budgets.
+- `ledger`: `OffsetLedger`, offset accounting scoped to one partition assignment: completion in any order, an observable contiguous frontier, and explicit consumption at commit points.
diff --git a/rust/common/kafka-consumer/src/charge.rs b/rust/common/kafka-consumer/src/charge.rs
new file mode 100644
index 000000000000..75bac14262e1
--- /dev/null
+++ b/rust/common/kafka-consumer/src/charge.rs
@@ -0,0 +1,39 @@
+use std::iter::Sum;
+use std::ops::{Add, AddAssign};
+
+/// A message's cost against later consumer admission budgets.
+#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
+pub struct Charge {
+ pub events: u64,
+ pub bytes: u64,
+}
+
+impl Charge {
+ pub const ZERO: Charge = Charge {
+ events: 0,
+ bytes: 0,
+ };
+}
+
+impl Add for Charge {
+ type Output = Charge;
+
+ fn add(self, rhs: Charge) -> Self::Output {
+ Charge {
+ events: self.events + rhs.events,
+ bytes: self.bytes + rhs.bytes,
+ }
+ }
+}
+
+impl AddAssign for Charge {
+ fn add_assign(&mut self, rhs: Charge) {
+ *self = *self + rhs;
+ }
+}
+
+impl Sum for Charge {
+ fn sum<I: Iterator<Item = Charge>>(iter: I) -> Self {
+ iter.fold(Charge::ZERO, Add::add)
+ }
+}
diff --git a/rust/ingestion-consumer/src/kafka_config.rs b/rust/common/kafka-consumer/src/config.rs
similarity index 93%
rename from rust/ingestion-consumer/src/kafka_config.rs
rename to rust/common/kafka-consumer/src/config.rs
index 6e55c606435e..104b1b4895c9 100644
--- a/rust/ingestion-consumer/src/kafka_config.rs
+++ b/rust/common/kafka-consumer/src/config.rs
@@ -242,6 +242,33 @@ impl ConsumerConfigBuilder {
mod tests {
use super::*;
+ #[test]
+ fn batch_consumer_defaults_are_stable() {
+ let config = ConsumerConfigBuilder::for_batch_consumer("kafka:9092", "g").build();
+
+ let mut entries: Vec<(String, String)> = config
+ .config_map()
+ .iter()
+ .map(|(k, v)| (k.clone(), v.clone()))
+ .collect();
+ entries.sort();
+
+ assert_eq!(
+ entries,
+ [
+ ("enable.auto.commit", "false"),
+ ("enable.auto.offset.store", "false"),
+ ("group.id", "g"),
+ ("heartbeat.interval.ms", "5000"),
+ ("max.poll.interval.ms", "300000"),
+ ("metadata.broker.list", "kafka:9092"),
+ ("session.timeout.ms", "60000"),
+ ("socket.timeout.ms", "10000"),
+ ]
+ .map(|(k, v)| (k.to_string(), v.to_string()))
+ );
+ }
+
#[test]
fn strips_classic_keys_under_consumer_protocol() {
let config = ConsumerConfigBuilder::for_batch_consumer("kafka:9092", "g")
diff --git a/rust/common/kafka-consumer/src/ledger.rs b/rust/common/kafka-consumer/src/ledger.rs
new file mode 100644
index 000000000000..01c6de2039a8
--- /dev/null
+++ b/rust/common/kafka-consumer/src/ledger.rs
@@ -0,0 +1,271 @@
+use std::collections::VecDeque;
+
+use crate::charge::Charge;
+use crate::types::Offset;
+
+#[derive(Debug)]
+struct Slot {
+ complete: bool,
+ charge: Charge,
+}
+
+/// A consumed contiguous prefix: its commit-ready frontier and the charge it
+/// covers.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub struct TakenFrontier {
+ pub offset: Offset,
+ pub charge: Charge,
+}
+
+/// Per-partition offset accounting: record offsets as they are delivered,
+/// complete them in any order, and read the frontier in Kafka's
+/// committed-offset representation. Observing the frontier never changes it;
+/// a commit point consumes it with `take_frontier`.
+///
+/// Charge every record the poll delivers, including records the caller drops
+/// without processing: an omitted offset is indistinguishable from an offset
+/// Kafka never delivered, and the frontier commits past it as if it held no
+/// message.
+///
+/// A ledger lives for one partition assignment: create it on assign, drop it
+/// on revoke. Kafka replays a partition from its committed offset after a
+/// rebalance, so a ledger kept across assignments sees the replay as
+/// duplicate delivery and panics. Completions from a previous assignment's
+/// in-flight work must be discarded before they reach the new ledger; it
+/// never charged those offsets and panics on them too (see the panic
+/// contracts on `charge` and `complete`).
+#[derive(Debug, Default)]
+pub struct OffsetLedger {
+ /// The offset of `slots[0]`; `None` until the first delivery.
+ base_offset: Option<Offset>,
+ /// Number of completed slots at the front of the window, kept current on
+ /// every completion so `frontier` stays O(1).
+ prefix: usize,
+ /// A dense sliding window over one contiguous offset range: `charge`
+ /// appends at the back, `take_frontier` pops the front, and `complete`
+ /// indexes by offset minus `base_offset`. Every operation is amortized constant
+ /// time per offset.
+ slots: VecDeque<Slot>,
+}
+
+impl OffsetLedger {
+ pub fn new() -> Self {
+ Self::default()
+ }
+
+ /// Record offsets in delivery order and return their total charge. An
+ /// offset gap (transaction control records) never blocks the frontier and
+ /// carries no charge.
+ ///
+ /// # Panics
+ ///
+ /// When an offset is not above every offset already recorded. Duplicate
+ /// or out-of-order delivery is a caller bug, and recording it would
+ /// corrupt the commit accounting.
+ pub fn charge(&mut self, offsets: impl IntoIterator<Item = (Offset, Charge)>) -> Charge {
+ let mut total = Charge::ZERO;
+ for (offset, charge) in offsets {
+ let base_offset = *self.base_offset.get_or_insert(offset);
+ let next_offset = base_offset + self.slots.len();
+ assert!(
+ offset >= next_offset,
+ "offset {offset} delivered below the window's next offset {next_offset}"
+ );
+ // A gap becomes pre-completed zero-charge filler so the index
+ // math stays aligned with offsets.
+ for _ in 0..offset - next_offset {
+ self.slots.push_back(Slot {
+ complete: true,
+ charge: Charge::ZERO,
+ });
+ }
+ self.slots.push_back(Slot {
+ complete: false,
+ charge,
+ });
+ total += charge;
+ }
+ total
+ }
+
+ /// Mark delivered offsets complete in any order.
+ ///
+ /// # Panics
+ ///
+ /// When an offset was never charged, was completed before, or was already
+ /// consumed by `take_frontier`. Each case means the completion does not
+ /// belong to this ledger's window, and marking it would corrupt the
+ /// commit accounting.
+ pub fn complete(&mut self, offsets: &[Offset]) {
+ let base_offset = self.base_offset.expect("completion before any delivery");
+ for &offset in offsets {
+ let slot_index =
+ usize::try_from(offset - base_offset).expect("completion below the window base");
+ let slot = self
+ .slots
+ .get_mut(slot_index)
+ .expect("completion for an uncharged offset");
+ assert!(!slot.complete, "offset {offset} completed twice");
+ slot.complete = true;
+ }
+ while self
+ .slots
+ .get(self.prefix)
+ .is_some_and(|slot| slot.complete)
+ {
+ self.prefix += 1;
+ }
+ }
+
+ /// The next offset to read: one past the highest contiguous completed
+ /// offset, in Kafka's committed-offset representation, so a commit uses
+ /// it verbatim. `None` before the first completion.
+ pub fn frontier(&self) -> Option<Offset> {
+ let base_offset = self.base_offset?;
+ (self.prefix > 0).then(|| base_offset + self.prefix)
+ }
+
+ /// Take the frontier and the charge of everything below it, forgetting
+ /// that span. Kept separate from `complete` so that reading the frontier
+ /// has no side effects and only commit points consume it.
+ pub fn take_frontier(&mut self) -> Option<TakenFrontier> {
+ let frontier_offset = self.frontier()?;
+ let charge = self
+ .slots
+ .drain(..self.prefix)
+ .map(|slot| slot.charge)
+ .sum();
+ self.base_offset = Some(frontier_offset);
+ self.prefix = 0;
+ Some(TakenFrontier {
+ offset: frontier_offset,
+ charge,
+ })
+ }
+
+ pub fn len(&self) -> usize {
+ self.slots.len()
+ }
+
+ pub fn is_empty(&self) -> bool {
+ self.slots.is_empty()
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn charge(offset: i64) -> (Offset, Charge) {
+ (
+ Offset(offset),
+ Charge {
+ events: 1,
+ bytes: 10,
+ },
+ )
+ }
+
+ #[test]
+ fn out_of_order_completion_does_not_move_the_frontier() {
+ let mut ledger = OffsetLedger::new();
+ ledger.charge([charge(0), charge(1), charge(2)]);
+ ledger.complete(&[Offset(2)]);
+ assert_eq!(ledger.frontier(), None);
+ assert_eq!(ledger.take_frontier(), None);
+ ledger.complete(&[Offset(0), Offset(1)]);
+ assert_eq!(ledger.frontier(), Some(Offset(3)));
+ }
+
+ #[test]
+ fn a_partial_take_keeps_the_remainder_completable() {
+ let mut ledger = OffsetLedger::new();
+ ledger.charge([charge(0), charge(1), charge(2)]);
+ ledger.complete(&[Offset(0)]);
+ let taken = ledger.take_frontier().unwrap();
+ assert_eq!(taken.offset, Offset(1));
+ assert_eq!(taken.charge.events, 1);
+ assert_eq!(ledger.len(), 2);
+ ledger.complete(&[Offset(1), Offset(2)]);
+ assert_eq!(ledger.frontier(), Some(Offset(3)));
+ assert_eq!(ledger.take_frontier().unwrap().charge.events, 2);
+ }
+
+ #[test]
+ #[should_panic(expected = "delivered below the window's next offset")]
+ fn duplicate_delivery_panics() {
+ let mut ledger = OffsetLedger::new();
+ ledger.charge([charge(0), charge(1)]);
+ ledger.charge([charge(1)]);
+ }
+
+ #[test]
+ #[should_panic(expected = "completed twice")]
+ fn double_completion_panics() {
+ let mut ledger = OffsetLedger::new();
+ ledger.charge([charge(0)]);
+ ledger.complete(&[Offset(0)]);
+ ledger.complete(&[Offset(0)]);
+ }
+
+ #[test]
+ #[should_panic(expected = "completion for an uncharged offset")]
+ fn completing_an_undelivered_offset_panics() {
+ let mut ledger = OffsetLedger::new();
+ ledger.charge([charge(0)]);
+ ledger.complete(&[Offset(5)]);
+ }
+
+ #[test]
+ #[should_panic(expected = "completion below the window base")]
+ fn completing_below_the_window_after_a_take_panics() {
+ let mut ledger = OffsetLedger::new();
+ ledger.charge([charge(0), charge(1)]);
+ ledger.complete(&[Offset(0)]);
+ ledger.take_frontier().unwrap();
+ ledger.complete(&[Offset(0)]);
+ }
+
+ #[test]
+ fn frontier_is_idempotent_and_take_drains_it() {
+ let mut ledger = OffsetLedger::new();
+ ledger.charge([charge(0), charge(1)]);
+ ledger.complete(&[Offset(0), Offset(1)]);
+ assert_eq!(ledger.frontier(), Some(Offset(2)));
+ assert_eq!(ledger.frontier(), Some(Offset(2)));
+ assert_eq!(ledger.take_frontier().unwrap().charge.events, 2);
+ assert_eq!(ledger.len(), 0);
+ }
+
+ #[test]
+ fn delivery_gaps_do_not_block_delivered_offsets() {
+ let mut ledger = OffsetLedger::new();
+ ledger.charge([charge(0), charge(3)]);
+ ledger.complete(&[Offset(0), Offset(3)]);
+ assert_eq!(ledger.frontier(), Some(Offset(4)));
+ }
+
+ #[test]
+ fn gap_filler_carries_no_charge_and_the_frontier_walks_over_it() {
+ let mut ledger = OffsetLedger::new();
+ ledger.charge([charge(0), charge(3)]);
+ ledger.complete(&[Offset(0)]);
+ assert_eq!(ledger.frontier(), Some(Offset(3)));
+ ledger.complete(&[Offset(3)]);
+ let taken = ledger.take_frontier().unwrap();
+ assert_eq!(taken.offset, Offset(4));
+ assert_eq!(taken.charge.events, 2);
+ }
+
+ #[test]
+ fn the_window_slides_across_take_frontier() {
+ let mut ledger = OffsetLedger::new();
+ ledger.charge([charge(0), charge(1)]);
+ ledger.complete(&[Offset(0), Offset(1)]);
+ ledger.take_frontier().unwrap();
+ ledger.charge([charge(2)]);
+ ledger.complete(&[Offset(2)]);
+ assert_eq!(ledger.frontier(), Some(Offset(3)));
+ assert_eq!(ledger.take_frontier().unwrap().charge.events, 1);
+ }
+}
diff --git a/rust/common/kafka-consumer/src/lib.rs b/rust/common/kafka-consumer/src/lib.rs
new file mode 100644
index 000000000000..177d17f21c3f
--- /dev/null
+++ b/rust/common/kafka-consumer/src/lib.rs
@@ -0,0 +1,11 @@
+//! Kafka consumption primitives shared by stateful services.
+
+pub mod charge;
+pub mod config;
+pub mod ledger;
+pub mod types;
+
+pub use charge::Charge;
+pub use config::ConsumerConfigBuilder;
+pub use ledger::{OffsetLedger, TakenFrontier};
+pub use types::Offset;
diff --git a/rust/common/kafka-consumer/src/types.rs b/rust/common/kafka-consumer/src/types.rs
new file mode 100644
index 000000000000..878b09b78aa3
--- /dev/null
+++ b/rust/common/kafka-consumer/src/types.rs
@@ -0,0 +1,28 @@
+use std::fmt;
+use std::ops::{Add, Sub};
+
+/// A Kafka message offset.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
+pub struct Offset(pub i64);
+
+impl Sub for Offset {
+ type Output = i64;
+
+ fn sub(self, rhs: Offset) -> i64 {
+ self.0 - rhs.0
+ }
+}
+
+impl Add<usize> for Offset {
+ type Output = Offset;
+
+ fn add(self, rhs: usize) -> Offset {
+ Offset(self.0 + rhs as i64)
+ }
+}
+
+impl fmt::Display for Offset {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ write!(f, "{}", self.0)
+ }
+}
diff --git a/rust/ingestion-consumer/Cargo.toml b/rust/ingestion-consumer/Cargo.toml
index 640067a89274..4c6895c1f109 100644
--- a/rust/ingestion-consumer/Cargo.toml
+++ b/rust/ingestion-consumer/Cargo.toml
@@ -9,6 +9,7 @@ axum = { workspace = true }
chrono = { workspace = true }
common-alloc = { path = "../common/alloc" }
common-continuous-profiling = { path = "../common/continuous_profiling" }
+common-kafka-consumer = { path = "../common/kafka-consumer" }
dashmap = { workspace = true }
envconfig = { workspace = true }
futures = { workspace = true }
diff --git a/rust/ingestion-consumer/src/config.rs b/rust/ingestion-consumer/src/config.rs
index d8f0b17919c4..fd6e7aee586d 100644
--- a/rust/ingestion-consumer/src/config.rs
+++ b/rust/ingestion-consumer/src/config.rs
@@ -4,8 +4,8 @@ use rdkafka::ClientConfig;
use tracing::info;
use crate::discovery::DiscoveryMode;
-use crate::kafka_config::ConsumerConfigBuilder;
use crate::routing::RoutingStrategy;
+use common_kafka_consumer::config::ConsumerConfigBuilder;
/// Configuration for the ingestion consumer.
///
diff --git a/rust/ingestion-consumer/src/lib.rs b/rust/ingestion-consumer/src/lib.rs
index 1b29911adcfc..7b934c76f685 100644
--- a/rust/ingestion-consumer/src/lib.rs
+++ b/rust/ingestion-consumer/src/lib.rs
@@ -5,7 +5,6 @@ pub mod debug_recorder;
pub mod discovery;
pub mod dispatcher;
pub mod grpc_transport;
-pub mod kafka_config;
pub mod kafka_stats;
pub mod order_sentinel;
pub mod readiness;