: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
feat(ingestion-consumer): treat worker 503 as retriable backpressure (#64538)
José Sequeiracf76a83ec716
diff --git a/rust/ingestion-consumer/src/config.rs b/rust/ingestion-consumer/src/config.rsindex 2f56167d370e..3a5d69f94ff9 100644--- a/rust/ingestion-consumer/src/config.rs+++ b/rust/ingestion-consumer/src/config.rs@@ -127,12 +127,15 @@ pub struct Config {#[envconfig(default = "3")]pub max_retries: u32,- /// Maximum in-flight batches per worker. MUST match- /// `INGESTION_WORKER_CONCURRENT_BATCHES` on the Node.js side, which is- /// passed into `BatchingPipeline.concurrentBatches`. The consumer caps- /// itself via a per-worker `Semaphore`; the worker still responds 503- /// if it sees `feed()` rejection, so any divergence is observable via- /// `ingestion_api_batch_capacity_rejections_total`.+ /// Soft cap on in-flight batches per worker, enforced by a per-worker+ /// `Semaphore`. Ideally aligned with the worker's+ /// `BatchingPipeline.concurrentBatches` (`INGESTION_WORKER_CONCURRENT_BATCHES`+ /// on the Node.js side) so the happy path backpressures by waiting for a+ /// permit before the worker fills up. It need not match exactly: if the+ /// worker still responds 503, the transport treats it as retriable+ /// backpressure and retries with a longer, jittered backoff. Divergence+ /// remains observable via `ingestion_api_batch_capacity_rejections_total`.+ /// (A future adaptive-concurrency controller will replace this static cap.)#[envconfig(from = "INGESTION_WORKER_CONCURRENT_BATCHES", default = "1")]pub ingestion_worker_concurrent_batches: usize,diff --git a/rust/ingestion-consumer/src/transport.rs b/rust/ingestion-consumer/src/transport.rsindex 59e73d361329..385d19aade95 100644--- a/rust/ingestion-consumer/src/transport.rs+++ b/rust/ingestion-consumer/src/transport.rs@@ -3,6 +3,7 @@ use std::sync::Arc;use std::time::Duration;use metrics::{counter, gauge, histogram};+use rand::Rng;use tokio::sync::Semaphore;use tracing::{error, info, warn};@@ -36,16 +37,17 @@ impl Drop for InFlightGuard {/// Sends batches to Node.js worker processes over HTTP.////// Uses reqwest with connection pooling (one pool per worker URL).-/// Retries on 5xx/timeout with exponential backoff.+/// Retries on 5xx/timeout/503 with exponential backoff.///-/// Per-worker `Semaphore`s cap how many concurrent batches we can have in-/// flight to each worker URL. The capacity must match the worker's own-/// `BatchingPipeline.concurrentBatches` setting (controlled by-/// `INGESTION_WORKER_CONCURRENT_BATCHES` on both sides). When all permits-/// are held, `send_batch` waits — this is the natural backpressure that-/// replaces retry-on-503. A 503 escaping to the transport indicates a-/// contract violation (mis-configured limits or a Rust-side timeout-/// leaving a worker still processing) and is treated as non-retriable.+/// Per-worker `Semaphore`s are a soft cap on how many concurrent batches we+/// keep in flight to each worker URL — ideally aligned with the worker's+/// `BatchingPipeline.concurrentBatches` (`INGESTION_WORKER_CONCURRENT_BATCHES`)+/// so the happy path proactively backpressures (waits for a permit) before the+/// worker fills up. The cap need not match the worker exactly: if the worker+/// rejects a batch with 503, the transport treats it as transient backpressure+/// and retries with a longer, jittered backoff. This keeps the consumer correct+/// when a worker is shared by other callers and its true capacity isn't a+/// number this consumer can reserve in advance.pub struct HttpTransport {client: reqwest::Client,max_retries: u32,@@ -182,12 +184,18 @@ impl HttpTransport {let _in_flight = InFlightGuard::new(worker_url);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.+ let mut last_was_busy = false;for attempt in 0..=self.max_retries {if attempt > 0 {- let backoff = Duration::from_millis(100 * 2u64.pow(attempt - 1));- tokio::time::sleep(backoff).await;- counter!("ingestion_consumer_transport_retries_total", "worker" => worker_url.to_string())- .increment(1);+ tokio::time::sleep(retry_backoff(attempt, last_was_busy)).await;+ counter!(+ "ingestion_consumer_transport_retries_total",+ "worker" => worker_url.to_string(),+ "reason" => if last_was_busy { "busy" } else { "error" },+ )+ .increment(1);}let start = std::time::Instant::now();@@ -203,6 +211,7 @@ impl HttpTransport {return Ok(response.accepted);}+ last_was_busy = false;let err_msg = response.error.unwrap_or_default();warn!(worker = %worker_url,@@ -217,11 +226,8 @@ impl HttpTransport {let elapsed = start.elapsed();histogram!("ingestion_consumer_transport_duration_seconds", "worker" => worker_url.to_string()).record(elapsed.as_secs_f64());- let status_label = if matches!(err, TransportError::WorkerBusy(_)) {- "busy"- } else {- "error"- };+ last_was_busy = matches!(err, TransportError::WorkerBusy(_));+ let status_label = if last_was_busy { "busy" } else { "error" };counter!("ingestion_consumer_transport_requests_total", "worker" => worker_url.to_string(), "status" => status_label).increment(1);@@ -266,10 +272,9 @@ impl HttpTransport {let response = req_builder.send().await?;let status = response.status();- // 503 means the worker is at concurrent batch capacity. The previous- // batch is still being processed — surface as a distinct error so the- // caller can apply a longer backoff instead of hammering with 100ms- // retries (which all bounce off the same in-flight batch).+ // 503 means the worker is at concurrent batch capacity. Surface it as a+ // distinct error so the retry loop applies the longer, jittered busy+ // backoff (rather than hammering with the short 5xx backoff).if status == reqwest::StatusCode::SERVICE_UNAVAILABLE {let body = response.text().await.unwrap_or_default();return Err(TransportError::WorkerBusy(body));@@ -308,18 +313,79 @@ pub enum TransportError {impl TransportError {/// 4xx errors are non-transient and should not be retried.- /// `WorkerBusy` (HTTP 503) is also non-retriable: the consumer's per-worker- /// semaphore is supposed to prevent it from ever firing, so it indicates a- /// contract violation rather than a transient condition — retrying just- /// hammers an already-overloaded worker.+ /// `WorkerBusy` (HTTP 503) is retriable backpressure: a worker shared by+ /// other callers can be momentarily at capacity even when this consumer's+ /// soft semaphore cap would allow more, so we retry with a longer, jittered+ /// backoff instead of failing.pub fn is_retriable(&self) -> bool {match self {TransportError::HttpStatus(status, _) => *status >= 500,TransportError::Http(_) => true,- TransportError::WorkerBusy(_) => false,+ TransportError::WorkerBusy(_) => true,TransportError::WorkerError(_) => true,TransportError::UnknownWorker(_) => false,TransportError::RetriesExhausted => false,}}}++/// Backoff before a retry. A busy worker (503) gets a longer base plus jitter so+/// that callers backing off the same worker don't retry in lockstep; other+/// retriable errors use a short exponential backoff. `attempt` is 1-based (the+/// first retry passes 1).+fn retry_backoff(attempt: u32, busy: bool) -> Duration {+ let exp = 2u64.saturating_pow(attempt.saturating_sub(1));+ if busy {+ let base = (250 * exp).min(5_000);+ let jitter = rand::thread_rng().gen_range(0..=base / 2);+ Duration::from_millis(base + jitter)+ } else {+ Duration::from_millis(100 * exp)+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn test_worker_busy_is_retriable() {+ assert!(TransportError::WorkerBusy("at capacity".into()).is_retriable());+ }++ #[test]+ fn test_client_errors_are_not_retriable() {+ assert!(!TransportError::HttpStatus(400, "bad".into()).is_retriable());+ assert!(!TransportError::UnknownWorker("x".into()).is_retriable());+ }++ #[test]+ fn test_server_errors_are_retriable() {+ assert!(TransportError::HttpStatus(500, "boom".into()).is_retriable());+ }++ #[test]+ fn test_busy_backoff_is_longer_than_error_backoff() {+ // Across attempts the busy backoff floor (base, no jitter) must exceed+ // the error backoff for the same attempt.+ for attempt in 1..=4 {+ let busy_min = 250 * 2u64.saturating_pow(attempt - 1);+ let err = retry_backoff(attempt, false);+ assert!(+ retry_backoff(attempt, true) >= Duration::from_millis(busy_min.min(5_000)),+ "busy backoff below floor at attempt {attempt}"+ );+ assert!(+ err < Duration::from_millis(busy_min.min(5_000)),+ "error backoff not shorter than busy at attempt {attempt}"+ );+ }+ }++ #[test]+ fn test_busy_backoff_is_capped() {+ // Even at a high attempt the busy base is capped at 5s; jitter adds up to+ // half the base, so the total stays at most 7.5s.+ assert!(retry_backoff(20, true) <= Duration::from_millis(7_500));+ }+}diff --git a/rust/ingestion-consumer/tests/transport_integration_test.rs b/rust/ingestion-consumer/tests/transport_integration_test.rsindex d8f743871c2d..b27d73d422d6 100644--- a/rust/ingestion-consumer/tests/transport_integration_test.rs+++ b/rust/ingestion-consumer/tests/transport_integration_test.rs@@ -122,6 +122,50 @@ async fn start_always_busy_worker() -> (String, tokio::task::JoinHandle<()>) {(url, handle)}+/// Spin up a mock worker that returns 503 for its first `busy_times` requests,+/// then 200 OK thereafter — simulating a worker that is momentarily at capacity.+async fn start_busy_then_ok_worker(busy_times: usize) -> (String, tokio::task::JoinHandle<()>) {+ let calls = Arc::new(AtomicUsize::new(0));+ let app = Router::new().route(+ "/ingest",+ post(move |Json(req): Json<IngestBatchRequest>| {+ let calls = calls.clone();+ async move {+ let n = calls.fetch_add(1, Ordering::SeqCst);+ if n < busy_times {+ return (+ axum::http::StatusCode::SERVICE_UNAVAILABLE,+ axum::Json(IngestBatchResponse {+ batch_id: req.batch_id,+ status: "error".to_string(),+ accepted: 0,+ error: Some("at concurrent batch capacity (1)".to_string()),+ }),+ )+ .into_response();+ }+ axum::Json(IngestBatchResponse {+ batch_id: req.batch_id,+ status: "ok".to_string(),+ accepted: req.messages.len() as u32,+ error: None,+ })+ .into_response()+ }+ }),+ );++ let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();+ let addr = listener.local_addr().unwrap();+ let url = format!("http://127.0.0.1:{}", addr.port());++ let handle = tokio::spawn(async move {+ axum::serve(listener, app).await.unwrap();+ });++ (url, handle)+}+/// Spin up a mock worker that sleeps `delay` before responding ok. Records/// the max number of overlapping in-flight requests it ever observed.async fn start_slow_worker(@@ -212,16 +256,15 @@ async fn transport_retries_on_server_error() {}#[tokio::test]-async fn transport_fails_fast_on_worker_busy_without_retry() {- // The Rust consumer's per-worker semaphore is supposed to prevent 503s.- // If the worker still returns 503, that's a contract violation, not a- // transient state — fail immediately rather than hammering an already- // overloaded worker.+async fn transport_retries_on_worker_busy() {+ // 503 is transient backpressure (a shared worker can be momentarily full),+ // so the transport retries with the longer, jittered busy backoff rather+ // than failing fast. An always-busy worker exhausts retries and returns the+ // last WorkerBusy error — but only after backing off at least once.let (url, _handle) = start_always_busy_worker().await;let urls = vec![url.clone()];- // max_retries = 3 — irrelevant for this path since WorkerBusy is non-retriable.- let transport = HttpTransport::new(Duration::from_secs(5), 3, None, &urls, 1);+ let transport = HttpTransport::new(Duration::from_secs(5), 1, None, &urls, 1);let messages = vec![make_message("tok", "user", 0, "{}")];@@ -236,13 +279,31 @@ async fn transport_fails_fast_on_worker_busy_without_retry() {matches!(err, TransportError::WorkerBusy(_)),"expected WorkerBusy, got {err:?}");- // No retry backoff should have been applied (would have been ≥100ms+200ms+400ms = 700ms).+ // One retry means one busy backoff (base 250ms + jitter), so the call must+ // take noticeably longer than the old fail-fast path (<200ms).assert!(- elapsed < Duration::from_millis(200),- "expected fail-fast on 503 (<200ms), got {elapsed:?}"+ elapsed >= Duration::from_millis(240),+ "expected a busy backoff before exhausting (≥240ms), got {elapsed:?}");}+#[tokio::test]+async fn transport_recovers_after_worker_busy() {+ // A worker that is busy once and then ready should succeed after a retry.+ let (url, _handle) = start_busy_then_ok_worker(1).await;++ let urls = vec![url.clone()];+ let transport = HttpTransport::new(Duration::from_secs(5), 3, None, &urls, 1);++ let messages = vec![make_message("tok", "user", 0, "{}")];++ let accepted = transport+ .send_batch(&url, "batch-recover", messages)+ .await+ .expect("should succeed after the worker stops being busy");+ assert_eq!(accepted, 1);+}+#[tokio::test]async fn transport_fails_on_unreachable_worker() {let url = "http://127.0.0.1:1".to_string();