: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(ingestion): split oversize batches instead of retrying them forever (#74531)
José Sequeirae15b76f34500
diff --git a/nodejs/src/common/api/body-limit.test.ts b/nodejs/src/common/api/body-limit.test.tsnew file mode 100644index 000000000000..b57a1925ceb6--- /dev/null+++ b/nodejs/src/common/api/body-limit.test.ts@@ -0,0 +1,43 @@+import supertest from 'supertest'+import type { Application, Request, Response } from 'ultimate-express'++import { setupExpressApp } from '~/common/api/router'++describe('setupExpressApp JSON body limit', () => {+ let app: Application+ let server: ReturnType<Application['listen']>++ beforeAll(() => {+ app = setupExpressApp({ jsonBodyLimit: '1kb' })+ app.post('/echo', (req: Request, res: Response) => {+ res.status(200).json({ ok: true })+ })+ server = app.listen(0, () => {})+ })++ afterAll(() => {+ // Fire-and-forget close, matching ServerLifecycle.stop — ultimate-express+ // never invokes the close callback, so awaiting it would hang.+ server.close()+ })++ // ultimate-express rejects an oversized body with a plain Error, which the+ // default handler renders as a 500. The Rust ingestion consumer treats 500+ // as retriable, so an oversized batch would retry forever — the 413 tells+ // it to split the payload instead.+ it('rejects an oversized JSON body with 413, not 500', async () => {+ const res = await supertest(app)+ .post('/echo')+ .send({ data: 'x'.repeat(2048) })++ expect(res.status).toEqual(413)+ expect(res.body).toEqual({ status: 'error', error: 'Request entity too large' })+ })++ it('accepts a JSON body under the limit', async () => {+ const res = await supertest(app).post('/echo').send({ data: 'x' })++ expect(res.status).toEqual(200)+ expect(res.body).toEqual({ ok: true })+ })+})diff --git a/nodejs/src/common/api/router.ts b/nodejs/src/common/api/router.tsindex c396d0ff8051..b59314feaaf6 100644--- a/nodejs/src/common/api/router.ts+++ b/nodejs/src/common/api/router.ts@@ -1,5 +1,5 @@import * as prometheus from 'prom-client'-import express, { Request, Response } from 'ultimate-express'+import express, { NextFunction, Request, Response } from 'ultimate-express'import { corsMiddleware } from '~/common/api/middleware/cors'import { httpMetricsMiddleware } from '~/common/api/middleware/http-metrics'@@ -29,6 +29,8 @@ export interface SetupExpressAppOptions {internalApiSecret?: string// Comma-separated previous secrets still accepted for verification during rotation.internalApiSecretFallbacks?: string+ // JSON body size limit, e.g. '20mb'. Overridable in tests.+ jsonBodyLimit?: string}export function setupCommonRoutes(@@ -66,13 +68,27 @@ export function setupExpressApp(options: SetupExpressAppOptions = {}): express.Aapp.use(express.json({- limit: '20mb',+ limit: options.jsonBodyLimit ?? '20mb',verify: (req, res, buf) => {;(req as any).rawBody = buf.toString('utf8')},}))+ // ultimate-express reports an oversized body as a plain Error with no+ // status, which the default handler renders as a 500 — indistinguishable+ // from a worker crash for callers deciding whether to retry. Answer 413 so+ // clients (the Rust ingestion consumer) split the payload instead of+ // retrying it verbatim. Also match express-style body-parser errors+ // (status 413 / type entity.too.large) for compatibility.+ app.use((err: any, _req: Request, res: Response, next: NextFunction) => {+ if (err?.message === 'Request entity too large' || err?.status === 413 || err?.type === 'entity.too.large') {+ res.status(413).json({ status: 'error', error: 'Request entity too large' })+ return+ }+ next(err)+ })+return app}diff --git a/rust/ingestion-consumer/src/config.rs b/rust/ingestion-consumer/src/config.rsindex 8999d98fa4ae..3dc1e6e66f27 100644--- a/rust/ingestion-consumer/src/config.rs+++ b/rust/ingestion-consumer/src/config.rs@@ -203,6 +203,14 @@ pub struct Config {#[envconfig(from = "INGESTION_TRANSPORT_COMPRESSION_ENABLED", default = "true")]pub transport_compression_enabled: bool,+ /// Cap on the serialized JSON size of one /ingest request body (bytes).+ /// Sub-batches above it are split into multiple sequential requests. Must+ /// stay under the worker's HTTP body limit (20 MB) with headroom for the+ /// size estimate; a request the worker still rejects with 413 is halved+ /// and resent. Default 10 MiB.+ #[envconfig(from = "INGESTION_TRANSPORT_MAX_BODY_BYTES", default = "10485760")]+ pub transport_max_body_bytes: usize,+/// Shared secret for authenticating with Node.js workers (X-Internal-Api-Secret header)#[envconfig(default = "")]pub internal_api_secret: String,diff --git a/rust/ingestion-consumer/src/main.rs b/rust/ingestion-consumer/src/main.rsindex 4ee0adbbd232..388ed15b9a40 100644--- a/rust/ingestion-consumer/src/main.rs+++ b/rust/ingestion-consumer/src/main.rs@@ -238,6 +238,7 @@ async fn async_main(config: Config) -> Result<()> {config.ingestion_worker_concurrent_batches,config.transport_compression_enabled,);+ transport.set_max_body_bytes(config.transport_max_body_bytes);if let Some(recorder) = &debug_recorder {transport.set_debug_recorder(Arc::clone(recorder));}diff --git a/rust/ingestion-consumer/src/transport.rs b/rust/ingestion-consumer/src/transport.rsindex 81c4ad8b89a3..386e34545e33 100644--- a/rust/ingestion-consumer/src/transport.rs+++ b/rust/ingestion-consumer/src/transport.rs@@ -1,3 +1,4 @@+use std::collections::VecDeque;use std::io::Write;use std::sync::Arc;use std::time::Duration;@@ -13,6 +14,11 @@ use tracing::{error, info, warn};use crate::debug_recorder::{record_if, DebugEventKind, DebugRecorder};use crate::types::{IngestBatchRequest, IngestBatchResponse, SerializedKafkaMessage};+/// Default cap on the serialized JSON size of one /ingest request body. The+/// worker's HTTP body limit is 20 MB; half that leaves headroom for the+/// per-message size estimate (which ignores JSON string escaping).+pub const DEFAULT_MAX_BODY_BYTES: usize = 10 * 1024 * 1024;+/// RAII guard that tracks the number of batches currently in flight to a/// worker. Increments the gauge on creation and decrements on drop, so every/// `send_batch` return path (success, error, retries exhausted, panic unwind)@@ -69,6 +75,10 @@ pub struct HttpTransport {/// Process-unique sender id stamped on every request, so the worker-side/// feed-order sentinel can rebaseline when the consumer restarts.consumer_id: String,+ /// Cap on the serialized JSON size of one request body. Sub-batches whose+ /// estimated size exceeds it are split into multiple sequential requests;+ /// a request the worker still rejects with 413 is halved and resent.+ max_body_bytes: usize,/// Debug event recorder; `None` unless `DEBUG_API_ENABLED`.debug_recorder: Option<Arc<DebugRecorder>>,}@@ -111,6 +121,7 @@ impl HttpTransport {worker_concurrent_batches,compression_enabled,consumer_id: make_consumer_id(),+ max_body_bytes: DEFAULT_MAX_BODY_BYTES,debug_recorder: None,}}@@ -120,6 +131,12 @@ impl HttpTransport {self.debug_recorder = Some(recorder);}+ /// Override the request body size cap. Call before the transport is shared.+ pub fn set_max_body_bytes(&mut self, bytes: usize) {+ assert!(bytes > 0, "max_body_bytes must be > 0");+ self.max_body_bytes = bytes;+ }+/// Get the worker's concurrency semaphore, creating it on first use so the/// transport serves workers added at runtime without explicit registration.fn semaphore_for(&self, worker_url: &str) -> Arc<Semaphore> {@@ -187,6 +204,16 @@ impl HttpTransport {/// here — that's the natural backpressure. The permit is released on/// drop, covering all return paths (success, retriable error, retries/// exhausted, non-retriable error).+ ///+ /// A sub-batch whose estimated body size exceeds `max_body_bytes` is split+ /// into multiple sequential requests (order-preserving, under the same+ /// permit). A request the worker still rejects with 413 is halved and+ /// resent; a single message the worker rejects with 413 is a non-retriable+ /// failure. The result stays all-or-nothing: `Ok` only when every chunk was+ /// accepted, and on any failure the `SendError` carries back the full+ /// original message set — already-accepted chunks may then be re-sent+ /// later, which is ordinary at-least-once replay.+ ////// `replay` marks a request that may repeat previously sent messages (a/// deferred-flush re-route); HTTP retries within this call are marked as/// replays automatically.@@ -197,16 +224,6 @@ impl HttpTransport {messages: Vec<SerializedKafkaMessage>,replay: bool,) -> Result<u32, SendError> {- let message_count = messages.len();- let mut request = IngestBatchRequest {- batch_id: batch_id.to_string(),- messages,- consumer_id: self.consumer_id.clone(),- replay,- };-- let url = format!("{worker_url}/ingest");-let semaphore = self.semaphore_for(worker_url);// Atomic "did we actually have to wait?" check. `available_permits`@@ -232,6 +249,83 @@ impl HttpTransport {// worker. The guard decrements the gauge on every return path.let _in_flight = InFlightGuard::new(worker_url);+ let mut queue: VecDeque<Vec<SerializedKafkaMessage>> =+ split_by_size(messages, self.max_body_bytes).into();+ if queue.len() > 1 {+ counter!(+ "ingestion_consumer_transport_batch_splits_total",+ "reason" => "size_estimate"+ )+ .increment((queue.len() - 1) as u64);+ }++ let mut sent: Vec<SerializedKafkaMessage> = Vec::new();+ let mut accepted_total = 0u32;+ while let Some(chunk) = queue.pop_front() {+ match self.send_chunk(worker_url, batch_id, chunk, replay).await {+ ChunkOutcome::Accepted { accepted, messages } => {+ accepted_total += accepted;+ sent.extend(messages);+ }+ ChunkOutcome::TooLarge { messages } if messages.len() > 1 => {+ // The estimate undershot the worker's body limit — halve+ // the chunk and resend both parts, front of the queue so+ // message order is preserved.+ counter!(+ "ingestion_consumer_transport_batch_splits_total",+ "reason" => "http_413"+ )+ .increment(1);+ let mut left = messages;+ let right = left.split_off(left.len() / 2);+ queue.push_front(right);+ queue.push_front(left);+ }+ ChunkOutcome::TooLarge { messages } => {+ // A single message the worker refuses can never succeed by+ // splitting or retrying.+ error!(+ worker = %worker_url,+ batch_id = %batch_id,+ "Worker rejected a single message as too large"+ );+ return Err(SendError {+ error: TransportError::PayloadTooLarge(String::new()),+ messages: reassemble(sent, messages, queue),+ });+ }+ ChunkOutcome::Failed { error, messages } => {+ return Err(SendError {+ error,+ messages: reassemble(sent, messages, queue),+ });+ }+ }+ }++ Ok(accepted_total)+ }++ /// Send one already-size-bounded chunk with the retry loop. Ownership of+ /// the messages travels through the outcome so the caller can split or+ /// re-defer them.+ async fn send_chunk(+ &self,+ worker_url: &str,+ batch_id: &str,+ messages: Vec<SerializedKafkaMessage>,+ replay: bool,+ ) -> ChunkOutcome {+ let message_count = messages.len();+ let mut request = IngestBatchRequest {+ batch_id: batch_id.to_string(),+ messages,+ consumer_id: self.consumer_id.clone(),+ replay,+ };++ let url = format!("{worker_url}/ingest");+let mut last_err = None;// Whether the previous attempt failed with a 503. A busy worker gets a// longer, jittered backoff so callers don't retry it in lockstep.@@ -267,7 +361,10 @@ impl HttpTransport {.increment(1);if response.status == "ok" {- return Ok(response.accepted);+ return ChunkOutcome::Accepted {+ accepted: response.accepted,+ messages: request.messages,+ };}last_was_busy = false;@@ -298,11 +395,18 @@ impl HttpTransport {error = %err,"Failed to send batch to worker");+ // 413 is deterministic for this chunk on every worker —+ // hand it back for splitting instead of retrying verbatim.+ if matches!(err, TransportError::PayloadTooLarge(_)) {+ return ChunkOutcome::TooLarge {+ messages: request.messages,+ };+ }if !err.is_retriable() {- return Err(SendError {+ return ChunkOutcome::Failed {error: err,messages: request.messages,- });+ };}last_err = Some(err);}@@ -325,10 +429,10 @@ impl HttpTransport {messages: message_count,error: err.to_string(),});- Err(SendError {+ ChunkOutcome::Failed {error: err,messages: request.messages,- })+ }}async fn do_send(@@ -370,6 +474,14 @@ impl HttpTransport {return Err(TransportError::WorkerBusy(body));}+ // 413 means the body exceeded the worker's HTTP body limit. Every+ // worker enforces the same limit, so retrying elsewhere can't succeed;+ // the caller splits the chunk instead.+ if status == reqwest::StatusCode::PAYLOAD_TOO_LARGE {+ let body = response.text().await.unwrap_or_default();+ return Err(TransportError::PayloadTooLarge(body));+ }+if status.is_client_error() || status.is_server_error() {let body = response.text().await.unwrap_or_default();return Err(TransportError::HttpStatus(status.as_u16(), body));@@ -380,6 +492,80 @@ impl HttpTransport {}}+/// Outcome of sending one size-bounded chunk of a sub-batch.+enum ChunkOutcome {+ Accepted {+ accepted: u32,+ messages: Vec<SerializedKafkaMessage>,+ },+ /// The worker rejected the body with 413 — split and resend, don't retry.+ TooLarge {+ messages: Vec<SerializedKafkaMessage>,+ },+ Failed {+ error: TransportError,+ messages: Vec<SerializedKafkaMessage>,+ },+}++/// Rebuild the sub-batch's full message list, in original order, from the+/// already-sent chunks, the failing chunk, and the not-yet-sent remainder —+/// `send_batch`'s failure contract hands the whole sub-batch back to the+/// caller for deferral.+fn reassemble(+ mut sent: Vec<SerializedKafkaMessage>,+ failed: Vec<SerializedKafkaMessage>,+ queue: VecDeque<Vec<SerializedKafkaMessage>>,+) -> Vec<SerializedKafkaMessage> {+ sent.extend(failed);+ for chunk in queue {+ sent.extend(chunk);+ }+ sent+}++/// Approximate serialized JSON size of one message within the batch body.+/// Field names and punctuation are a small constant; escaping of the embedded+/// JSON text is absorbed by the headroom between the split cap and the+/// worker's hard body limit (and by the 413 halving fallback).+fn approx_message_size(msg: &SerializedKafkaMessage) -> usize {+ const PER_MESSAGE_OVERHEAD: usize = 96;+ msg.topic.len()+ + msg.key.as_deref().map_or(0, str::len)+ + msg.value.as_deref().map_or(0, str::len)+ + msg+ .headers+ .iter()+ .map(|(k, v)| k.len() + v.len() + 8)+ .sum::<usize>()+ + PER_MESSAGE_OVERHEAD+}++/// Split a sub-batch into chunks whose estimated serialized size stays under+/// `max_body_bytes`, preserving message order. A single message estimated+/// above the cap gets its own chunk — it can't be split further.+fn split_by_size(+ messages: Vec<SerializedKafkaMessage>,+ max_body_bytes: usize,+) -> Vec<Vec<SerializedKafkaMessage>> {+ let mut chunks = Vec::new();+ let mut current = Vec::new();+ let mut current_size = 0usize;+ for msg in messages {+ let size = approx_message_size(&msg);+ if !current.is_empty() && current_size + size > max_body_bytes {+ chunks.push(std::mem::take(&mut current));+ current_size = 0;+ }+ current_size += size;+ current.push(msg);+ }+ if !current.is_empty() {+ chunks.push(current);+ }+ chunks+}+/// Failure from [`HttpTransport::send_batch`], carrying back the batch's/// messages so the caller can defer/replay them (the worker may have died/// mid-send and the messages were never accepted).@@ -400,6 +586,9 @@ pub enum TransportError {#[error("Worker busy (HTTP 503): {0}")]WorkerBusy(String),+ #[error("Request body too large (HTTP 413): {0}")]+ PayloadTooLarge(String),+#[error("Worker returned HTTP {0}: {1}")]HttpStatus(u16, String),@@ -422,6 +611,7 @@ impl TransportError {TransportError::Http(_) => true,TransportError::Serialize(_) => false,TransportError::WorkerBusy(_) => true,+ TransportError::PayloadTooLarge(_) => false,TransportError::WorkerError(_) => true,TransportError::RetriesExhausted => false,}@@ -479,9 +669,63 @@ mod tests {#[test]fn test_client_errors_are_not_retriable() {assert!(!TransportError::HttpStatus(400, "bad".into()).is_retriable());+ assert!(!TransportError::PayloadTooLarge("too big".into()).is_retriable());assert!(!TransportError::RetriesExhausted.is_retriable());}+ fn message_with_value(offset: i64, value_len: usize) -> SerializedKafkaMessage {+ SerializedKafkaMessage {+ topic: "t".to_string(),+ partition: 0,+ offset,+ timestamp: 0,+ key: None,+ value: Some("x".repeat(value_len)),+ headers: std::collections::HashMap::new(),+ }+ }++ #[test]+ fn test_split_by_size_respects_cap_and_preserves_order() {+ let messages: Vec<_> = (0..10).map(|i| message_with_value(i, 1000)).collect();+ // Each message estimates to ~1100 bytes, so a 2500-byte cap fits two.+ let chunks = split_by_size(messages, 2500);++ assert!(+ chunks.len() >= 5,+ "expected >= 5 chunks, got {}",+ chunks.len()+ );+ for chunk in &chunks {+ let size: usize = chunk.iter().map(approx_message_size).sum();+ assert!(size <= 2500, "chunk exceeds cap: {size}");+ }+ let offsets: Vec<i64> = chunks.iter().flatten().map(|m| m.offset).collect();+ assert_eq!(offsets, (0..10).collect::<Vec<_>>());+ }++ #[test]+ fn test_split_by_size_isolates_oversize_message() {+ let messages = vec![+ message_with_value(0, 10),+ message_with_value(1, 5000),+ message_with_value(2, 10),+ ];+ let chunks = split_by_size(messages, 1000);++ assert_eq!(chunks.len(), 3);+ assert_eq!(chunks[1].len(), 1);+ assert_eq!(chunks[1][0].offset, 1);+ }++ #[test]+ fn test_split_by_size_single_chunk_when_under_cap() {+ let messages: Vec<_> = (0..3).map(|i| message_with_value(i, 10)).collect();+ let chunks = split_by_size(messages, DEFAULT_MAX_BODY_BYTES);+ assert_eq!(chunks.len(), 1);+ assert_eq!(chunks[0].len(), 3);+ }+#[test]fn test_server_errors_are_retriable() {assert!(TransportError::HttpStatus(500, "boom".into()).is_retriable());diff --git a/rust/ingestion-consumer/tests/transport_integration_test.rs b/rust/ingestion-consumer/tests/transport_integration_test.rsindex 8c7914b9b9f1..441f34d432c0 100644--- a/rust/ingestion-consumer/tests/transport_integration_test.rs+++ b/rust/ingestion-consumer/tests/transport_integration_test.rs@@ -185,6 +185,46 @@ async fn start_slow_worker(serve_worker(app).await}+/// Spin up a mock worker that rejects bodies larger than `limit` bytes with+/// 413 (like the real worker's JSON body limit) and otherwise records the+/// batch and returns OK.+async fn start_size_limited_worker(+ limit: usize,+ received: Arc<Mutex<Vec<IngestBatchRequest>>>,+) -> (String, tokio::task::JoinHandle<()>) {+ let app = Router::new().route(+ "/ingest",+ post({+ let received = received.clone();+ move |body: axum::body::Bytes| {+ let received = received.clone();+ async move {+ if body.len() > limit {+ return (+ axum::http::StatusCode::PAYLOAD_TOO_LARGE,+ "Request entity too large".to_string(),+ )+ .into_response();+ }+ let req: IngestBatchRequest = serde_json::from_slice(&body).unwrap();+ let accepted = req.messages.len() as u32;+ let batch_id = req.batch_id.clone();+ received.lock().unwrap().push(req);+ Json(IngestBatchResponse {+ batch_id,+ status: "ok".to_string(),+ accepted,+ error: None,+ })+ .into_response()+ }+ }+ }),+ );++ serve_worker(app).await+}+#[tokio::test]async fn transport_sends_batch_and_receives_ack() {let received = Arc::new(Mutex::new(Vec::new()));@@ -296,6 +336,107 @@ async fn transport_fails_on_unreachable_worker() {assert!(result.is_err());}+#[tokio::test]+async fn transport_splits_oversized_batch_by_estimate() {+ // A sub-batch whose estimated body size exceeds the cap is split into+ // multiple sequential requests, preserving message order, and the result+ // still reports every message accepted.+ let received = Arc::new(Mutex::new(Vec::new()));+ let (url, _handle) = start_mock_worker(received.clone()).await;++ let urls = vec![url.clone()];+ let mut transport = HttpTransport::new(Duration::from_secs(5), 0, None, &urls, 1, true);+ transport.set_max_body_bytes(3000);++ let value = "x".repeat(1000);+ let messages: Vec<_> = (0..10)+ .map(|i| make_message("tok", "user", i, &value))+ .collect();++ let accepted = transport+ .send_batch(&url, "batch-split", messages, false)+ .await+ .expect("split batch should be fully accepted");+ assert_eq!(accepted, 10);++ let batches = received.lock().unwrap();+ assert!(+ batches.len() > 1,+ "expected multiple requests, got {}",+ batches.len()+ );+ let offsets: Vec<i64> = batches+ .iter()+ .flat_map(|b| &b.messages)+ .map(|m| m.offset)+ .collect();+ assert_eq!(offsets, (0..10).collect::<Vec<_>>());+}++#[tokio::test]+async fn transport_halves_chunk_on_413() {+ // The size estimate can undershoot the worker's body limit. A 413 response+ // must split the chunk in half and resend rather than retrying verbatim+ // (which would loop forever) or giving up (which would poison the batch).+ let received = Arc::new(Mutex::new(Vec::new()));+ let (url, _handle) = start_size_limited_worker(2000, received.clone()).await;++ let urls = vec![url.clone()];+ // Compression off so the mock's body-length check sees raw JSON sizes.+ let transport = HttpTransport::new(Duration::from_secs(5), 0, None, &urls, 1, false);++ let value = "x".repeat(700);+ let messages: Vec<_> = (0..4)+ .map(|i| make_message("tok", "user", i, &value))+ .collect();++ let accepted = transport+ .send_batch(&url, "batch-413", messages, false)+ .await+ .expect("batch should succeed after halving on 413");+ assert_eq!(accepted, 4);++ let batches = received.lock().unwrap();+ assert!(+ batches.len() >= 2,+ "expected the batch to be split after 413, got {} request(s)",+ batches.len()+ );+ let offsets: Vec<i64> = batches+ .iter()+ .flat_map(|b| &b.messages)+ .map(|m| m.offset)+ .collect();+ assert_eq!(offsets, (0..4).collect::<Vec<_>>());+}++#[tokio::test]+async fn transport_single_oversize_message_fails_without_splitting() {+ // A single message the worker rejects with 413 can't be split further —+ // the send fails with a non-retriable error carrying the message back.+ let received = Arc::new(Mutex::new(Vec::new()));+ let (url, _handle) = start_size_limited_worker(500, received.clone()).await;++ let urls = vec![url.clone()];+ let transport = HttpTransport::new(Duration::from_secs(5), 3, None, &urls, 1, false);++ let value = "x".repeat(1000);+ let messages = vec![make_message("tok", "user", 0, &value)];++ let err = transport+ .send_batch(&url, "batch-giant", messages, false)+ .await+ .unwrap_err();++ assert!(+ matches!(err.error, TransportError::PayloadTooLarge(_)),+ "expected PayloadTooLarge, got {:?}",+ err.error+ );+ assert_eq!(err.messages.len(), 1);+ assert!(!err.error.is_retriable());+}+#[tokio::test]async fn transport_lazily_creates_semaphore_for_unseeded_worker() {// Dynamic membership: a worker not seeded at construction (discovered at