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): bound consumer batches by payload bytes (#84459)

Paweł Ledwoń27e4c888da95
diff --git a/rust/ingestion-consumer/src/config.rs b/rust/ingestion-consumer/src/config.rs
index 3dc1e6e66f27..87ea4703fc2c 100644
--- a/rust/ingestion-consumer/src/config.rs
+++ b/rust/ingestion-consumer/src/config.rs
@@ -117,6 +117,29 @@ pub struct Config {
#[envconfig(default = "500")]
pub consumer_batch_size: usize,
+ /// Maximum payload bytes to collect before dispatching a batch, in KiB.
+ /// `0` (default) disables the bound, leaving collection count-only.
+ ///
+ /// Resident memory is `CONSUMER_MAX_BACKGROUND_TASKS x batch x event size`,
+ /// doubled while a sub-batch is in flight, so a count-only cap only bounds
+ /// memory if every lane's event size is known and stable. It is not: measured
+ /// mean payloads across analytics lanes span ~1KB to ~43KB, a 45x spread, and
+ /// the same `CONSUMER_BATCH_SIZE` therefore means 45x the memory on one lane
+ /// versus another. This bound restates the limit in the unit that actually
+ /// constrains the pod, so one value is safe everywhere.
+ ///
+ /// Whichever bound is reached first ends collection. The count cap stays
+ /// useful as a downstream-shape guard (worker request size, per-batch
+ /// overhead); this one is the memory guard. Checked before appending, so a
+ /// batch always carries at least one message and overshoot is bounded by a
+ /// single message (itself capped by `fetch.message.max.bytes`).
+ ///
+ /// Default is off so that rolling this image out changes no lane's batch
+ /// composition; lanes opt in where their memory arithmetic is already
+ /// written down.
+ #[envconfig(from = "CONSUMER_BATCH_SIZE_KB", default = "0")]
+ pub consumer_batch_size_kb: usize,
+
/// Maximum time to wait while collecting a batch (milliseconds)
#[envconfig(default = "500")]
pub consumer_batch_timeout_ms: u64,
diff --git a/rust/ingestion-consumer/src/consumer.rs b/rust/ingestion-consumer/src/consumer.rs
index 1407bfc4ba09..d34e420cbfc2 100644
--- a/rust/ingestion-consumer/src/consumer.rs
+++ b/rust/ingestion-consumer/src/consumer.rs
@@ -71,6 +71,9 @@ struct InFlightBatch {
/// Used in integration tests where the Kafka consumer is created externally.
pub struct IngestionConsumerOptions {
pub batch_size: usize,
+ /// Payload-byte bound on a batch; `0` disables it (count-only collection).
+ /// See `Config::consumer_batch_size_kb`.
+ pub batch_size_bytes: usize,
pub batch_timeout: Duration,
pub max_in_flight_batches: usize,
pub group_id: String,
@@ -95,6 +98,7 @@ pub struct IngestionConsumer {
transport: Arc<HttpTransport>,
worker_urls: Vec<String>,
batch_size: usize,
+ batch_size_bytes: usize,
batch_timeout: Duration,
max_in_flight_batches: usize,
deferred_flush_timeout: Duration,
@@ -131,6 +135,7 @@ impl IngestionConsumer {
transport,
worker_urls,
batch_size: options.batch_size,
+ batch_size_bytes: options.batch_size_bytes,
batch_timeout: options.batch_timeout,
max_in_flight_batches: options.max_in_flight_batches.max(1),
deferred_flush_timeout: options.deferred_flush_timeout,
@@ -173,6 +178,7 @@ impl IngestionConsumer {
group = %config.ingestion_consumer_group_id,
workers = worker_urls.len(),
batch_size = config.consumer_batch_size,
+ batch_size_kb = config.consumer_batch_size_kb,
"Kafka consumer subscribed"
);
@@ -184,6 +190,7 @@ impl IngestionConsumer {
transport,
worker_urls,
batch_size: config.consumer_batch_size,
+ batch_size_bytes: config.consumer_batch_size_kb.saturating_mul(1024),
batch_timeout: Duration::from_millis(config.consumer_batch_timeout_ms),
max_in_flight_batches: config.consumer_max_background_tasks.max(1),
deferred_flush_timeout: Duration::from_millis(
@@ -311,6 +318,7 @@ impl IngestionConsumer {
let transport = Arc::clone(&self.transport);
let group_id = self.group_id.clone();
let max_batch_size = self.batch_size;
+ let max_batch_bytes = self.batch_size_bytes;
let handle = tokio::spawn(async move {
Self::process_collected_batch(
@@ -320,6 +328,7 @@ impl IngestionConsumer {
transport,
group_id,
max_batch_size,
+ max_batch_bytes,
)
.await
});
@@ -559,6 +568,7 @@ impl IngestionConsumer {
transport: Arc<HttpTransport>,
group_id: String,
max_batch_size: usize,
+ max_batch_bytes: usize,
) -> anyhow::Result<ProcessedBatch> {
let batch_size = collected.messages.len();
let start = Instant::now();
@@ -574,6 +584,17 @@ impl IngestionConsumer {
.set(batch_size as f64 / max_batch_size as f64);
}
+ // The same ratio against the byte bound. Reported separately because the
+ // two disagree on lanes whose events are large: a count utilization can
+ // sit far below 1.0 while batches are in fact full, simply because the
+ // byte bound (or the prefetch queue behind it) ends collection first.
+ // Reading only the count ratio there invites raising a cap that cannot
+ // be reached. Absent when the byte bound is disabled.
+ if max_batch_bytes > 0 {
+ gauge!("consumer_batch_utilization_bytes", "groupId" => group_id.clone())
+ .set(collected.stats.total_bytes as f64 / max_batch_bytes as f64);
+ }
+
// Batch size distribution — matches Node.js `consumer_batch_size` histogram.
histogram!("consumer_batch_size").record(batch_size as f64);
histogram!("consumer_batch_size_kb").record(collected.stats.total_bytes as f64 / 1024.0);
@@ -697,7 +718,14 @@ impl IngestionConsumer {
Ok(accepted)
}
- /// Collect messages from Kafka up to batch_size or batch_timeout.
+ /// Collect messages from Kafka until the first of `batch_size` messages,
+ /// `batch_size_bytes` of payload (when enabled), or `batch_timeout`.
+ ///
+ /// The byte bound is checked at the top of the loop, where accumulated
+ /// bytes are those of messages already appended: a batch therefore always
+ /// carries at least one message — a single payload larger than the whole
+ /// bound still moves rather than wedging the partition — and overshoot is
+ /// at most one message, itself bounded by `fetch.message.max.bytes`.
async fn collect_batch(&self) -> anyhow::Result<CollectedBatch> {
let mut messages = Vec::with_capacity(self.batch_size);
let mut offsets: HashMap<(String, i32), OffsetSpan> = HashMap::new();
@@ -712,6 +740,11 @@ impl IngestionConsumer {
break;
}
+ if self.batch_size_bytes > 0 && stats.total_bytes >= self.batch_size_bytes {
+ counter!("ingestion_consumer_batches_byte_capped_total").increment(1);
+ break;
+ }
+
let remaining = deadline.saturating_duration_since(Instant::now());
if remaining.is_zero() {
break;
diff --git a/rust/ingestion-consumer/tests/e2e_integration_test.rs b/rust/ingestion-consumer/tests/e2e_integration_test.rs
index ea50a2cbc50b..75d5db2a51bd 100644
--- a/rust/ingestion-consumer/tests/e2e_integration_test.rs
+++ b/rust/ingestion-consumer/tests/e2e_integration_test.rs
@@ -122,6 +122,10 @@ struct FakeWorker {
pub url: String,
/// (distinct_id, seq) pairs in arrival order.
pub received: Arc<Mutex<Vec<(String, usize)>>>,
+ /// Message count of each accepted /ingest request, in arrival order. With a
+ /// single worker and partition a sub-batch is the whole Kafka batch, which
+ /// is what lets the batching-bound tests read batch sizes from here.
+ pub batch_sizes: Arc<Mutex<Vec<usize>>>,
/// Gates /_ready (pool membership). When false the worker leaves the pool.
pub healthy: Arc<AtomicBool>,
/// Gates /ingest only. When false the worker stays ready (in the pool) but
@@ -167,6 +171,7 @@ impl FakeWorker {
async fn start_inner(delivery_log: Option<DeliveryLog>) -> Self {
let received: Arc<Mutex<Vec<(String, usize)>>> = Arc::new(Mutex::new(Vec::new()));
+ let batch_sizes: Arc<Mutex<Vec<usize>>> = Arc::new(Mutex::new(Vec::new()));
let healthy = Arc::new(AtomicBool::new(true));
let ingest_ok = Arc::new(AtomicBool::new(true));
let ack_lost_once = Arc::new(AtomicBool::new(false));
@@ -196,6 +201,7 @@ impl FakeWorker {
"/ingest",
post({
let recv = Arc::clone(&received);
+ let sizes = Arc::clone(&batch_sizes);
let h = Arc::clone(&healthy);
let ingest_ok = Arc::clone(&ingest_ok);
let ack_lost_once = Arc::clone(&ack_lost_once);
@@ -206,6 +212,7 @@ impl FakeWorker {
let delivery_log = delivery_log.clone();
move |AxumJson(req): AxumJson<IngestBatchRequest>| {
let recv = recv.clone();
+ let sizes = sizes.clone();
let h = h.clone();
let ingest_ok = ingest_ok.clone();
let ack_lost_once = ack_lost_once.clone();
@@ -266,6 +273,7 @@ impl FakeWorker {
})
.collect();
recv.lock().unwrap().extend(entries.iter().cloned());
+ sizes.lock().unwrap().push(req.messages.len());
// Record the whole batch as one contiguous slot in the
// shared total order (it was accepted as a unit).
if let Some(log) = &delivery_log {
@@ -315,6 +323,7 @@ impl FakeWorker {
Self {
url,
received,
+ batch_sizes,
healthy,
ingest_ok,
ack_lost_once,
@@ -330,6 +339,11 @@ impl FakeWorker {
self.received.lock().unwrap().len()
}
+ /// Message count of each accepted /ingest request, in arrival order.
+ fn batch_sizes(&self) -> Vec<usize> {
+ self.batch_sizes.lock().unwrap().clone()
+ }
+
/// /ingest requests that have reached this worker (including any held by the gate).
fn arrived_count(&self) -> usize {
self.arrived.load(Ordering::SeqCst)
@@ -435,6 +449,44 @@ impl Harness {
max_in_flight: usize,
deferred_flush_timeout: Duration,
registry_config: WorkerRegistryConfig,
+ ) -> Self {
+ Self::start_inner(
+ topic,
+ partitions,
+ worker_count,
+ max_in_flight,
+ deferred_flush_timeout,
+ registry_config,
+ 0,
+ )
+ .await
+ }
+
+ /// Like `start`, but bounds batch collection by payload bytes as well as
+ /// count (`CONSUMER_BATCH_SIZE_KB`). Single worker and partition, so each
+ /// /ingest request is one whole Kafka batch.
+ async fn start_byte_capped(topic: &str, batch_size_bytes: usize) -> Self {
+ Self::start_inner(
+ topic,
+ 1,
+ 1,
+ 1,
+ Duration::from_secs(60),
+ fast_registry_config(),
+ batch_size_bytes,
+ )
+ .await
+ }
+
+ #[allow(clippy::too_many_arguments)]
+ async fn start_inner(
+ topic: &str,
+ partitions: i32,
+ worker_count: usize,
+ max_in_flight: usize,
+ deferred_flush_timeout: Duration,
+ registry_config: WorkerRegistryConfig,
+ batch_size_bytes: usize,
) -> Self {
create_topic(topic, partitions).await;
@@ -483,6 +535,7 @@ impl Harness {
worker_urls,
IngestionConsumerOptions {
batch_size: 50,
+ batch_size_bytes,
batch_timeout: Duration::from_millis(100),
max_in_flight_batches: max_in_flight,
group_id: "e2e-test".to_string(),
@@ -560,6 +613,7 @@ impl Harness {
worker_urls,
IngestionConsumerOptions {
batch_size: 50,
+ batch_size_bytes: 0,
batch_timeout: Duration::from_millis(100),
max_in_flight_batches: self.max_in_flight,
group_id: "e2e-test".to_string(),
@@ -708,6 +762,84 @@ async fn messages_per_distinct_id_arrive_in_order() {
harness.stop().await;
}
+/// The byte bound ends collection before the count bound when payloads are
+/// large, so batch memory tracks bytes rather than event count.
+///
+/// Twelve 2KiB messages sit far inside the 50-message count cap, so without the
+/// byte bound they batch together; the 4KiB cap admits at most two per batch
+/// (the second crosses it). The count cap alone cannot express that, which is
+/// the regression: a lane whose events are large gets the memory of a full
+/// count batch no matter how the count is tuned.
+#[tokio::test]
+async fn byte_bound_caps_batches_below_the_count_bound() {
+ let topic = format!("e2e-bytecap-{}", Uuid::new_v4());
+ let harness = Harness::start_byte_capped(&topic, 4096).await;
+
+ let producer = make_producer();
+ let payload = vec![b'x'; 2048];
+ for seq in 0..12usize {
+ produce_raw(
+ &producer,
+ &topic,
+ 0,
+ &format!("tok:user-1:{seq}"),
+ &payload,
+ None,
+ )
+ .await;
+ }
+
+ harness.wait_for(12, Duration::from_secs(20)).await;
+
+ let sizes = harness.workers[0].batch_sizes();
+ assert_eq!(
+ sizes.iter().sum::<usize>(),
+ 12,
+ "every message must still be delivered, got batches {sizes:?}"
+ );
+ // A collection timeout can only make a batch smaller, so this holds
+ // regardless of how production interleaves with the 100ms window.
+ assert!(
+ sizes.iter().all(|&n| n <= 2),
+ "no batch may exceed the byte bound by more than one message, got {sizes:?}"
+ );
+
+ harness.stop().await;
+}
+
+/// A single message larger than the whole byte bound still moves.
+///
+/// The bound is checked before appending, so the first message of a batch is
+/// always admitted. Checking after would let one oversized payload produce an
+/// empty batch and wedge its partition — the message can never be skipped, and
+/// no smaller batch can ever contain it.
+#[tokio::test]
+async fn message_larger_than_byte_bound_is_still_delivered() {
+ let topic = format!("e2e-bytecap-oversize-{}", Uuid::new_v4());
+ let harness = Harness::start_byte_capped(&topic, 4096).await;
+
+ let producer = make_producer();
+ produce_raw(
+ &producer,
+ &topic,
+ 0,
+ "tok:user-1:0",
+ &vec![b'x'; 16384],
+ None,
+ )
+ .await;
+
+ harness.wait_for(1, Duration::from_secs(20)).await;
+
+ assert_eq!(
+ harness.workers[0].batch_sizes(),
+ vec![1],
+ "the oversized message must arrive as a batch of one"
+ );
+
+ 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]
@@ -2035,6 +2167,7 @@ async fn second_consumer_joining_the_group_preserves_all_messages() {
worker_urls,
IngestionConsumerOptions {
batch_size: 50,
+ batch_size_bytes: 0,
batch_timeout: Duration::from_millis(100),
max_in_flight_batches: 1,
group_id: "e2e-test".to_string(),
@@ -2112,6 +2245,7 @@ async fn fenced_static_member_exits_on_fatal_error() {
urls,
IngestionConsumerOptions {
batch_size: 50,
+ batch_size_bytes: 0,
batch_timeout: Duration::from_millis(100),
max_in_flight_batches: 1,
group_id: "e2e-test".to_string(),