: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(flags): fit db timeouts inside the request timeout (#108014)
Phil Haack1f1544258294
diff --git a/docs/internal/feature-flags/database-interaction-patterns.md b/docs/internal/feature-flags/database-interaction-patterns.mdindex 1d57a4f2a57a..5b347775e64f 100644--- a/docs/internal/feature-flags/database-interaction-patterns.md+++ b/docs/internal/feature-flags/database-interaction-patterns.md@@ -54,10 +54,10 @@ pub struct PoolConfig {| ---------------------- | --------------- | --------------- | ------------------------------------------ || `min_connections` | 0 | 0 per pool | Start with no connections, scale on demand || `max_connections` | 10 | 10 | Maximum connections per pool |-| `acquire_timeout` | 10s | 3s (test) | Wait time for connection from pool |+| `acquire_timeout` | 10s | 1s | Wait time for connection from pool || `idle_timeout` | 300s (5 min) | 300s | Close unused connections || `test_before_acquire` | true | true | Validate connection before use |-| `statement_timeout_ms` | None | 5000ms | Cancel queries exceeding this duration |+| `statement_timeout_ms` | None | per pool | Cancel queries exceeding this duration |### Per-pool statement timeouts@@ -214,6 +214,9 @@ Transient errors (suitable for retry):| `40003` | Statement completion unknown || `40P01` | Deadlock detected |+The `57***` class includes 57014, which is a statement timeout.+The hash key override retry predicate checks `is_timeout_error` first, so it does not retry a timeout.+Non-transient errors (fail immediately):| SQLSTATE class | Meaning |@@ -250,35 +253,40 @@ Used for retrying hash key override writes when a person is deleted during the o## Retry strategies-The service uses the `tokio-retry` crate with exponential backoff:+The hash key override calls use the `tokio-retry` crate with exponential backoff.+Each call passes `should_retry_on_error` to `RetryIf`.+It retries a transient error and a foreign key violation, which means a person was deleted during a write.+It does not retry a timeout, because a second attempt could wait the full acquire and statement timeouts again.### Read operations+`get_feature_flag_hash_key_overrides`:+```rustlet retry_strategy = ExponentialBackoff::from_millis(50).max_delay(Duration::from_millis(300))- .take(3) // 3 attempts total+ .take(1) // 1 retry = 2 attempts total.map(jitter);```- **Initial delay**: 50ms- **Max delay**: 300ms-- **Max attempts**: 3-- **Retry on**: Transient errors only+- **Max attempts**: 2### Write operations+`should_write_hash_key_override` and `set_feature_flag_hash_key_overrides`:+```rustlet retry_strategy = ExponentialBackoff::from_millis(100).max_delay(Duration::from_millis(300))- .take(2) // 2 attempts for writes+ .take(2) // 2 retries = 3 attempts total.map(jitter);```-- **Initial delay**: 100ms (slower to avoid overwhelming)+- **Initial delay**: 100ms- **Max delay**: 300ms-- **Max attempts**: 2 (more conservative)-- **Retry on**: Foreign key constraint errors (person deletion race)+- **Max attempts**: 3## Observability@@ -291,7 +299,7 @@ let retry_strategy = ExponentialBackoff::from_millis(100)| `flags_definition_query_time` | - | Flag definition query duration || `flags_pool_utilization_ratio` | `pool` | Pool utilization (0.0-1.0) || `flags_connection_hold_time_ms` | `pool`, `operation` | How long connections are held |-| `flags_hash_key_retries_total` | `team_id`, `operation` | Retry counter |+| `flags_hash_key_retries_total` | `team_id`, `operation` | Retries that started. A failed attempt counts only when its retry starts || `flags_flag_evaluation_error_total` | `error_type` | Error counter || `db_connection_created_total` | `pool` | Connection creation events (physical TCP/TLS, not pool reuse) || `flags_db_connection_pool_size` | `pool` | Total pool size (should equal active + idle) |@@ -347,24 +355,25 @@ Queries exceeding 500ms are logged at WARN level with timing information.### Environment variables-| Variable | Default | Purpose |-| ----------------------------------------- | ------------ | ---------------------------------------------------------------- |-| `READ_DATABASE_URL` | required | Main database read replica URL |-| `WRITE_DATABASE_URL` | required | Main database primary URL |-| `PERSONS_READ_DATABASE_URL` | empty | Persons database read replica (enables routing) |-| `PERSONS_WRITE_DATABASE_URL` | empty | Persons database primary (enables routing) |-| `MAX_PG_CONNECTIONS` | 10 | Max connections per pool |-| `MIN_NON_PERSONS_READER_CONNECTIONS` | 0 | Min idle connections for non-persons reader |-| `MIN_NON_PERSONS_WRITER_CONNECTIONS` | 0 | Min idle connections for non-persons writer |-| `MIN_PERSONS_READER_CONNECTIONS` | 0 | Min idle connections for persons reader |-| `MIN_PERSONS_WRITER_CONNECTIONS` | 0 | Min idle connections for persons writer |-| `ACQUIRE_TIMEOUT_SECS` | 10 | Connection acquisition timeout |-| `IDLE_TIMEOUT_SECS` | 300 | Idle connection timeout |-| `TEST_BEFORE_ACQUIRE` | true | Validate connections before use |-| `NON_PERSONS_READER_STATEMENT_TIMEOUT_MS` | 0 (disabled) | Statement timeout for non-persons reads |-| `PERSONS_READER_STATEMENT_TIMEOUT_MS` | 0 (disabled) | Statement timeout for persons reads |-| `WRITER_STATEMENT_TIMEOUT_MS` | 0 (disabled) | Statement timeout for writes |-| `BEHAVIORAL_COHORTS_READ_DATABASE_URL` | empty | Behavioral cohorts database (enables realtime cohort evaluation) |+| Variable | Default | Purpose |+| ------------------------------------------- | -------- | ---------------------------------------------------------------- |+| `READ_DATABASE_URL` | required | Main database read replica URL |+| `WRITE_DATABASE_URL` | required | Main database primary URL |+| `PERSONS_READ_DATABASE_URL` | empty | Persons database read replica (enables routing) |+| `PERSONS_WRITE_DATABASE_URL` | empty | Persons database primary (enables routing) |+| `MAX_PG_CONNECTIONS` | 10 | Max connections per pool |+| `MIN_NON_PERSONS_READER_CONNECTIONS` | 0 | Min idle connections for non-persons reader |+| `MIN_NON_PERSONS_WRITER_CONNECTIONS` | 0 | Min idle connections for non-persons writer |+| `MIN_PERSONS_READER_CONNECTIONS` | 0 | Min idle connections for persons reader |+| `MIN_PERSONS_WRITER_CONNECTIONS` | 0 | Min idle connections for persons writer |+| `ACQUIRE_TIMEOUT_SECS` | 1 | Connection acquisition timeout |+| `IDLE_TIMEOUT_SECS` | 300 | Idle connection timeout |+| `TEST_BEFORE_ACQUIRE` | true | Validate connections before use |+| `NON_PERSONS_READER_STATEMENT_TIMEOUT_MS` | 2000 | Statement timeout for non-persons reads |+| `PERSONS_READER_STATEMENT_TIMEOUT_MS` | 1000 | Statement timeout for persons reads |+| `WRITER_STATEMENT_TIMEOUT_MS` | 2000 | Statement timeout for writes |+| `BEHAVIORAL_COHORTS_READ_DATABASE_URL` | empty | Behavioral cohorts database (enables realtime cohort evaluation) |+| `BATCH_FLAG_EVAL_SCAN_STATEMENT_TIMEOUT_MS` | 10000 | Statement timeout for the batch evaluation person scan |### Tuning guidance@@ -383,13 +392,26 @@ IDLE_TIMEOUT_SECS=600 # Keep connections warm longerMIN_NON_PERSONS_READER_CONNECTIONS=3 # Pre-warm some connections```-**Strict timeout enforcement**:--```bash-NON_PERSONS_READER_STATEMENT_TIMEOUT_MS=5000 # 5s for reads-PERSONS_READER_STATEMENT_TIMEOUT_MS=5000-WRITER_STATEMENT_TIMEOUT_MS=2000 # 2s for writes (should be fast)-```+**Raising timeouts**:++One database call can wait the full acquire timeout and then run until the statement timeout cancels its query.+Keep `ACQUIRE_TIMEOUT_SECS` plus each pool's statement timeout well under `REQUEST_TIMEOUT_MS`.+Otherwise the request can time out while its query still runs, and sqlx closes the connection instead of returning it to the pool.+The service logs a warning at startup for each pool where the sum does not fit.+It skips a pool that aliases another pool, because an aliased pool runs with the other pool's statement timeout.+Hash key override calls do not retry a timeout.+They do retry a transient error.+Each retry waits for a connection and runs the query again, so this sum bounds one acquire and one statement, not the whole call.+A hash key override write chains two acquires and four statements across two pools in one attempt.+The foreign key from `posthog_featureflaghashkeyoverride` to `posthog_person` is deferred, so Postgres checks it at `COMMIT`.+`statement_timeout` does not cover `COMMIT`.+The write runs `SET CONSTRAINTS ALL IMMEDIATE` first, so the foreign key check on the person row runs inside the insert, under the writer statement timeout.+The batch evaluation endpoint shares these pools, so its per-person lookups get the same limits.+When a transient database fault or a timeout fails a person, the endpoint evaluates the person a second time before it counts them in `errors_count`.+A `database_error` gets no second attempt, because it comes from a query that fails the same way every time.+Each page allows at most 20 of these retries, so a sustained stall cannot spend the page timeout on retries.+Django leaves a person in that count out of the static cohort.+`flags_batch_eval_person_retries_total` counts these retries by `outcome` (`recovered` or `failed`).## Related filesdiff --git a/docs/internal/feature-flags/rust-service-overview.md b/docs/internal/feature-flags/rust-service-overview.mdindex f282e0112acf..c69a5f1f739d 100644--- a/docs/internal/feature-flags/rust-service-overview.md+++ b/docs/internal/feature-flags/rust-service-overview.md@@ -252,11 +252,11 @@ Exact property matching is selected per team through `TeamFeatureFlagsConfig.pro| `PERSONS_WRITE_DATABASE_URL` | (empty, aliases to main) | Persons database primary || `PERSONS_READ_DATABASE_URL` | (empty, aliases to main) | Persons database replica || `MAX_PG_CONNECTIONS` | `10` | Max connections per pool |-| `ACQUIRE_TIMEOUT_SECS` | `5` | Connection acquisition timeout |+| `ACQUIRE_TIMEOUT_SECS` | `1` | Connection acquisition timeout || `IDLE_TIMEOUT_SECS` | `300` | Close idle connections after this || `NON_PERSONS_READER_STATEMENT_TIMEOUT_MS` | `2000` | Statement timeout for flag/team reads |-| `PERSONS_READER_STATEMENT_TIMEOUT_MS` | `3000` | Statement timeout for person lookups |-| `WRITER_STATEMENT_TIMEOUT_MS` | `3000` | Statement timeout for writes |+| `PERSONS_READER_STATEMENT_TIMEOUT_MS` | `1000` | Statement timeout for person lookups |+| `WRITER_STATEMENT_TIMEOUT_MS` | `2000` | Statement timeout for writes |### Behavioral cohortsdiff --git a/rust/feature-flags/src/api/batch_flag_evaluation.rs b/rust/feature-flags/src/api/batch_flag_evaluation.rsindex bb57c8e25729..3cedc73217e9 100644--- a/rust/feature-flags/src/api/batch_flag_evaluation.rs+++ b/rust/feature-flags/src/api/batch_flag_evaluation.rs@@ -41,12 +41,12 @@ use common_database::PostgresReader;use common_metrics::inc;use common_types::PersonId;use serde::{Deserialize, Serialize};-use sqlx::FromRow;+use sqlx::{Acquire, FromRow};use tracing::warn;use uuid::Uuid;use crate::{- api::errors::FlagError,+ api::{errors::FlagError, types::FlagsResponse},database::{get_connection_with_metrics, PostgresRouter},flags::{cache_builder::compute_flag_dependencies,@@ -56,7 +56,8 @@ use crate::{},handler::authentication::is_internal_request_inner,metrics::consts::{- FLAG_BATCH_EVAL_PERSONS_COUNTER, FLAG_BATCH_EVAL_REQUESTS_COUNTER, FLAG_BATCH_EVAL_TIME,+ FLAG_BATCH_EVAL_PERSONS_COUNTER, FLAG_BATCH_EVAL_PERSON_RETRIES_COUNTER,+ FLAG_BATCH_EVAL_REQUESTS_COUNTER, FLAG_BATCH_EVAL_TIME,},router,team::team_models::{PropertyMatchingVersion, Team},@@ -99,6 +100,11 @@ pub struct BatchFlagEvaluationResponse {const DEFAULT_LIMIT: i64 = 1_000;+/// A page evaluates its persons one at a time under `BATCH_FLAG_EVAL_TIMEOUT_MS`. A retry of a+/// person that timed out waits the persons pool timeouts a second time. The cap keeps a+/// sustained stall from spending the page timeout on retries.+const MAX_PERSON_RETRIES_PER_PAGE: u32 = 20;+#[derive(Debug)]pub enum BatchFlagEvaluationError {Unauthorized,@@ -232,9 +238,26 @@ async fn scan_persons_page(team_id: i32,cursor: i64,limit: i64,+ statement_timeout_ms: u64,) -> Result<Vec<PersonScanRow>, FlagError> {let mut conn =get_connection_with_metrics(&reader, "persons_reader", "batch_eval_person_scan").await?;+ let scan_failed = |e: sqlx::Error| {+ warn!(team_id, cursor, "Batch eval person scan failed: {e}");+ let message = format!("person scan query failed: {e}");+ FlagError::internal(anyhow::Error::new(e).context(message))+ };++ // SET LOCAL lasts only until the transaction ends, so the connection goes back to the+ // pool with the pool's statement timeout.+ let mut tx = conn.begin().await.map_err(scan_failed)?;+ // SET does not accept a bind parameter. The value is a u64, so it cannot inject SQL.+ sqlx::query(&format!(+ "SET LOCAL statement_timeout = {statement_timeout_ms}"+ ))+ .execute(&mut *tx)+ .await+ .map_err(scan_failed)?;// Sort-free PK range scan on the partitioned persons table; the lateral subquery is// covered by the existing person_id index on posthog_persondistinctid.@@ -257,17 +280,15 @@ async fn scan_persons_page(LIMIT $3"#;- sqlx::query_as::<_, PersonScanRow>(query)+ let rows = sqlx::query_as::<_, PersonScanRow>(query).bind(team_id).bind(cursor).bind(limit)- .fetch_all(&mut *conn)+ .fetch_all(&mut *tx).await- .map_err(|e| {- warn!(team_id, cursor, "Batch eval person scan failed: {e}");- let message = format!("person scan query failed: {e}");- FlagError::internal(anyhow::Error::new(e).context(message))- })+ .map_err(scan_failed)?;+ tx.commit().await.map_err(scan_failed)?;+ Ok(rows)}/// Fetches the team's flags fresh from Postgres and locates the target flag by key.@@ -341,6 +362,68 @@ pub async fn batch_flag_evaluation(result.map(Json)}+fn failure_code(result: &Result<FlagsResponse, FlagError>, target_key: &str) -> Option<String> {+ match result {+ Ok(response) => response+ .flags+ .get(target_key)+ .filter(|details| details.failed)+ .map(|details| details.reason.code.clone()),+ Err(e) => Some(e.evaluation_error_code()),+ }+}++/// Whether a failure code comes from a transient database fault or a timeout, which a second+/// evaluation can fix. Other failures, such as a missing dependency, an unsupported filter, or a+/// `database_error` from a query that cannot succeed, fail the same way on every attempt. An+/// unknown code gets no retry, so a new kind of failure cannot double the load on the persons+/// pools.+fn is_transient_failure(code: &str) -> bool {+ code.starts_with("timeout")+ || matches!(+ code,+ "database_unavailable"+ | "no_more_connections"+ | "query_wait_timeout"+ | "hash_key_override_error"+ )+}++/// Evaluates a person a second time when the first evaluation fails with a transient code. The+/// persons pools size their timeouts for /flags. Django leaves a failed person out of the cohort.+/// Each retry uses one unit of `retries_left`. When the budget is empty, a failed person gets no+/// second attempt, so a degraded replica cannot double the queries of a whole page.+async fn evaluate_with_one_retry<F, Fut>(+ target_key: &str,+ retries_left: &mut u32,+ mut evaluate: F,+) -> Result<FlagsResponse, FlagError>+where+ F: FnMut() -> Fut,+ Fut: std::future::Future<Output = Result<FlagsResponse, FlagError>>,+{+ let first = evaluate().await;+ if *retries_left == 0+ || !failure_code(&first, target_key).is_some_and(|code| is_transient_failure(&code))+ {+ return first;+ }+ *retries_left -= 1;++ let second = evaluate().await;+ let outcome = if failure_code(&second, target_key).is_some() {+ "failed"+ } else {+ "recovered"+ };+ inc(+ FLAG_BATCH_EVAL_PERSON_RETRIES_COUNTER,+ &[("outcome".to_string(), outcome.to_string())],+ 1,+ );+ second+}+async fn handle_batch_flag_evaluation(state: &router::State,body: &[u8],@@ -465,6 +548,7 @@ async fn handle_batch_flag_evaluation(request.team_id,request.cursor,limit,+ state.config.batch_flag_eval_scan_statement_timeout_ms,).await.map_err(BatchFlagEvaluationError::Upstream)?;@@ -487,9 +571,12 @@ async fn handle_batch_flag_evaluation(.includes_team(request.team_id);let use_explicit_exact_matching = team.property_matching_version.uses_explicit_matching();let team_timezone = team.parsed_timezone();+ let optimize_experience_continuity_lookups =+ state.config.optimize_experience_continuity_lookups.0;let mut matched_person_uuids: Vec<Uuid> = Vec::new();let mut errors_count: u64 = 0;+ let mut retries_left = MAX_PERSON_RETRIES_PER_PAGE;for row in rows {// Persons with zero distinct_ids (almost-deleted) are skipped.@@ -498,39 +585,46 @@ async fn handle_batch_flag_evaluation(continue;};- // Per-person so each evaluation is independently traceable in canonical logs.- let request_id = Uuid::new_v4();+ let evaluate = || {+ // Per-evaluation so each one is independently traceable in canonical logs.+ let request_id = Uuid::new_v4();- let mut matcher = FeatureFlagMatcher::new(- distinct_id,- None,- request.team_id,- pg_router.clone(),- state.cohort_cache_manager.clone(),- state.group_type_cache_manager.clone(),- None,- )- .with_cohort_membership_provider(state.cohort_membership_provider.clone())- .with_realtime_cohort_evaluation(enable_realtime_cohort_evaluation)- .with_explicit_exact_matching(use_explicit_exact_matching)- .with_membership_stamp_policy(state.config.realtime_cohort_membership_stamp_policy)- .with_rayon_dispatcher(state.rayon_dispatcher.clone())- .with_parallel_eval_threshold(state.config.parallel_eval_threshold)- // Read-only: experience-continuity overrides are consulted but never written.- .with_skip_writes(true)- .with_timezone(team_timezone);-- let evaluation = matcher- .evaluate_all_feature_flags(- flag_list.clone(),+ let mut matcher = FeatureFlagMatcher::new(+ distinct_id.clone(),None,+ request.team_id,+ pg_router.clone(),+ state.cohort_cache_manager.clone(),+ state.group_type_cache_manager.clone(),None,- None,- request_id,- Some(vec![target_key.clone()]),- state.config.optimize_experience_continuity_lookups.0,)- .await;+ .with_cohort_membership_provider(state.cohort_membership_provider.clone())+ .with_realtime_cohort_evaluation(enable_realtime_cohort_evaluation)+ .with_explicit_exact_matching(use_explicit_exact_matching)+ .with_membership_stamp_policy(state.config.realtime_cohort_membership_stamp_policy)+ .with_rayon_dispatcher(state.rayon_dispatcher.clone())+ .with_parallel_eval_threshold(state.config.parallel_eval_threshold)+ // Read-only: experience-continuity overrides are consulted but never written.+ .with_skip_writes(true)+ .with_timezone(team_timezone);++ let flag_list = flag_list.clone();+ let target_key = target_key.clone();+ async move {+ matcher+ .evaluate_all_feature_flags(+ flag_list,+ None,+ None,+ None,+ request_id,+ Some(vec![target_key]),+ optimize_experience_continuity_lookups,+ )+ .await+ }+ };+ let evaluation = evaluate_with_one_retry(&target_key, &mut retries_left, evaluate).await;match evaluation {Ok(response) => match response.flags.get(&target_key) {@@ -582,3 +676,215 @@ fn record_person_outcome(result: &str) {1,);}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::api::types::{FlagDetails, FromFeatureAndMatch};+ use crate::config::DEFAULT_TEST_CONFIG;+ use crate::flags::flag_match_reason::FeatureFlagMatchReason;+ use crate::flags::flag_matching::FeatureFlagMatch;+ use crate::mock;+ use crate::utils::graph_utils::DependencyType;+ use crate::utils::test_utils::{counter_total, TestContext};+ use common_database::{get_pool_with_config, PoolConfig};+ use metrics_util::debugging::DebuggingRecorder;+ use std::collections::HashMap;+ use std::sync::atomic::{AtomicUsize, Ordering};+ use std::time::Duration;++ fn target_flag_response(details: FlagDetails) -> Result<FlagsResponse, FlagError> {+ Ok(FlagsResponse::new(+ false,+ HashMap::from([("target".to_string(), details)]),+ None,+ Uuid::nil(),+ ))+ }++ fn failed_target_flag(error: FlagError) -> Result<FlagsResponse, FlagError> {+ let flag = mock!(FeatureFlag, key: "target".to_string());+ target_flag_response(FlagDetails::create_error(&flag, &error, None))+ }++ fn evaluated() -> Result<FlagsResponse, FlagError> {+ let flag = mock!(FeatureFlag, key: "target".to_string());+ target_flag_response(FlagDetails::create(+ &flag,+ &FeatureFlagMatch {+ matches: false,+ variant: None,+ reason: FeatureFlagMatchReason::NoConditionMatch,+ condition_index: None,+ payload: None,+ },+ ))+ }++ fn database_unavailable() -> Result<FlagsResponse, FlagError> {+ Err(FlagError::DatabaseUnavailable)+ }++ #[rstest::rstest]+ #[case::error(database_unavailable, evaluated, 1, false, Some("recovered"))]+ #[case::transient_failed_flag(+ || failed_target_flag(FlagError::DatabaseUnavailable),+ evaluated,+ 1,+ false,+ Some("recovered")+ )]+ #[case::timeout_error(+ || Err(FlagError::TimeoutError(Some("query_canceled".to_string()))),+ evaluated,+ 1,+ false,+ Some("recovered")+ )]+ #[case::timeout_failed_flag(+ || failed_target_flag(FlagError::TimeoutError(None)),+ evaluated,+ 1,+ false,+ Some("recovered")+ )]+ #[case::dependency_failed_flag(+ || failed_target_flag(FlagError::DependencyNotFound(DependencyType::Cohort, 1)),+ evaluated,+ 1,+ true,+ None+ )]+ #[case::database_error(+ || Err(FlagError::DatabaseError(sqlx::Error::ColumnNotFound("id".to_string()), None)),+ evaluated,+ 1,+ true,+ None+ )]+ #[case::evaluated(evaluated, evaluated, 1, false, None)]+ #[case::retry_fails(database_unavailable, database_unavailable, 1, true, Some("failed"))]+ #[case::budget_spent(database_unavailable, evaluated, 0, true, None)]+ #[tokio::test]+ async fn test_evaluate_with_one_retry(+ #[case] first_attempt: fn() -> Result<FlagsResponse, FlagError>,+ #[case] second_attempt: fn() -> Result<FlagsResponse, FlagError>,+ #[case] retry_budget: u32,+ #[case] expected_failed: bool,+ #[case] expected_outcome: Option<&str>,+ ) {+ let recorder = DebuggingRecorder::new();+ let snapshotter = recorder.snapshotter();+ let _guard = metrics::set_default_local_recorder(&recorder);+ let attempts = AtomicUsize::new(0);+ let mut retries_left = retry_budget;++ let result = evaluate_with_one_retry("target", &mut retries_left, || {+ let attempt = attempts.fetch_add(1, Ordering::SeqCst);+ async move {+ if attempt == 0 {+ first_attempt()+ } else {+ second_attempt()+ }+ }+ })+ .await;++ let attempts = attempts.load(Ordering::SeqCst);+ assert_eq!(attempts, 1 + usize::from(expected_outcome.is_some()));+ assert_eq!(retries_left, retry_budget + 1 - attempts as u32);+ let failed = match result {+ Ok(response) => response.flags["target"].failed,+ Err(_) => true,+ };+ assert_eq!(failed, expected_failed);+ for outcome in ["recovered", "failed"] {+ assert_eq!(+ counter_total(+ &snapshotter,+ FLAG_BATCH_EVAL_PERSON_RETRIES_COUNTER,+ &[("outcome", outcome)]+ ),+ u64::from(expected_outcome == Some(outcome)),+ "{outcome}"+ );+ }+ }++ #[tokio::test]+ async fn test_person_scan_outlasts_the_pool_statement_timeout() {+ let context = TestContext::new(None).await;+ let team = context.insert_new_team(None).await.unwrap();+ context+ .insert_person(team.id, "user".to_string(), None)+ .await+ .unwrap();++ let reader: PostgresReader = Arc::new(+ get_pool_with_config(+ &DEFAULT_TEST_CONFIG.get_persons_read_database_url(),+ PoolConfig {+ statement_timeout_ms: Some(100),+ max_connections: 1,+ ..PoolConfig::default()+ },+ )+ .unwrap(),+ );++ let mut lock_conn = context.persons_writer.get_connection().await.unwrap();+ let mut lock_tx = lock_conn.begin().await.unwrap();+ sqlx::query("LOCK TABLE posthog_person IN ACCESS EXCLUSIVE MODE")+ .execute(&mut *lock_tx)+ .await+ .unwrap();++ let scan = tokio::spawn(scan_persons_page(reader.clone(), team.id, 0, 10, 10_000));++ // Release the lock only after the scan query waits on it. Otherwise the scan can start+ // after the rollback and pass without the SET LOCAL timeout.+ let deadline = tokio::time::Instant::now() + Duration::from_secs(10);+ loop {+ // pg_stat_activity keeps one snapshot for the whole transaction, so clear it+ // before each read.+ sqlx::query("SELECT pg_stat_clear_snapshot()")+ .execute(&mut *lock_tx)+ .await+ .unwrap();+ let scan_blocked: bool = sqlx::query_scalar(+ "SELECT EXISTS (+ SELECT 1 FROM pg_stat_activity+ WHERE pg_backend_pid() = ANY(pg_blocking_pids(pid))+ AND query LIKE '%JOIN LATERAL%'+ )",+ )+ .fetch_one(&mut *lock_tx)+ .await+ .unwrap();+ if scan_blocked {+ break;+ }+ assert!(+ tokio::time::Instant::now() < deadline,+ "the person scan never waited on the table lock"+ );+ tokio::time::sleep(Duration::from_millis(10)).await;+ }++ // Hold the lock for longer than the pool's 100ms statement timeout.+ tokio::time::sleep(Duration::from_millis(300)).await;+ lock_tx.rollback().await.unwrap();++ let rows = scan.await.unwrap().unwrap();+ assert_eq!(rows.len(), 1);++ // The pool has one connection, so this acquire returns the connection the scan used.+ let mut conn = reader.get_connection().await.unwrap();+ let statement_timeout: String = sqlx::query_scalar("SHOW statement_timeout")+ .fetch_one(&mut *conn)+ .await+ .unwrap();+ assert_eq!(statement_timeout, "100ms");+ }+}diff --git a/rust/feature-flags/src/config.rs b/rust/feature-flags/src/config.rsindex df523c911dd5..2549b8f795af 100644--- a/rust/feature-flags/src/config.rs+++ b/rust/feature-flags/src/config.rs@@ -426,7 +426,8 @@ pub struct Config {// Upper bound on a single realtime cohort membership lookup (pool acquire + query).// Keeps an unreachable behavioral cohorts DB from stalling flag requests for the- // pool's full 2s acquire timeout; on timeout the lookup degrades to non-membership.+ // pool's full acquire timeout plus statement timeout. On timeout the lookup degrades to+ // non-membership.// The default matches the pool's 1s statement timeout: a tighter client-side bound// would discard answers the DB would still deliver, flipping flags for the person,// so this bound only adds cover where statement_timeout cannot reach (pool acquire@@ -519,10 +520,13 @@ pub struct Config {#[envconfig(default = "4500")]pub request_timeout_ms: u64,- // How long to wait for a connection from the pool before timing out.- // Must be well under request_timeout_ms so there's still time for query + response.- // With Envoy at 5s and request_timeout at 4.5s, 2s leaves room for a query + serialization.- #[envconfig(default = "2")]+ // How long to wait for a connection from the pool before timing out (whole seconds, minimum 1).+ // The wait covers queueing for a free connection, the test_before_acquire ping, and opening a+ // new connection.+ // This plus each pool's statement timeout must stay well under request_timeout_ms. Then+ // Postgres cancels a slow query before the request times out, and the connection goes back+ // to the pool. When the request times out first, sqlx closes the connection instead.+ #[envconfig(default = "1")]pub acquire_timeout_secs: u64,// Close connections that have been idle for this many seconds@@ -548,19 +552,23 @@ pub struct Config {// PostgreSQL statement_timeout for persons reader queries (milliseconds)// - Set to 0 to use database default (typically unlimited)- // - Person and cohort queries should complete well under 3s (P99 hold time is 25ms)- // - Default: 3000ms (3 seconds)+ // - Person and cohort queries should complete well under 1s (P99 hold time is 25ms)+ // - Default: 1000ms (1 second)// - This timeout is enforced server-side and properly kills queries- #[envconfig(default = "3000")]+ #[envconfig(default = "1000")]pub persons_reader_statement_timeout_ms: u64,// PostgreSQL statement_timeout for writer database queries (milliseconds)// - Set to 0 to use database default (typically unlimited)- // - Hash key override writes have retry logic (2 attempts, 100ms backoff)- // - 3s per attempt with retries gives 6s total before failure- // - Default: 3000ms (3 seconds)+ // - Hash key override writes retry a transient error and a foreign key violation, which+ // occurs when a person is deleted during the write. A statement that hits this timeout is+ // not retried.+ // - Hash key override inserts have a longer latency tail than person reads. A timed-out insert+ // returns an error for every experience continuity flag in the response, so this timeout is+ // longer than the persons reader timeout.+ // - Default: 2000ms (2 seconds)// - This timeout is enforced server-side and properly kills queries- #[envconfig(default = "3000")]+ #[envconfig(default = "2000")]pub writer_statement_timeout_ms: u64,// How often to report database pool metrics (seconds)@@ -843,6 +851,12 @@ pub struct Config {#[envconfig(from = "BATCH_FLAG_EVAL_TIMEOUT_MS", default = "120000")]pub batch_flag_eval_timeout_ms: u64,+ // Statement timeout for the batch evaluation person scan (milliseconds). It replaces the+ // persons reader pool's timeout, which is sized for /flags. It also bounds how long one+ // scan holds a persons reader connection that /flags traffic needs.+ #[envconfig(from = "BATCH_FLAG_EVAL_SCAN_STATEMENT_TIMEOUT_MS", default = "10000")]+ pub batch_flag_eval_scan_statement_timeout_ms: u64,+// Redis compression configuration// When enabled, uses zstd compression for Redis values above threshold// The `default_test_config()` sets this to true for test/development scenarios.@@ -1194,6 +1208,7 @@ impl Config {internal_request_token: None,batch_flag_eval_max_limit: 10_000,batch_flag_eval_timeout_ms: 120_000,+ batch_flag_eval_scan_statement_timeout_ms: 10_000,billing_flush_interval_ms: 100,billing_max_pending_entries: 500_000,billing_per_flush_batch_size: 200,diff --git a/rust/feature-flags/src/database/pool_names.rs b/rust/feature-flags/src/database/pool_names.rsindex 95c6fcd830ac..a19ab6793aba 100644--- a/rust/feature-flags/src/database/pool_names.rs+++ b/rust/feature-flags/src/database/pool_names.rs@@ -11,3 +11,4 @@ pub const PERSONS_READER: &str = "persons_reader";pub const PERSONS_WRITER: &str = "persons_writer";pub const NON_PERSONS_READER: &str = "non_persons_reader";pub const NON_PERSONS_WRITER: &str = "non_persons_writer";+pub const BEHAVIORAL_COHORTS: &str = "behavioral_cohorts";diff --git a/rust/feature-flags/src/database_pools.rs b/rust/feature-flags/src/database_pools.rsindex ef56dd11a311..47533bab4a7c 100644--- a/rust/feature-flags/src/database_pools.rs+++ b/rust/feature-flags/src/database_pools.rs@@ -1,5 +1,6 @@use crate::api::errors::FlagError;use crate::config::Config;+use crate::database::pool_names;use common_database::{get_pool_with_config, PoolConfig};use sqlx::PgPool;use std::sync::Arc;@@ -21,6 +22,8 @@ impl DatabasePools {/// Default value for max_connections when config value is invalid (matches PoolConfig::default)const DEFAULT_MAX_CONNECTIONS: u32 = 10;+ const BEHAVIORAL_COHORTS_STATEMENT_TIMEOUT_MS: u64 = 1000;+/// Helper to build a pool configuration, overriding specific fields from the base config.fn build_pool_config(base: &PoolConfig,@@ -42,6 +45,55 @@ impl DatabasePools {}}+ /// Lists each pool, with its statement timeout, where one call can outlast the request timeout.+ /// A statement timeout of 0 leaves the query unbounded.+ ///+ /// This bounds one call, not one request. A request that runs several calls in sequence can+ /// still outlast the request timeout.+ ///+ /// A pool that aliases another pool runs with that pool's statement timeout. The check skips+ /// an aliased pool, because its own setting has no effect.+ fn pools_over_request_timeout(config: &Config) -> Vec<(&'static str, u64)> {+ let acquire_ms = config.acquire_timeout_secs.saturating_mul(1000);+ let routing = config.is_persons_db_routing_enabled();+ let writes = !*config.skip_writes;+ [+ (+ pool_names::NON_PERSONS_READER,+ config.non_persons_reader_statement_timeout_ms,+ true,+ ),+ (+ pool_names::PERSONS_READER,+ config.persons_reader_statement_timeout_ms,+ routing,+ ),+ (+ pool_names::PERSONS_WRITER,+ config.writer_statement_timeout_ms,+ routing && writes,+ ),+ (+ pool_names::NON_PERSONS_WRITER,+ config.writer_statement_timeout_ms,+ writes,+ ),+ (+ pool_names::BEHAVIORAL_COHORTS,+ Self::BEHAVIORAL_COHORTS_STATEMENT_TIMEOUT_MS,+ config.is_behavioral_cohorts_db_configured(),+ ),+ ]+ .into_iter()+ .filter(|&(_, statement_timeout_ms, built)| {+ built+ && (statement_timeout_ms == 0+ || acquire_ms.saturating_add(statement_timeout_ms) >= config.request_timeout_ms)+ })+ .map(|(pool, statement_timeout_ms, _)| (pool, statement_timeout_ms))+ .collect()+ }+pub async fn from_config(config: &Config) -> Result<Self, FlagError> {// Validate acquire_timeout_secs - must be at least 1 secondif config.acquire_timeout_secs == 0 {@@ -50,6 +102,16 @@ impl DatabasePools {)));}+ for (pool, statement_timeout_ms) in Self::pools_over_request_timeout(config) {+ tracing::warn!(+ pool,+ statement_timeout_ms,+ acquire_timeout_secs = config.acquire_timeout_secs,+ request_timeout_ms = config.request_timeout_ms,+ "Acquire timeout plus statement timeout on this pool does not fit inside REQUEST_TIMEOUT_MS (a statement timeout of 0 means none), so a slow query outlasts the request and its connection is closed"+ );+ }+// Validate and fix max_connections if it's 0let max_pg_connections = if config.max_pg_connections == 0 {tracing::warn!(@@ -271,8 +333,13 @@ impl DatabasePools {// Optional behavioral cohorts database pool for realtime cohort membership lookups.// Small pool (max 5 connections) with a tight 1s statement timeout for simple key lookups.let behavioral_cohorts_reader = if config.is_behavioral_cohorts_db_configured() {- let pool_config =- Self::build_pool_config(&base_pool_config, 1, Some(5), 1000, "behavioral_cohorts");+ let pool_config = Self::build_pool_config(+ &base_pool_config,+ 1,+ Some(5),+ Self::BEHAVIORAL_COHORTS_STATEMENT_TIMEOUT_MS,+ pool_names::BEHAVIORAL_COHORTS,+ );info!("Creating behavioral cohorts reader pool");Some(Arc::new(get_pool_with_config(&config.behavioral_cohorts_read_database_url, pool_config)@@ -303,6 +370,8 @@ impl DatabasePools {mod tests {use super::*;use crate::config::Config;+ use envconfig::Envconfig;+ use std::collections::HashMap;use std::sync::Arc;#[test]@@ -324,6 +393,70 @@ mod tests {assert_eq!(config.pool_name, Some("non_persons_writer".to_string()));}+ #[rstest::rstest]+ #[case::defaults(&[], &[])]+ #[case::statement_timeouts(+ &[+ ("NON_PERSONS_READER_STATEMENT_TIMEOUT_MS", "4000"),+ ("PERSONS_READER_STATEMENT_TIMEOUT_MS", "0"),+ ],+ &[(pool_names::NON_PERSONS_READER, 4000), (pool_names::PERSONS_READER, 0)]+ )]+ #[case::acquire(+ &[("ACQUIRE_TIMEOUT_SECS", "4")],+ &[+ (pool_names::NON_PERSONS_READER, 2000),+ (pool_names::PERSONS_READER, 1000),+ (pool_names::PERSONS_WRITER, 2000),+ (pool_names::NON_PERSONS_WRITER, 2000),+ ]+ )]+ #[case::behavioral_cohorts_configured(+ &[+ ("ACQUIRE_TIMEOUT_SECS", "4"),+ ("BEHAVIORAL_COHORTS_READ_DATABASE_URL", "postgres://localhost:5432/behavioral_cohorts"),+ ],+ &[+ (pool_names::NON_PERSONS_READER, 2000),+ (pool_names::PERSONS_READER, 1000),+ (pool_names::PERSONS_WRITER, 2000),+ (pool_names::NON_PERSONS_WRITER, 2000),+ (pool_names::BEHAVIORAL_COHORTS, 1000),+ ]+ )]+ #[case::sum_equals_request_timeout(+ &[("ACQUIRE_TIMEOUT_SECS", "2"), ("PERSONS_READER_STATEMENT_TIMEOUT_MS", "2500")],+ &[(pool_names::PERSONS_READER, 2500)]+ )]+ #[case::longer_request_timeout(+ &[("ACQUIRE_TIMEOUT_SECS", "4"), ("REQUEST_TIMEOUT_MS", "7000")],+ &[]+ )]+ #[case::persons_pools_aliased(+ &[+ ("PERSONS_READ_DATABASE_URL", ""),+ ("PERSONS_WRITE_DATABASE_URL", ""),+ ("PERSONS_READER_STATEMENT_TIMEOUT_MS", "0"),+ ],+ &[]+ )]+ #[case::writers_aliased(+ &[("SKIP_WRITES", "true"), ("WRITER_STATEMENT_TIMEOUT_MS", "0")],+ &[]+ )]+ fn test_pools_over_request_timeout(+ #[case] env: &[(&str, &str)],+ #[case] expected: &[(&str, u64)],+ ) {+ let env: HashMap<String, String> = env+ .iter()+ .map(|(k, v)| (k.to_string(), v.to_string()))+ .collect();+ let config = Config::init_from_hashmap(&env).unwrap();++ assert_eq!(DatabasePools::pools_over_request_timeout(&config), expected);+ }+#[tokio::test]async fn test_database_routing_disabled() {let config = Config {diff --git a/rust/feature-flags/src/flags/flag_matching_utils.rs b/rust/feature-flags/src/flags/flag_matching_utils.rsindex 48c4a8d21e44..bec7bde39112 100644--- a/rust/feature-flags/src/flags/flag_matching_utils.rs+++ b/rust/feature-flags/src/flags/flag_matching_utils.rs@@ -1,10 +1,12 @@use std::{collections::{HashMap, HashSet},+ future::Future,+ sync::Mutex,time::{Duration, Instant},};use tokio_retry::{strategy::{jitter, ExponentialBackoff},- Retry,+ RetryIf,};use crate::database::{@@ -49,8 +51,7 @@ const LONG_SCALE: u64 = 0xfffffffffffffff;const REPLICA_STALENESS_SAMPLE_RATE: f64 = 0.01;/// Bounds how long a detached check can occupy the writer pool. Covers connection acquisition as-/// well as the query, so a saturated pool kills the task here rather than at its 10s acquire-/// timeout.+/// well as the query, so a saturated pool kills the task here rather than at its acquire timeout.const REPLICA_STALENESS_CHECK_TIMEOUT: Duration = Duration::from_millis(50);/// Precomputed mapping from property name to its $initial_ equivalent.@@ -670,22 +671,14 @@ fn are_overrides_useful_for_flag(/// Classifies whether a FlagError is worth retrying.///-/// NOTE: this does not gate retries. The call sites use `Retry::spawn`, which retries-/// every `Err` unconditionally; this only labels metrics and logs. Switch to-/// `RetryIf::spawn` with this as the predicate if retries should actually be gated.+/// Timeouts are not retried. A second attempt could wait the full acquire and statement timeouts+/// again, which pushes the call past the request timeout. A foreign key violation is retried+/// because it means that a person was deleted during a hash key override write.fn should_retry_on_error(error: &FlagError) -> bool {- match error {- // Errors constructed with context (e.g. "Failed to fetch flags") bypass- // From<sqlx::Error> and still carry the raw error, so classify by transience here.- FlagError::DatabaseError(sqlx_error, _) => common_database::is_transient_error(sqlx_error),-- // Transient DB faults propagated via `?` (From<sqlx::Error>) or connection- // acquisition failures arrive already classified as DatabaseUnavailable (503).- FlagError::DatabaseUnavailable => true,-- // Other error types generally should not be retried- _ => false,- }+ matches!(+ classify_db_error(error),+ Some(("foreign_key" | "transient", _))+ )}/// Check if a FlagError contains a foreign key constraint violation@@ -699,17 +692,18 @@ fn flag_error_is_foreign_key_constraint(error: &FlagError) -> bool {}/// Maps a database-related FlagError to its `(error_type, timeout_subtype)` metric labels,-/// or None for errors that aren't tracked. Split out from `classify_and_track_error` so the-/// classification can be tested without observing the global counter.+/// or None for errors that aren't tracked.fn classify_db_error(error: &FlagError) -> Option<(&'static str, Option<&str>)> {let labels = match error {FlagError::DatabaseError(sqlx_error, _) => {+ // is_transient_error also accepts the statement timeout 57014. The timeout check+ // therefore runs first, so should_retry_on_error does not retry a timeout.let err_type = if common_database::is_foreign_key_constraint_error(sqlx_error) {"foreign_key"- } else if common_database::is_transient_error(sqlx_error) {- "transient"} else if common_database::is_timeout_error(sqlx_error) {"timeout"+ } else if common_database::is_transient_error(sqlx_error) {+ "transient"} else {// Errors reaching this arm were built with context, bypassing// From<sqlx::Error>; transient/timeout ones are caught above, so@@ -732,16 +726,11 @@ fn classify_db_error(error: &FlagError) -> Option<(&'static str, Option<&str>)>Some(labels)}-/// Classify and track database errors-fn classify_and_track_error(error: &FlagError, operation: &str, will_retry: bool) {- let Some((error_type, timeout_subtype)) = classify_db_error(error) else {- return;- };-+fn track_db_error(error_type: &str, timeout_subtype: Option<&str>, operation: &str, retried: bool) {let mut labels = vec![("error_type".to_string(), error_type.to_string()),("operation".to_string(), operation.to_string()),- ("retried".to_string(), will_retry.to_string()),+ ("retried".to_string(), retried.to_string()),];// Add timeout subtype if available@@ -752,6 +741,122 @@ fn classify_and_track_error(error: &FlagError, operation: &str, will_retry: boolcommon_metrics::inc(FLAG_DATABASE_ERROR_COUNTER, &labels, 1);}+/// Records `flags_hash_key_retries_total` and the `retried` label on `flags_database_error_total`+/// for one hash key override call.+///+/// `RetryIf` evaluates its condition before it checks whether any delays remain. The error alone+/// therefore does not tell an attempt whether a retry follows it. The caller can also drop the+/// call during the backoff, for example when the request times out. A failed attempt therefore+/// counts as retried only when the next attempt starts. If the call ends before that, `Drop`+/// records the error as not retried.+struct HashKeyRetryMetrics {+ team_id: TeamId,+ operation: &'static str,+ retries: usize,+ attempts: Mutex<Attempts>,+}++#[derive(Default)]+struct Attempts {+ started: usize,+ error_awaiting_retry: Option<(&'static str, Option<String>)>,+}++impl HashKeyRetryMetrics {+ fn new(team_id: TeamId, operation: &'static str, retries: usize) -> Self {+ Self {+ team_id,+ operation,+ retries,+ attempts: Mutex::default(),+ }+ }++ fn start(&self) {+ let mut attempts = self.attempts.lock().unwrap();+ if attempts.started > 0 {+ common_metrics::inc(+ FLAG_HASH_KEY_RETRIES_COUNTER,+ &[+ ("team_id".to_string(), self.team_id.to_string()),+ ("operation".to_string(), self.operation.to_string()),+ ],+ 1,+ );+ if let Some((error_type, timeout_subtype)) = attempts.error_awaiting_retry.take() {+ track_db_error(error_type, timeout_subtype.as_deref(), self.operation, true);+ }+ }+ attempts.started += 1;+ }++ /// Records the error of the attempt that started last and returns whether `RetryIf` retries it.+ fn fail(&self, error: &FlagError) -> bool {+ let mut attempts = self.attempts.lock().unwrap();+ let will_retry = attempts.started <= self.retries && should_retry_on_error(error);+ if let Some((error_type, timeout_subtype)) = classify_db_error(error) {+ if will_retry {+ attempts.error_awaiting_retry =+ Some((error_type, timeout_subtype.map(str::to_owned)));+ } else {+ track_db_error(error_type, timeout_subtype, self.operation, false);+ }+ }+ will_retry+ }+}++impl Drop for HashKeyRetryMetrics {+ fn drop(&mut self) {+ let error = self+ .attempts+ .get_mut()+ .ok()+ .and_then(|attempts| attempts.error_awaiting_retry.take());+ if let Some((error_type, timeout_subtype)) = error {+ track_db_error(+ error_type,+ timeout_subtype.as_deref(),+ self.operation,+ false,+ );+ }+ }+}++/// Runs a hash key override call and retries it after each of `retry_delays` while+/// `should_retry_on_error` accepts the error. `log_retry` runs for each error that gets a retry.+///+/// `HashKeyRetryMetrics::fail` is the `RetryIf` condition, so the metrics and the retry come from+/// one decision.+async fn retry_hash_key_call<T, Fut>(+ team_id: TeamId,+ operation: &'static str,+ retry_delays: Vec<Duration>,+ mut attempt: impl FnMut() -> Fut,+ log_retry: impl Fn(&FlagError),+) -> Result<T, FlagError>+where+ Fut: Future<Output = Result<T, FlagError>>,+{+ let metrics = HashKeyRetryMetrics::new(team_id, operation, retry_delays.len());+ RetryIf::spawn(+ retry_delays,+ || {+ metrics.start();+ attempt()+ },+ |e: &FlagError| {+ let will_retry = metrics.fail(e);+ if will_retry {+ log_retry(e);+ }+ will_retry+ },+ )+ .await+}+// Attempts to match a flag condition filter that depends on another flag// evaluation result to a flag evaluation resultpub fn match_flag_value_to_flag_filter(@@ -805,54 +910,34 @@ pub async fn get_feature_flag_hash_key_overrides(#[cfg(test)]increment_hash_key_override_lookup_count();- let retry_strategy = ExponentialBackoff::from_millis(50)+ let retry_delays: Vec<Duration> = ExponentialBackoff::from_millis(50).max_delay(Duration::from_millis(300))- .take(1) // 1 retry = 2 total attempts; keeps retry budget tight (~350ms worst case)- .map(jitter);-- // Use tokio-retry to automatically retry on transient failures- Retry::spawn(retry_strategy, || async {- let result = try_get_feature_flag_hash_key_overrides(- &reader,- pool_name,- &persons_writer,- team_id,- &distinct_id_and_hash_key_override,- )- .await;-- // Log retry attempts for observability- if let Err(ref e) = result {- let will_retry = should_retry_on_error(e);-- // Track error classification- classify_and_track_error(e, "get_hash_key_overrides", will_retry);-- if will_retry {- // Increment retry counter for monitoring- common_metrics::inc(- FLAG_HASH_KEY_RETRIES_COUNTER,- &[- ("team_id".to_string(), team_id.to_string()),- (- "operation".to_string(),- "get_hash_key_overrides".to_string(),- ),- ],- 1,- );-- tracing::warn!(- team_id = %team_id,- distinct_ids = ?distinct_id_and_hash_key_override,- error = ?e,- "Hash key override query failed, will retry"- );- }- }+ .take(1) // 1 retry = 2 total attempts+ .map(jitter)+ .collect();- result- })+ retry_hash_key_call(+ team_id,+ "get_hash_key_overrides",+ retry_delays,+ || {+ try_get_feature_flag_hash_key_overrides(+ &reader,+ pool_name,+ &persons_writer,+ team_id,+ &distinct_id_and_hash_key_override,+ )+ },+ |e| {+ tracing::warn!(+ team_id = %team_id,+ distinct_ids = ?distinct_id_and_hash_key_override,+ error = ?e,+ "Hash key override query failed, will retry"+ );+ },+ ).await}@@ -1072,61 +1157,35 @@ pub async fn set_feature_flag_hash_key_overrides(distinct_ids: Vec<String>,hash_key_override: String,) -> Result<bool, FlagError> {- let retry_strategy = ExponentialBackoff::from_millis(100)+ let retry_delays: Vec<Duration> = ExponentialBackoff::from_millis(100).max_delay(Duration::from_millis(300)).take(2)- .map(jitter); // Add jitter to prevent thundering herd-- // Use tokio-retry to automatically retry on transient failures- Retry::spawn(retry_strategy, || async {- let result = try_set_feature_flag_hash_key_overrides(- router,- team_id,- &distinct_ids,- &hash_key_override,- )- .await;-- // Only retry on foreign key constraint errors (person deletion race condition)- match &result {- Err(e) if flag_error_is_foreign_key_constraint(e) => {- // Track error classification- classify_and_track_error(e, "set_hash_key_overrides", true);-- // Increment retry counter for monitoring- common_metrics::inc(- FLAG_HASH_KEY_RETRIES_COUNTER,- &[- ("team_id".to_string(), team_id.to_string()),- (- "operation".to_string(),- "set_hash_key_overrides".to_string(),- ),- ],- 1,- );+ .map(jitter) // Add jitter to prevent thundering herd+ .collect();+ retry_hash_key_call(+ team_id,+ "set_hash_key_overrides",+ retry_delays,+ || {+ try_set_feature_flag_hash_key_overrides(+ router,+ team_id,+ &distinct_ids,+ &hash_key_override,+ )+ },+ |e| {+ if flag_error_is_foreign_key_constraint(e) {tracing::info!(team_id = %team_id,distinct_ids = ?distinct_ids,error = ?e,"Hash key override setting failed due to a person deletion race condition, will retry");-- // Return error to trigger retry- result- }- // For other errors, don't retry - return immediately to stop retrying- Err(e) => {- // Track error classification for non-retried errors- classify_and_track_error(e, "set_hash_key_overrides", false);-- result}- // Success case - return the result- Ok(_) => result,- }- })+ },+ ).await}@@ -1146,6 +1205,14 @@ async fn try_set_feature_flag_hash_key_overrides().await?;let mut transaction = persons_conn.begin().await?;+ // The foreign key from posthog_featureflaghashkeyoverride to posthog_person is deferred.+ // Postgres checks deferred keys at COMMIT. statement_timeout does not cover COMMIT. When+ // another transaction holds FOR UPDATE on the person row, as a delete does, the commit waits+ // until that transaction ends or the request times out. This statement moves the check into+ // the INSERT, where statement_timeout applies.+ sqlx::query("SET CONSTRAINTS ALL IMMEDIATE")+ .execute(&mut *transaction)+ .await?;// Query 1: Get all person data - person_ids + existing overrides + validation (person pool)let person_data_query = r#"@@ -1252,11 +1319,7 @@ async fn try_set_feature_flag_hash_key_overrides("set_hash_key_overrides",).await- .map_err(|e| {- sqlx::Error::Configuration(- format!("Failed to acquire non-persons connection: {e}").into(),- )- })?;+ .map_err(FlagError::from)?;let flags_labels = [(@@ -1401,54 +1464,20 @@ pub async fn should_write_hash_key_override(distinct_id: String,hash_key_override: String,) -> Result<bool, FlagError> {- let retry_strategy = ExponentialBackoff::from_millis(100)+ let retry_delays: Vec<Duration> = ExponentialBackoff::from_millis(100).max_delay(Duration::from_millis(300)).take(2)- .map(jitter); // Add jitter to prevent thundering herd-- let distinct_ids = vec![distinct_id.clone(), hash_key_override.clone()];-- // Use tokio-retry to automatically retry on transient failures- Retry::spawn(retry_strategy, || async {- let result = try_should_write_hash_key_override(router, team_id, &distinct_ids).await;-- // Only retry on foreign key constraint errors (person deletion race condition)- match &result {- Err(e) if flag_error_is_foreign_key_constraint(e) => {- // Increment retry counter for monitoring- common_metrics::inc(- FLAG_HASH_KEY_RETRIES_COUNTER,- &[- ("team_id".to_string(), team_id.to_string()),- (- "operation".to_string(),- "should_write_hash_key_override".to_string(),- ),- ],- 1,- );-- tracing::info!(- team_id = %team_id,- distinct_id = %distinct_id,- error = ?e,- "Hash key override check failed, will retry"- );-- // Return error to trigger retry- result- }- // For other errors, don't retry - return immediately to stop retrying- Err(e) => {- // Track error classification for non-retried errors- classify_and_track_error(e, "should_write_hash_key_override", false);-- result- }- // Success case - return the result- Ok(_) => result,- }- })+ .map(jitter) // Add jitter to prevent thundering herd+ .collect();+ let distinct_ids = vec![distinct_id, hash_key_override];++ retry_hash_key_call(+ team_id,+ "should_write_hash_key_override",+ retry_delays,+ || try_should_write_hash_key_override(router, team_id, &distinct_ids),+ |_| {},+ ).await}@@ -1712,14 +1741,20 @@ fn increment_hash_key_override_lookup_count() {#[cfg(test)]mod tests {+ use std::sync::atomic::Ordering;++ use common_database::{get_pool_with_config, PoolConfig};+ use futures::FutureExt;+ use metrics_util::debugging::DebuggingRecorder;use rstest::rstest;use serde_json::json;use crate::{+ config::DEFAULT_TEST_CONFIG,flags::flag_models::{FeatureFlag, FeatureFlagRow, FlagFilters},mock,properties::property_models::{OperatorType, PropertyFilter, PropertyType},- utils::test_utils::TestContext,+ utils::test_utils::{counter_total, CountingFailingClient, TestContext},};use super::*;@@ -2618,6 +2653,253 @@ mod tests {assert!(!result);}+ #[rstest]+ #[case::timeout(|| sqlx::Error::PoolTimedOut, 1, 1, 1)]+ #[case::transient(|| sqlx::Error::PoolClosed, 2, 3, 3)]+ #[tokio::test(start_paused = true)]+ async fn test_hash_key_override_retries(+ #[case] error: fn() -> sqlx::Error,+ #[case] read_attempts: usize,+ #[case] write_attempts: usize,+ #[case] check_attempts: usize,+ ) {+ let recorder = DebuggingRecorder::new();+ let snapshotter = recorder.snapshotter();+ let _guard = metrics::set_default_local_recorder(&recorder);++ let client = std::sync::Arc::new(CountingFailingClient::new(error));+ let router = PostgresRouter::new(+ client.clone(),+ client.clone(),+ client.clone(),+ client.clone(),+ );+ let calls = || client.calls.swap(0, Ordering::SeqCst);++ let read = get_feature_flag_hash_key_overrides(+ client.clone(),+ pool_names::PERSONS_READER,+ client.clone(),+ 1,+ vec!["user".to_string()],+ )+ .await;+ assert!(read.is_err());+ assert_eq!(calls(), read_attempts, "read attempts");++ let write = set_feature_flag_hash_key_overrides(+ &router,+ 1,+ vec!["user".to_string()],+ "hash".to_string(),+ )+ .await;+ assert!(write.is_err());+ assert_eq!(calls(), write_attempts, "write attempts");++ let check =+ should_write_hash_key_override(&router, 1, "user".to_string(), "hash".to_string())+ .await;+ assert!(check.is_err());+ assert_eq!(calls(), check_attempts, "check attempts");++ let counter =+ |name: &str, labels: &[(&str, &str)]| counter_total(&snapshotter, name, labels);+ for (operation, attempts) in [+ ("get_hash_key_overrides", read_attempts),+ ("set_hash_key_overrides", write_attempts),+ ("should_write_hash_key_override", check_attempts),+ ] {+ let retries = (attempts - 1) as u64;+ assert_eq!(+ counter(FLAG_HASH_KEY_RETRIES_COUNTER, &[("operation", operation)]),+ retries,+ "{operation} retries"+ );+ assert_eq!(+ counter(+ FLAG_DATABASE_ERROR_COUNTER,+ &[("operation", operation), ("retried", "true")]+ ),+ retries,+ "{operation} errors labeled retried"+ );+ assert_eq!(+ counter(+ FLAG_DATABASE_ERROR_COUNTER,+ &[("operation", operation), ("retried", "false")]+ ),+ 1,+ "{operation} final error labeled not retried"+ );+ }+ }++ #[tokio::test(start_paused = true)]+ async fn test_hash_key_override_dropped_during_backoff_counts_no_retry() {+ let recorder = DebuggingRecorder::new();+ let snapshotter = recorder.snapshotter();+ let _guard = metrics::set_default_local_recorder(&recorder);++ let client = std::sync::Arc::new(CountingFailingClient::new(|| sqlx::Error::PoolClosed));++ let read = get_feature_flag_hash_key_overrides(+ client.clone(),+ pool_names::PERSONS_READER,+ client.clone(),+ 1,+ vec!["user".to_string()],+ )+ .now_or_never();++ assert!(read.is_none(), "read finished instead of waiting to retry");+ assert_eq!(client.calls.load(Ordering::SeqCst), 1);+ let counter =+ |name: &str, labels: &[(&str, &str)]| counter_total(&snapshotter, name, labels);+ assert_eq!(counter(FLAG_HASH_KEY_RETRIES_COUNTER, &[]), 0);+ assert_eq!(+ counter(FLAG_DATABASE_ERROR_COUNTER, &[("retried", "true")]),+ 0+ );+ assert_eq!(+ counter(FLAG_DATABASE_ERROR_COUNTER, &[("retried", "false")]),+ 1+ );+ }++ #[tokio::test]+ async fn test_set_overrides_retries_transient_non_persons_acquire_failure() {+ let context = TestContext::new(None).await;+ let team = context.insert_new_team(None).await.unwrap();+ context+ .insert_person(team.id, "user".to_string(), None)+ .await+ .unwrap();++ let non_persons_reader =+ std::sync::Arc::new(CountingFailingClient::new(|| sqlx::Error::PoolClosed));+ let router = PostgresRouter::new(+ context.persons_reader.clone(),+ context.persons_writer.clone(),+ non_persons_reader.clone(),+ context.non_persons_writer.clone(),+ );++ let result = set_feature_flag_hash_key_overrides(+ &router,+ team.id,+ vec!["user".to_string()],+ "hash".to_string(),+ )+ .await;++ assert!(result.is_err());+ assert_eq!(non_persons_reader.calls.load(Ordering::SeqCst), 3);+ }++ #[tokio::test]+ async fn test_set_overrides_statement_timeout_covers_person_row_lock() {+ let context = TestContext::new(None).await;+ let team = context.insert_new_team(None).await.unwrap();+ let person_id = context+ .insert_person(team.id, "user".to_string(), None)+ .await+ .unwrap();+ let flag = mock!(FeatureFlag,+ team_id: team.id,+ ensure_experience_continuity: Some(true)+ );+ context+ .insert_flag(team.id, Some(mock!(FeatureFlagRow, from: flag)))+ .await+ .unwrap();++ let persons_writer: PostgresWriter = std::sync::Arc::new(+ get_pool_with_config(+ &DEFAULT_TEST_CONFIG.get_persons_write_database_url(),+ PoolConfig {+ statement_timeout_ms: Some(200),+ ..PoolConfig::default()+ },+ )+ .unwrap(),+ );+ let router = PostgresRouter::new(+ context.persons_reader.clone(),+ persons_writer,+ context.non_persons_reader.clone(),+ context.non_persons_writer.clone(),+ );++ // FOR UPDATE conflicts with the KEY SHARE lock that the foreign key check takes on the+ // person row.+ let mut lock_conn = context.persons_writer.get_connection().await.unwrap();+ let mut lock_tx = lock_conn.begin().await.unwrap();+ sqlx::query("SELECT id FROM posthog_person WHERE id = $1 FOR UPDATE")+ .bind(person_id)+ .execute(&mut *lock_tx)+ .await+ .unwrap();++ let result = timeout(+ Duration::from_secs(10),+ set_feature_flag_hash_key_overrides(+ &router,+ team.id,+ vec!["user".to_string()],+ "hash".to_string(),+ ),+ )+ .await+ .expect("the write waited for the person row lock instead of timing out");+ lock_tx.rollback().await.unwrap();++ assert!(+ matches!(result, Err(FlagError::TimeoutError(_))),+ "expected a statement timeout, got {result:?}"+ );+ }++ /// `common_database` has the same mock, but it is private to that crate's tests.+ #[derive(Debug)]+ struct MockDbError {+ code: &'static str,+ }++ impl std::fmt::Display for MockDbError {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ write!(f, "database error {}", self.code)+ }+ }++ impl std::error::Error for MockDbError {}++ impl sqlx::error::DatabaseError for MockDbError {+ fn message(&self) -> &str {+ "mock database error"+ }++ fn code(&self) -> Option<std::borrow::Cow<'_, str>> {+ Some(self.code.into())+ }++ fn as_error(&self) -> &(dyn std::error::Error + Send + Sync + 'static) {+ self+ }++ fn as_error_mut(&mut self) -> &mut (dyn std::error::Error + Send + Sync + 'static) {+ self+ }++ fn into_error(self: Box<Self>) -> Box<dyn std::error::Error + Send + Sync + 'static> {+ self+ }++ fn kind(&self) -> sqlx::error::ErrorKind {+ sqlx::error::ErrorKind::Other+ }+ }+#[tokio::test]async fn test_should_retry_on_error() {use sqlx::Error as SqlxError;@@ -2649,7 +2931,18 @@ mod tests {let protocol_timeout_error =FlagError::DatabaseError(SqlxError::Protocol("operation timeout".to_string()), None);- assert!(should_retry_on_error(&protocol_timeout_error));+ assert!(!should_retry_on_error(&protocol_timeout_error));++ let wrapped_statement_timeout = FlagError::DatabaseError(+ SqlxError::from(MockDbError { code: "57014" }),+ Some("Failed to fetch person data".to_string()),+ );+ assert!(!should_retry_on_error(&wrapped_statement_timeout));++ let foreign_key_violation: FlagError =+ SqlxError::from(MockDbError { code: "23503" }).into();+ assert!(flag_error_is_foreign_key_constraint(&foreign_key_violation));+ assert!(should_retry_on_error(&foreign_key_violation));// Test that configuration errors don't trigger retrieslet config_error = FlagError::DatabaseError(@@ -2709,6 +3002,15 @@ mod tests {);assert_eq!(classify_db_error(&contextual), Some(("unknown", None)));+ let contextual_statement_timeout = FlagError::DatabaseError(+ SqlxError::from(MockDbError { code: "57014" }),+ Some("Failed to fetch person data".to_string()),+ );+ assert_eq!(+ classify_db_error(&contextual_statement_timeout),+ Some(("timeout", None))+ );+let timeout = FlagError::TimeoutError(Some("pool_timeout".to_string()));assert_eq!(classify_db_error(&timeout),diff --git a/rust/feature-flags/src/metrics/consts.rs b/rust/feature-flags/src/metrics/consts.rsindex fe6ef097db83..14f35944a4c6 100644--- a/rust/feature-flags/src/metrics/consts.rs+++ b/rust/feature-flags/src/metrics/consts.rs@@ -88,6 +88,7 @@ pub const GEOIP_PROPERTIES_DIFFER_FROM_LOOKUP_COUNTER: &str =// (per-request sequential/parallel strategy metrics emitted from flag_matching.rs).pub const FLAG_BATCH_EVAL_REQUESTS_COUNTER: &str = "flags_batch_eval_requests_total";pub const FLAG_BATCH_EVAL_PERSONS_COUNTER: &str = "flags_batch_eval_persons_total";+pub const FLAG_BATCH_EVAL_PERSON_RETRIES_COUNTER: &str = "flags_batch_eval_person_retries_total";pub const FLAG_BATCH_EVAL_TIME: &str = "flags_batch_eval_duration_ms";pub const FLAG_QUEUE_TIME_MS: &str = "flags_queue_time_ms";pub const FLAG_REQUEST_FAULTS_COUNTER: &str = "flags_request_faults_total";diff --git a/rust/feature-flags/src/utils/test_utils.rs b/rust/feature-flags/src/utils/test_utils.rsindex a4e8a3ff3068..2825a10ba75a 100644--- a/rust/feature-flags/src/utils/test_utils.rs+++ b/rust/feature-flags/src/utils/test_utils.rs@@ -25,6 +25,7 @@ use rand::{distributions::Alphanumeric, Rng};use serde_json::{json, Value};use sqlx::{pool::PoolConnection, Error as SqlxError, Postgres, Row};use std::collections::{HashMap, HashSet};+use std::sync::atomic::{AtomicUsize, Ordering};use std::sync::Arc;use std::time::Duration;use uuid::Uuid;@@ -273,6 +274,29 @@ impl common_hypercache::S3Client for AlwaysMissS3Client {}}+#[cfg(test)]+pub fn counter_total(+ snapshotter: &metrics_util::debugging::Snapshotter,+ name: &str,+ labels: &[(&str, &str)],+) -> u64 {+ snapshotter+ .snapshot()+ .into_vec()+ .into_iter()+ .filter(|(key, ..)| {+ key.key().name() == name+ && labels+ .iter()+ .all(|(k, v)| key.key().labels().any(|l| l.key() == *k && l.value() == *v))+ })+ .map(|(.., value)| match value {+ metrics_util::debugging::DebugValue::Counter(c) => c,+ _ => 0,+ })+ .sum()+}+/// A dummy S3 client (always NotFound) for injecting into the test server.pub fn dummy_s3_client() -> Arc<dyn common_hypercache::S3Client + Send + Sync> {Arc::new(AlwaysMissS3Client)@@ -592,6 +616,32 @@ impl Client for MockPgClient {}}+pub struct CountingFailingClient {+ pub error: fn() -> SqlxError,+ pub calls: AtomicUsize,+}++impl CountingFailingClient {+ pub fn new(error: fn() -> SqlxError) -> Self {+ Self {+ error,+ calls: AtomicUsize::new(0),+ }+ }+}++#[async_trait]+impl Client for CountingFailingClient {+ async fn get_connection(&self) -> Result<PoolConnection<Postgres>, CustomDatabaseError> {+ self.calls.fetch_add(1, Ordering::SeqCst);+ Err(CustomDatabaseError::Other((self.error)()))+ }++ fn get_pool_stats(&self) -> Option<common_database::PoolStats> {+ None+ }+}+pub async fn setup_invalid_pg_client() -> Arc<dyn Client + Send + Sync> {Arc::new(MockPgClient)}