: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(batch-import): split capture batches over the 10 MiB limit (#66676)
José Sequeira1dac8eab9ddd
diff --git a/rust/batch-import-worker/src/emit/capture.rs b/rust/batch-import-worker/src/emit/capture.rsindex 80179b61de45..ff5ceccd5569 100644--- a/rust/batch-import-worker/src/emit/capture.rs+++ b/rust/batch-import-worker/src/emit/capture.rs@@ -1,4 +1,5 @@use std::{+ io::{self, Write},sync::Mutex,time::{Duration, Instant},};@@ -8,7 +9,7 @@ use async_trait::async_trait;use common_types::{InternallyCapturedEvent, RawEvent};use metrics::counter;use posthog_rs::{Client, Event};-use tracing::info;+use tracing::{info, warn};use super::{Emitter, Transaction};@@ -106,27 +107,39 @@ impl<'a> Transaction<'a> for CaptureTransaction<'a> {let txn_elapsed = self.start.elapsed();let to_sleep = min_duration.saturating_sub(txn_elapsed);+ // Split into sub-batches under capture's 10 MiB body limit. Capture rejects an+ // over-limit batch without producing anything to Kafka, so the size failure this+ // prevents never half-commits a chunk. Capture does not dedupe by UUID alone (events+ // without a source id get a fresh UUID per parse): if a later sub-batch fails after+ // earlier ones were accepted, the offset rollback re-sends the whole chunk and+ // re-delivers the accepted events — bounded over-delivery we accept over skipping data.+ let batches = split_into_byte_limited_batches(events)?;+info!(count,+ batches = batches.len(),?txn_elapsed,?min_duration,?to_sleep,"sending events to capture");- match self.client.capture_batch(events, true).await {- Ok(()) => {- counter!("capture_batch_events_total", "outcome" => "success")- .increment(count as u64);- info!(count, "successfully sent batch to capture");- Ok(to_sleep)- }- Err(e) => {+ for batch in batches {+ let batch_count = batch.len();+ if let Err(e) = self.client.capture_batch(batch, true).await {counter!("capture_batch_events_total", "outcome" => "failure")- .increment(count as u64);- Err(Error::msg(format!("capture batch failed: {e}")))+ .increment(batch_count as u64);+ return Err(Error::msg(format!("capture batch failed: {e}")));}}++ // Count success once per fully-committed chunk. A mid-chunk failure rolls the offset+ // back and re-sends the whole chunk on retry, so counting per sub-batch would inflate+ // the success total across retries.+ counter!("capture_batch_events_total", "outcome" => "success").increment(count as u64);++ info!(count, "successfully sent batch to capture");+ Ok(to_sleep)}}@@ -136,6 +149,79 @@ fn get_min_txn_duration(send_rate: u64, count: usize) -> Duration {Duration::from_secs_f64(batch_size / max_send_rate)}+/// Capture's `/batch/` endpoint rejects any request body larger than 10 MiB with+/// `payload_too_large`. We pack events into sub-batches that stay under this budget so a+/// chunk whose serialized events exceed the limit is split across several requests+/// instead of wedging the import. The headroom below 10 MiB absorbs the batch envelope+/// and the per-event `api_key` / `$lib*` fields capture injects into each event.+const MAX_BATCH_PAYLOAD_BYTES: usize = 9 * 1024 * 1024;++/// Overhead capture adds per event beyond its own JSON (injected `api_key`, `$lib*`+/// properties and separators). Counted toward every event so a flood of tiny events+/// can't accumulate past the wire limit.+const PER_EVENT_OVERHEAD_BYTES: usize = 256;++/// Greedily pack events into batches whose estimated serialized size stays under+/// [`MAX_BATCH_PAYLOAD_BYTES`], preserving order. A single event larger than the budget+/// gets its own batch — best effort, since capture may still reject it, but that is a+/// genuinely oversized event rather than an aggregation problem.+fn split_into_byte_limited_batches(events: Vec<Event>) -> Result<Vec<Vec<Event>>, Error> {+ let mut batches: Vec<Vec<Event>> = Vec::new();+ let mut current: Vec<Event> = Vec::new();+ let mut current_bytes: usize = 0;++ for event in events {+ let event_bytes = serialized_len(&event)?.saturating_add(PER_EVENT_OVERHEAD_BYTES);++ if !current.is_empty()+ && current_bytes.saturating_add(event_bytes) > MAX_BATCH_PAYLOAD_BYTES+ {+ batches.push(std::mem::take(&mut current));+ current_bytes = 0;+ }++ if event_bytes > MAX_BATCH_PAYLOAD_BYTES {+ warn!(+ event_bytes,+ limit = MAX_BATCH_PAYLOAD_BYTES,+ "single event exceeds capture batch size limit; sending it in its own request"+ );+ }++ current.push(event);+ current_bytes = current_bytes.saturating_add(event_bytes);+ }++ if !current.is_empty() {+ batches.push(current);+ }++ Ok(batches)+}++/// Serialized JSON byte length of `event`, measured without retaining the bytes:+/// `serde_json::to_writer` into a counting sink, so sizing a multi-MB event doesn't+/// allocate a multi-MB buffer just to read its length.+fn serialized_len(event: &Event) -> Result<usize, Error> {+ let mut counter = ByteCountWriter(0);+ serde_json::to_writer(&mut counter, event)+ .map_err(|e| Error::msg(format!("failed to size event for batching: {e}")))?;+ Ok(counter.0)+}++struct ByteCountWriter(usize);++impl Write for ByteCountWriter {+ fn write(&mut self, buf: &[u8]) -> io::Result<usize> {+ self.0 += buf.len();+ Ok(buf.len())+ }++ fn flush(&mut self) -> io::Result<()> {+ Ok(())+ }+}+#[cfg(test)]mod tests {use super::*;@@ -460,4 +546,91 @@ mod tests {assert!(result.is_err());mock.assert();}++ fn padded_event(pad_bytes: usize) -> Event {+ let mut event = Event::new("big", "user1");+ event.insert_prop("pad", "x".repeat(pad_bytes)).unwrap();+ event+ }++ fn batch_bytes(batch: &[Event]) -> usize {+ batch+ .iter()+ .map(|e| serde_json::to_vec(e).unwrap().len() + PER_EVENT_OVERHEAD_BYTES)+ .sum()+ }++ #[test]+ fn test_split_empty_returns_no_batches() {+ assert!(split_into_byte_limited_batches(vec![]).unwrap().is_empty());+ }++ #[test]+ fn test_split_keeps_small_events_in_one_batch() {+ let events = vec![padded_event(10), padded_event(10), padded_event(10)];+ let batches = split_into_byte_limited_batches(events).unwrap();+ assert_eq!(batches.len(), 1);+ assert_eq!(batches[0].len(), 3);+ }++ #[test]+ fn test_split_breaks_oversized_chunk_into_multiple_batches() {+ // Five ~2.5 MiB events against a 9 MiB budget must span more than one batch.+ let events: Vec<Event> = (0..5).map(|_| padded_event(2_500_000)).collect();+ let total = events.len();++ let batches = split_into_byte_limited_batches(events).unwrap();++ assert!(batches.len() > 1, "expected multiple batches");+ let mut seen = 0;+ for batch in &batches {+ assert!(+ batch_bytes(batch) <= MAX_BATCH_PAYLOAD_BYTES,+ "batch exceeds capture limit"+ );+ seen += batch.len();+ }+ assert_eq!(seen, total, "no events may be dropped while splitting");+ }++ #[test]+ fn test_split_isolates_single_oversized_event() {+ let events = vec![padded_event(10 * 1024 * 1024), padded_event(10)];+ let batches = split_into_byte_limited_batches(events).unwrap();+ assert_eq!(batches.len(), 2);+ assert_eq!(batches[0].len(), 1, "oversized event sent on its own");+ assert_eq!(batches[1].len(), 1);+ }++ #[tokio::test]+ async fn test_commit_write_splits_oversized_chunk_across_requests() {+ let events: Vec<Event> = (0..5).map(|_| padded_event(2_500_000)).collect();+ let expected_requests = split_into_byte_limited_batches(events.clone())+ .unwrap()+ .len();+ assert!(+ expected_requests > 1,+ "test must exercise multiple requests"+ );++ let mut server = mockito::Server::new_async().await;+ let mock = server+ .mock("POST", "/i/v1/analytics/events")+ .with_status(200)+ .with_body(V1_OK_BODY)+ .expect(expected_requests)+ .create();++ let client = make_client(&server.url()).await;+ let txn = Box::new(CaptureTransaction {+ client: &client,+ send_rate: 10_000,+ start: Instant::now(),+ events: Mutex::new(events),+ });++ let result = txn.commit_write().await;+ assert!(result.is_ok(), "got {result:?}");+ mock.assert();+ }}diff --git a/rust/batch-import-worker/src/job/mod.rs b/rust/batch-import-worker/src/job/mod.rsindex 5245e45d047b..7b08fe9afe5a 100644--- a/rust/batch-import-worker/src/job/mod.rs+++ b/rust/batch-import-worker/src/job/mod.rs@@ -509,16 +509,25 @@ impl Job {info!(job_id = %self.job_id, "Writing {} events", parsed.data.len());self.shutdown_guard()?;txn.emit(&parsed.data).await?;- // Two-stage commit: pause the job in PG before committing to the sink, so that if we- // crash between the two, the job is paused and requires manual intervention rather than- // silently skipping a chunk. The operator can confirm whether the sink commit succeeded- // by looking at the last event written or the logs.+ // Two-stage commit: advance the offset and pause the job in PG *before* committing to+ // the sink. If we crash between the two, the job is left paused at the advanced offset+ // and requires manual intervention rather than silently skipping a chunk — the operator+ // confirms whether the sink commit landed via the last event written or the logs.self.shutdown_guard()?;info!(job_id = %self.job_id, "Beginning PG part commit");self.begin_part_commit(&key, parsed.consumed).await?;info!(job_id = %self.job_id, "Beginning emitter part commit");- let to_sleep = txn.commit_write().await?;+ // A *returned* error (as opposed to a crash) means the sink definitively rejected the+ // chunk, so the speculative offset advance above is wrong: roll it back and record the+ // real error, so a resume re-processes the chunk instead of skipping it.+ let to_sleep = match txn.commit_write().await {+ Ok(to_sleep) => to_sleep,+ Err(e) => {+ self.rollback_part_commit(&key, parsed.consumed, &e).await?;+ return Err(e);+ }+ };info!(job_id = %self.job_id, "Finishing PG part commit");self.complete_commit().await?;info!(job_id = %self.job_id, "Committed part {} consumed {} bytes", key, parsed.consumed);@@ -548,16 +557,12 @@ impl Job {return Err(Error::msg("No model state found"));};- // Iterate through the parts list and update the relevant part- let Some(part) = model_state.parts.iter_mut().find(|p| p.key == key) else {+ let Some(new_offset) = model_state.advance_part_offset(key, consumed as u64) else {return Err(Error::msg(format!("No part found with key {key}")));};- part.current_offset += consumed as u64;-let status_message = format!(- "Starting commit of part {} to offset {}, consumed {} additional bytes",- key, part.current_offset, consumed+ "Starting commit of part {key} to offset {new_offset}, consumed {consumed} additional bytes");model@@ -569,6 +574,36 @@ impl Job {.await}+ // Reverts the speculative offset advance from begin_part_commit after a definitive sink+ // rejection, leaving the job paused with the real error and the original offset, so a resume+ // re-processes the chunk rather than skipping it.+ async fn rollback_part_commit(+ &self,+ key: &str,+ consumed: usize,+ err: &Error,+ ) -> Result<(), Error> {+ let mut model = self.model.lock().await;+ let Some(model_state) = &mut model.state else {+ return Err(Error::msg("No model state found"));+ };++ let Some(new_offset) = model_state.revert_part_offset(key, consumed as u64) else {+ return Err(Error::msg(format!("No part found with key {key}")));+ };++ let status_message =+ format!("Commit of part {key} failed, rolled back to offset {new_offset}: {err:#}");++ model+ .pause(+ self.context.clone(),+ status_message,+ Some("Job paused after a failed commit. Resolve the error and resume.".to_string()),+ )+ .await+ }+// Unpauses the jobasync fn complete_commit(&self) -> Result<(), Error> {let mut model = self.model.lock().await;diff --git a/rust/batch-import-worker/src/job/model.rs b/rust/batch-import-worker/src/job/model.rsindex ad4c9186d99c..d0b217203d1d 100644--- a/rust/batch-import-worker/src/job/model.rs+++ b/rust/batch-import-worker/src/job/model.rs@@ -74,6 +74,25 @@ impl PartState {}}+impl JobState {+ /// Advance the named part's offset by `consumed` bytes, returning the new offset.+ /// Returns `None` if no part matches `key`.+ pub fn advance_part_offset(&mut self, key: &str, consumed: u64) -> Option<u64> {+ let part = self.parts.iter_mut().find(|p| p.key == key)?;+ part.current_offset = part.current_offset.saturating_add(consumed);+ Some(part.current_offset)+ }++ /// Revert the named part's offset by `consumed` bytes — the inverse of+ /// [`advance_part_offset`](Self::advance_part_offset), saturating at 0. Returns the new+ /// offset, or `None` if no part matches `key`.+ pub fn revert_part_offset(&mut self, key: &str, consumed: u64) -> Option<u64> {+ let part = self.parts.iter_mut().find(|p| p.key == key)?;+ part.current_offset = part.current_offset.saturating_sub(consumed);+ Some(part.current_offset)+ }+}+impl JobModel {pub async fn claim_next_job(context: Arc<AppContext>) -> Result<Option<JobModel>, Error> {// We use select for update to lock a row, then update it, returning the updated row@@ -464,6 +483,49 @@ mod tests {}}+ fn make_job_state(parts: &[(&str, u64)]) -> JobState {+ JobState {+ parts: parts+ .iter()+ .map(|(key, offset)| PartState {+ key: key.to_string(),+ current_offset: *offset,+ total_size: None,+ })+ .collect(),+ }+ }++ #[test]+ fn test_advance_part_offset_increments_and_returns_new_offset() {+ let mut state = make_job_state(&[("a", 100), ("b", 0)]);+ assert_eq!(state.advance_part_offset("a", 50), Some(150));+ assert_eq!(state.parts[0].current_offset, 150);+ assert_eq!(state.parts[1].current_offset, 0, "other parts untouched");+ }++ #[test]+ fn test_revert_part_offset_is_inverse_of_advance() {+ let mut state = make_job_state(&[("a", 100)]);+ let advanced = state.advance_part_offset("a", 4242).unwrap();+ assert_eq!(state.revert_part_offset("a", 4242), Some(advanced - 4242));+ assert_eq!(state.parts[0].current_offset, 100);+ }++ #[test]+ fn test_revert_part_offset_saturates_at_zero() {+ let mut state = make_job_state(&[("a", 10)]);+ assert_eq!(state.revert_part_offset("a", 999), Some(0));+ assert_eq!(state.parts[0].current_offset, 0);+ }++ #[test]+ fn test_offset_helpers_return_none_for_unknown_key() {+ let mut state = make_job_state(&[("a", 0)]);+ assert_eq!(state.advance_part_offset("missing", 1), None);+ assert_eq!(state.revert_part_offset("missing", 1), None);+ }+#[tokio::test]async fn test_schedule_backoff_persists_db() -> Result<(), anyhow::Error> {let Some(pool) = get_pool().await else {