: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(embedding-worker): prevent pod crashes from provider hiccups (#62731)
Oliver Browned9bbdefff295
diff --git a/rust/embedding-worker/Cargo.toml b/rust/embedding-worker/Cargo.tomlindex a7dc4ee94760..bfaa8250a248 100644--- a/rust/embedding-worker/Cargo.toml+++ b/rust/embedding-worker/Cargo.toml@@ -30,7 +30,7 @@ serde.workspace = truerand.workspace = true[dev-dependencies]-+tokio = { workspace = true, features = ["test-util"] }[lints]workspace = truediff --git a/rust/embedding-worker/src/app_context.rs b/rust/embedding-worker/src/app_context.rsindex ac3e7efa2b1e..a8c3e59ea997 100644--- a/rust/embedding-worker/src/app_context.rs+++ b/rust/embedding-worker/src/app_context.rs@@ -64,7 +64,11 @@ impl AppContext {let options = PgPoolOptions::new().max_connections(config.max_pg_connections);let pool = options.connect(&config.database_url).await?;- let client = reqwest::Client::new();+ let client = reqwest::Client::builder()+ .timeout(Duration::from_secs(+ config.embedding_request_timeout_seconds,+ ))+ .build()?;let org_cache = CacheBuilder::new(10_000).time_to_live(Duration::from_secs(30))@@ -147,24 +151,30 @@ impl AppContext {}}+// leaky-bucket adds `refill` tokens once per `interval`. Refilling the whole+// per-minute budget in a single 60s lump means a drained bucket suspends the+// next acquire() until the minute boundary - up to ~60s - which stalls the+// worker's liveness heartbeat and gets the pod killed. Drip the budget in small+// sub-second increments instead, so a drained bucket only ever blocks for about+// one interval. Long-run throughput is unchanged (still capped at the budget).+const REFILL_INTERVAL: Duration = Duration::from_millis(100);+const REFILLS_PER_MINUTE: usize = 600; // 60_000ms / 100ms++fn build_rate_limiter(per_minute: usize) -> RateLimiter {+ RateLimiter::builder()+ .max(per_minute.max(1))+ .initial(per_minute)+ .refill((per_minute / REFILLS_PER_MINUTE).max(1))+ .interval(REFILL_INTERVAL)+ .build()+}+impl From<ApiLimits> for Limiter {fn from(definition: ApiLimits) -> Self {- let tokens = RateLimiter::builder()- .max(definition.tokens_per_minute)- .refill(definition.tokens_per_minute)- .initial(definition.tokens_per_minute)- .interval(Duration::from_secs(60))- .build();- let requests = RateLimiter::builder()- .max(definition.requests_per_minute)- .refill(definition.requests_per_minute)- .initial(definition.requests_per_minute)- .interval(Duration::from_secs(60))- .build();Limiter {+ tokens: build_rate_limiter(definition.tokens_per_minute),+ requests: build_rate_limiter(definition.requests_per_minute),definition,- tokens,- requests,}}}@@ -207,3 +217,25 @@ impl Limiter {self.acquire(to_consume_tokens, to_consume_requests).await;}}++#[cfg(test)]+mod tests {+ use super::*;++ #[tokio::test(start_paused = true)]+ async fn drained_rate_limiter_refills_within_one_interval() {+ // 600/min => 1 token dripped every 100ms.+ let limiter = build_rate_limiter(600);++ // Drain the full initial balance, then acquire one more token. With the old+ // 60s-lump refill this acquire blocks until the minute boundary; with the+ // sub-second drip it must be satisfied within roughly one interval. Paused+ // time auto-advances to the next timer, so the 1s ceiling fails fast if the+ // refill cadence ever regresses to ~60s.+ limiter.acquire(600).await;++ tokio::time::timeout(Duration::from_secs(1), limiter.acquire(1))+ .await+ .expect("drained limiter should refill within ~100ms, well under 60s");+ }+}diff --git a/rust/embedding-worker/src/config.rs b/rust/embedding-worker/src/config.rsindex 9c7fc0d337d7..dd3c7494b744 100644--- a/rust/embedding-worker/src/config.rs+++ b/rust/embedding-worker/src/config.rs@@ -46,6 +46,12 @@ pub struct Config {#[envconfig(default = "10")]pub max_event_batch_wait_seconds: u64,++ // Per-request timeout for calls to the embedding provider, covering the whole+ // request (connect through response body). Bounds a slow/hung request so it+ // can't stall batch processing indefinitely.+ #[envconfig(default = "10")]+ pub embedding_request_timeout_seconds: u64,}impl Config {diff --git a/rust/embedding-worker/src/lib.rs b/rust/embedding-worker/src/lib.rsindex d4cf305b02b7..db3714788f39 100644--- a/rust/embedding-worker/src/lib.rs+++ b/rust/embedding-worker/src/lib.rs@@ -101,6 +101,13 @@ pub async fn handle_single(Ok((model, embedding))}+// Exponential backoff (base 2) with jitter, in milliseconds, for retry `attempt`.+fn retry_backoff_ms(attempt: usize) -> u64 {+ let base_ms = RETRY_BASE_SECS.pow(attempt as u32 + 1) * 1000;+ let jitter_ms = rand::thread_rng().gen_range(RETRY_JITTER_RANGE);+ (base_ms as i64 + jitter_ms).max(0) as u64+}+pub async fn generate_embedding(context: Arc<AppContext>,model: EmbeddingModel,@@ -117,6 +124,7 @@ pub async fn generate_embedding(let mut last_status = None;let mut last_error_body = None;+ let mut last_transport_error = None;for attempt in 0..MAX_RETRY_ATTEMPTS {let api_req = construct_request(@@ -127,7 +135,28 @@ pub async fn generate_embedding();counter!(REQUESTS_SENT, labels.render()).increment(1);- let response = context.client.execute(api_req).await?; // Unhandled - network errors etc+ let response = match context.client.execute(api_req).await {+ Ok(response) => response,+ Err(e) => {+ // Transport errors (timeouts, connection resets, etc.) are transient.+ // Retry them with backoff like a 5xx rather than aborting the whole+ // batch, which would panic and restart the worker.+ if attempt < MAX_RETRY_ATTEMPTS - 1 {+ let sleep_ms = retry_backoff_ms(attempt);+ warn!(+ "Request to embedding provider failed ({}), retrying in {}ms (attempt {}/{})",+ e,+ sleep_ms,+ attempt + 1,+ MAX_RETRY_ATTEMPTS - 1+ );+ tokio::time::sleep(Duration::from_millis(sleep_ms)).await;+ }+ last_status = None;+ last_transport_error = Some(e);+ continue;+ }+ };let status = response.status();let response_labels = labels@@ -159,9 +188,7 @@ pub async fn generate_embedding(}if attempt < MAX_RETRY_ATTEMPTS - 1 {- let base_ms = RETRY_BASE_SECS.pow(attempt as u32 + 1) * 1000;- let jitter_ms = rand::thread_rng().gen_range(RETRY_JITTER_RANGE);- let sleep_ms = (base_ms as i64 + jitter_ms).max(0) as u64;+ let sleep_ms = retry_backoff_ms(attempt);warn!("Got {} from embedding provider, retrying in {}ms (attempt {}/{})",status,@@ -174,14 +201,26 @@ pub async fn generate_embedding(}// All attempts exhausted or non-retryable error- let status = last_status.unwrap();- error!(- "Failed to generate embeddings, got {} from {}",- status,- model.provider()- );- if let Some(error_message) = last_error_body {- error!("Error message from {}: {}", model.provider(), error_message);+ match last_status {+ Some(status) => {+ error!(+ "Failed to generate embeddings, got {} from {}",+ status,+ model.provider()+ );+ if let Some(error_message) = last_error_body {+ error!("Error message from {}: {}", model.provider(), error_message);+ }+ }+ None => {+ error!(+ "Failed to generate embeddings, no response from {}: {}",+ model.provider(),+ last_transport_error+ .map(|e| e.to_string())+ .unwrap_or_else(|| "unknown error".to_string())+ );+ }}Err(anyhow::anyhow!("Failed to generate embeddings"))