Skip to content

: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.

fix(flags): bound persons db work with a request deadline (#108017)

Phil Haackc1cc7f1ee2ab
diff --git a/docs/internal/feature-flags/database-interaction-patterns.md b/docs/internal/feature-flags/database-interaction-patterns.md
index 5b347775e64f..e92fe48e7758 100644
--- a/docs/internal/feature-flags/database-interaction-patterns.md
+++ b/docs/internal/feature-flags/database-interaction-patterns.md
@@ -75,6 +75,33 @@ Statement timeouts are set via `SET statement_timeout = {ms}` on each new connec
The same hook also increments the `db_connection_created_total` counter when `pool_name` is set, providing visibility into connection churn per pool.
+### Persons DB deadline
+
+`PERSONS_DB_DEADLINE_MS` (default 2500ms) bounds all persons DB work in one flag evaluation.
+The hash key override check, write, and read, and the person, cohort, and group properties fetch share one deadline, so sequential calls cannot add up past it.
+The deadline starts when the matcher is built, just before evaluation.
+Postgres `statement_timeout` cannot cancel a query on a database that has stopped answering, so once a query is in flight this client-side timer is the only bound.
+When the pool has no free connection, the pool acquire timeout (`ACQUIRE_TIMEOUT_SECS`) can fire first, and the call fails with `timeout:pool_timeout` instead.
+
+When the deadline passes, the call fails with `FlagError::TimeoutError("persons_db_deadline")` and the existing degrade path runs:
+
+- Flags that need persons data return `reason.code = "timeout:persons_db_deadline"`. Experience continuity flags return `hash_key_override_error`.
+- The other flags evaluate normally.
+- The request returns a 200 with `errorsWhileComputingFlags: true`.
+
+A call that would start after the deadline fails without taking a connection.
+Each stopped call increments `flags_database_error_total` with `timeout_type="persons_db_deadline"` and the call's `operation`.
+The canonical log line records the first stopped call in `persons_db_deadline_exceeded`.
+The internal batch evaluation endpoint does not apply the deadline. When a person's evaluation returns an error, Django leaves that person out of the static cohort and still reports the run as a success.
+Set `PERSONS_DB_DEADLINE_MS=0` to disable the deadline.
+
+A query that the deadline drops mid-flight keeps its connection until sqlx's on-release ping finishes.
+The ping waits for the dropped query.
+If the query completes, the connection goes back to the pool.
+If `statement_timeout` cancels the query, the ping fails and sqlx closes the connection.
+If the database never answers, the connection stays checked out.
+Keep the persons statement timeouts below the deadline so that Postgres cancels ordinary slow queries before the deadline drops them.
+
### Total connection count
```text
@@ -292,33 +319,34 @@ let retry_strategy = ExponentialBackoff::from_millis(100)
### Prometheus metrics
-| Metric | Labels | Purpose |
-| ------------------------------------------ | ---------------------- | ------------------------------------------------------------------------------------------------------ |
-| `flags_db_connection_time` | `pool`, `operation` | Connection acquisition latency (sub-ms precision, bucket floor 0.05ms) |
-| `flags_person_query_time` | - | Person lookup query duration |
-| `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` | 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) |
-| `flags_db_connection_pool_active_total` | `pool` | Active (in-use) connections |
-| `flags_db_connection_pool_idle_total` | `pool` | Idle (available) connections |
-| `flags_db_connection_pool_max_total` | `pool` | Configured maximum connections |
-| `flags_queue_time_ms` | `team_id` | Request queue wait time (bucket ceiling 30000ms) |
-| `flags_pre_handler_time_ms` | `team_id` | Pre-handler work timing (UA parse, rate limit checks, token extract) |
-| `flags_rate_limit_check_ms` | `kind` | Rate limit check duration (`kind="ip"` or `kind="token"`) |
-| `flags_token_extract_ms` | - | Token extraction timing |
-| `flags_concurrency_limit_wait_ms` | - | Concurrency limit permit wait time (pod-level, no `team_id`) |
-| `flags_realtime_cohort_query_time` | `team_id` | Realtime cohort lookup at the evaluation site, including cache hits (sub-ms precision) |
-| `flags_realtime_cohort_query_error_total` | `team_id` | Realtime cohort lookups that failed and degraded to non-membership |
-| `flags_realtime_cohort_db_query_time` | `outcome` | Behavioral cohorts DB query latency (`success`, `error`, `timeout`; sub-ms precision, 20ms SLO bucket) |
-| `flags_db_cohort_membership_reads_total` | - | Successful behavioral cohorts DB reads |
-| `flags_db_cohort_membership_errors_total` | - | Failed or timed-out behavioral cohorts DB reads |
-| `flags_cohort_membership_cache_hit_total` | - | Membership lookups fully served from the Moka cache |
-| `flags_cohort_membership_cache_miss_total` | - | Membership lookups that issued a behavioral cohorts DB query |
-| `flags_cohort_membership_cache_entries` | - | Current entries in the membership cache (one per team + person pair) |
+| Metric | Labels | Purpose |
+| ------------------------------------------ | ---------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| `flags_db_connection_time` | `pool`, `operation` | Connection acquisition latency (sub-ms precision, bucket floor 0.05ms) |
+| `flags_person_query_time` | - | Person lookup query duration |
+| `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` | Retries that started. A failed attempt counts only when its retry starts |
+| `flags_flag_evaluation_error_total` | `error_type` | Error counter |
+| `flags_database_error_total` | `error_type`, `operation`, `retried`, `timeout_type` | Database errors by operation. `timeout_type="persons_db_deadline"` counts persons DB calls stopped by `PERSONS_DB_DEADLINE_MS`, including calls skipped because it had passed |
+| `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) |
+| `flags_db_connection_pool_active_total` | `pool` | Active (in-use) connections |
+| `flags_db_connection_pool_idle_total` | `pool` | Idle (available) connections |
+| `flags_db_connection_pool_max_total` | `pool` | Configured maximum connections |
+| `flags_queue_time_ms` | `team_id` | Request queue wait time (bucket ceiling 30000ms) |
+| `flags_pre_handler_time_ms` | `team_id` | Pre-handler work timing (UA parse, rate limit checks, token extract) |
+| `flags_rate_limit_check_ms` | `kind` | Rate limit check duration (`kind="ip"` or `kind="token"`) |
+| `flags_token_extract_ms` | - | Token extraction timing |
+| `flags_concurrency_limit_wait_ms` | - | Concurrency limit permit wait time (pod-level, no `team_id`) |
+| `flags_realtime_cohort_query_time` | `team_id` | Realtime cohort lookup at the evaluation site, including cache hits (sub-ms precision) |
+| `flags_realtime_cohort_query_error_total` | `team_id` | Realtime cohort lookups that failed and degraded to non-membership |
+| `flags_realtime_cohort_db_query_time` | `outcome` | Behavioral cohorts DB query latency (`success`, `error`, `timeout`; sub-ms precision, 20ms SLO bucket) |
+| `flags_db_cohort_membership_reads_total` | - | Successful behavioral cohorts DB reads |
+| `flags_db_cohort_membership_errors_total` | - | Failed or timed-out behavioral cohorts DB reads |
+| `flags_cohort_membership_cache_hit_total` | - | Membership lookups fully served from the Moka cache |
+| `flags_cohort_membership_cache_miss_total` | - | Membership lookups that issued a behavioral cohorts DB query |
+| `flags_cohort_membership_cache_entries` | - | Current entries in the membership cache (one per team + person pair) |
### Example PromQL queries
@@ -374,6 +402,7 @@ Queries exceeding 500ms are logged at WARN level with timing information.
| `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 |
+| `PERSONS_DB_DEADLINE_MS` | 2500 | Deadline shared by all persons DB calls in one evaluation |
### Tuning guidance
diff --git a/rust/feature-flags/src/api/batch_flag_evaluation.rs b/rust/feature-flags/src/api/batch_flag_evaluation.rs
index a85c246e16cb..370f86b578b7 100644
--- a/rust/feature-flags/src/api/batch_flag_evaluation.rs
+++ b/rust/feature-flags/src/api/batch_flag_evaluation.rs
@@ -22,6 +22,10 @@
//! caller reads only the target's `enabled`.
//! - Flags are always read fresh from Postgres (never the hypercache) so the
//! `expected_version` optimistic-lock check is meaningful.
+//! - The matcher runs without the persons DB deadline (`PERSONS_DB_DEADLINE_MS`). When a
+//! person's evaluation returns an error, Django leaves that person out of the cohort and
+//! still reports the run as a success. A slow persons query must therefore finish rather
+//! than time out.
//!
//! The paged scan walks `posthog_person.id` ascending across a live table, so the run sees
//! a moving snapshot rather than a point-in-time one: persons inserted above the current
diff --git a/rust/feature-flags/src/api/errors.rs b/rust/feature-flags/src/api/errors.rs
index a411faf6cc9f..ab236d170d67 100644
--- a/rust/feature-flags/src/api/errors.rs
+++ b/rust/feature-flags/src/api/errors.rs
@@ -107,6 +107,7 @@ pub enum FlagError {
/// - `"io_timeout"` - Network/socket timeout
/// - `"protocol_timeout"` - PostgreSQL protocol timeout
/// - `"client_timeout"` - Client-side tokio::timeout wrapper
+ /// - `"persons_db_deadline"` - Deadline shared by all persons DB work in one flag evaluation
/// - `"redis_timeout"` - Redis operation timeout
/// - `"cache_timeout"` - Cache operation timeout
/// - `"database_timeout"` - Generic database timeout (fallback when SQLSTATE unavailable)
@@ -139,6 +140,8 @@ pub(crate) const CODE_FLAG_DATA_PARSING: &str = "flag_data_parsing_error";
pub(crate) const CODE_PERSON_NOT_FOUND: &str = "person_not_found";
pub(crate) const CODE_DEPENDENCY_FAILED: &str = "dependency_failed";
+const TIMEOUT_PERSONS_DB_DEADLINE: &str = "persons_db_deadline";
+
impl FlagError {
/// The `Internal error: ` prefix reaches customers as the `$feature_flag_reason`
/// event property, so changing it changes their data. `context` keeps the chain.
@@ -201,6 +204,14 @@ impl FlagError {
}
}
+ pub fn persons_db_deadline() -> Self {
+ FlagError::TimeoutError(Some(TIMEOUT_PERSONS_DB_DEADLINE.to_string()))
+ }
+
+ pub fn is_persons_db_deadline(&self) -> bool {
+ matches!(self, FlagError::TimeoutError(Some(t)) if t == TIMEOUT_PERSONS_DB_DEADLINE)
+ }
+
/// Returns (error_code, status_code) for this error.
///
/// This consolidates error classification in one place to ensure consistency
diff --git a/rust/feature-flags/src/config.rs b/rust/feature-flags/src/config.rs
index 759b0f88aa46..d88d6f0cc9b5 100644
--- a/rust/feature-flags/src/config.rs
+++ b/rust/feature-flags/src/config.rs
@@ -435,6 +435,15 @@ pub struct Config {
#[envconfig(from = "REALTIME_COHORT_LOOKUP_TIMEOUT_MS", default = "1000")]
pub realtime_cohort_lookup_timeout_ms: u64,
+ // Deadline shared by all persons DB calls in one /flags evaluation: the hash key override
+ // check, write, and read, and the properties fetch.
+ // statement_timeout cannot cancel a query on a database that has stopped answering.
+ // Only this timer bounds the request then. On expiry, the flags that need persons data
+ // return an error and the other flags evaluate normally. The default leaves 2s of the
+ // 4.5s REQUEST_TIMEOUT_MS for the rest of the request. 0 disables the deadline.
+ #[envconfig(from = "PERSONS_DB_DEADLINE_MS", default = "2500")]
+ pub persons_db_deadline_ms: u64,
+
#[envconfig(default = "1000")]
pub max_concurrency: usize,
@@ -1151,6 +1160,7 @@ impl Config {
cohort_membership_cache_ttl_seconds: 60,
cohort_membership_cache_max_entries: 50_000,
realtime_cohort_lookup_timeout_ms: 1000,
+ persons_db_deadline_ms: 30_000,
max_concurrency: 1000,
max_pg_connections: 10,
min_non_persons_reader_connections: 0,
@@ -1323,6 +1333,12 @@ impl Config {
}
}
+ /// The budget for all persons DB work in one flag evaluation, or `None` when disabled.
+ pub fn persons_db_deadline(&self) -> Option<std::time::Duration> {
+ (self.persons_db_deadline_ms > 0)
+ .then(|| std::time::Duration::from_millis(self.persons_db_deadline_ms))
+ }
+
/// Check if persons database routing is enabled
pub fn is_persons_db_routing_enabled(&self) -> bool {
!self.persons_read_database_url.is_empty() && !self.persons_write_database_url.is_empty()
diff --git a/rust/feature-flags/src/flags/flag_matching.rs b/rust/feature-flags/src/flags/flag_matching.rs
index af85a6854856..d20c4308c502 100644
--- a/rust/feature-flags/src/flags/flag_matching.rs
+++ b/rust/feature-flags/src/flags/flag_matching.rs
@@ -16,10 +16,10 @@ use crate::flags::flag_group_type_mapping::{
};
use crate::flags::flag_match_reason::FeatureFlagMatchReason;
use crate::flags::flag_matching_utils::{
- calculate_hash, fetch_and_locally_cache_all_relevant_properties,
+ calculate_hash, db_operations, fetch_and_locally_cache_all_relevant_properties,
get_feature_flag_hash_key_overrides, match_flag_value_to_flag_filter,
populate_missing_initial_properties, populate_os_aliases, set_feature_flag_hash_key_overrides,
- should_write_hash_key_override,
+ should_write_hash_key_override, track_unretried_db_error,
};
use crate::flags::flag_models::{
default_has_experiment, FeatureFlag, FeatureFlagId, FeatureFlagList, FlagFilters,
@@ -42,6 +42,7 @@ use crate::metrics::consts::{
use crate::properties::property_matching::{match_property, PropertyMatchingContext};
use crate::properties::property_models::{OperatorType, PropertyFilter, PropertyType};
use crate::rayon_dispatcher::RayonDispatcher;
+use crate::utils::deadline::before_deadline;
use crate::utils::graph_utils::PrecomputedDependencyGraph;
use anyhow::Result;
use chrono::{DateTime, Utc};
@@ -52,7 +53,10 @@ use common_types::{PersonId, TeamId};
use rayon::prelude::*;
use serde_json::Value;
use std::collections::{HashMap, HashSet};
+use std::future::Future;
use std::sync::Arc;
+use std::time::Duration;
+use tokio::time::Instant;
use tracing::{debug, error, instrument, warn};
use uuid::Uuid;
@@ -489,6 +493,9 @@ pub struct FeatureFlagMatcher {
timezone: Tz,
/// Request evaluation time. Only v2 relative-date predicates read it; tests pin it.
now: DateTime<Utc>,
+ /// Every persons DB call in this evaluation fails once this instant passes. `None` leaves
+ /// each call bounded only by the pool acquire timeout and statement_timeout.
+ persons_db_deadline: Option<Instant>,
}
/// Lightweight snapshot of a flag's identity fields, saved before moving
@@ -537,6 +544,36 @@ fn ids_of_failed_flags<'a>(
.map(|details| details.metadata.id)
}
+// This is a plain fn rather than an `async fn` so that it boxes `call` before any async state
+// captures it. An `async fn` would store `call` in its own state. The `before_deadline` and
+// `timeout_at` futures store it again. In debug builds those copies grow the /flags handler
+// future enough to overflow a 2 MiB thread stack.
+fn before_persons_db_deadline<T>(
+ deadline: Option<Instant>,
+ operation: &'static str,
+ call: impl Future<Output = Result<T, FlagError>>,
+) -> impl Future<Output = Result<T, FlagError>> {
+ let call = Box::pin(call);
+ async move {
+ let result = before_deadline(deadline, call, FlagError::persons_db_deadline).await;
+ record_persons_db_deadline_exceeded(operation, &result);
+ result
+ }
+}
+
+fn record_persons_db_deadline_exceeded<T>(operation: &'static str, result: &Result<T, FlagError>) {
+ let Err(e) = result else {
+ return;
+ };
+ if !e.is_persons_db_deadline() {
+ return;
+ }
+ track_unretried_db_error(e, operation);
+ with_canonical_log(|log| {
+ log.persons_db_deadline_exceeded.get_or_insert(operation);
+ });
+}
+
impl FeatureFlagMatcher {
#[allow(clippy::too_many_arguments)]
pub fn new(
@@ -572,6 +609,7 @@ impl FeatureFlagMatcher {
only_use_override_person_properties: false,
timezone: Tz::UTC,
now: Utc::now(),
+ persons_db_deadline: None,
}
}
@@ -641,6 +679,12 @@ impl FeatureFlagMatcher {
self
}
+ /// Gives all persons DB work in this evaluation one shared budget, which starts now.
+ pub fn with_persons_db_deadline(mut self, budget: Option<Duration>) -> Self {
+ self.persons_db_deadline = budget.map(|budget| Instant::now() + budget);
+ self
+ }
+
/// Evaluates all feature flags for the current matcher context.
///
/// ## Arguments
@@ -812,11 +856,15 @@ impl FeatureFlagMatcher {
hash_key: String,
target_distinct_ids: Vec<String>,
) -> (Option<HashMap<String, String>>, bool) {
- let should_write = match should_write_hash_key_override(
- &self.router,
- self.team_id,
- self.distinct_id.clone(),
- hash_key.clone(),
+ let should_write = match before_persons_db_deadline(
+ self.persons_db_deadline,
+ db_operations::SHOULD_WRITE_HASH_KEY_OVERRIDE,
+ should_write_hash_key_override(
+ &self.router,
+ self.team_id,
+ self.distinct_id.clone(),
+ hash_key.clone(),
+ ),
)
.await
{
@@ -845,12 +893,16 @@ impl FeatureFlagMatcher {
"SKIP_WRITES: skipping hash key override write to PostgreSQL"
);
} else {
- if let Err(e) = set_feature_flag_hash_key_overrides(
- // NB: this is the only method that writes to the database
- &self.router,
- self.team_id,
- target_distinct_ids.clone(),
- hash_key.clone(),
+ // NB: this is the only method that writes to the database
+ if let Err(e) = before_persons_db_deadline(
+ self.persons_db_deadline,
+ db_operations::SET_HASH_KEY_OVERRIDES,
+ set_feature_flag_hash_key_overrides(
+ &self.router,
+ self.team_id,
+ target_distinct_ids.clone(),
+ hash_key.clone(),
+ ),
)
.await
{
@@ -890,12 +942,16 @@ impl FeatureFlagMatcher {
)
};
- match get_feature_flag_hash_key_overrides(
- database_for_reading,
- pool_name,
- self.router.get_persons_writer().clone(),
- self.team_id,
- target_distinct_ids,
+ match before_persons_db_deadline(
+ self.persons_db_deadline,
+ db_operations::GET_HASH_KEY_OVERRIDES,
+ get_feature_flag_hash_key_overrides(
+ database_for_reading,
+ pool_name,
+ self.router.get_persons_writer().clone(),
+ self.team_id,
+ target_distinct_ids,
+ ),
)
.await
{
@@ -2756,13 +2812,17 @@ impl FeatureFlagMatcher {
// Single DB operation for properties and cohorts
let db_fetch_timer = common_metrics::timing_guard(FLAG_DB_PROPERTIES_FETCH_TIME, &[]);
- match fetch_and_locally_cache_all_relevant_properties(
- &mut self.flag_evaluation_state,
- self.router.get_persons_reader().clone(),
- self.distinct_id.clone(),
- self.team_id,
- &group_data,
- static_cohort_ids,
+ match before_persons_db_deadline(
+ self.persons_db_deadline,
+ db_operations::FETCH_PROPERTIES,
+ fetch_and_locally_cache_all_relevant_properties(
+ &mut self.flag_evaluation_state,
+ self.router.get_persons_reader().clone(),
+ self.distinct_id.clone(),
+ self.team_id,
+ &group_data,
+ static_cohort_ids,
+ ),
)
.await
{
@@ -3007,12 +3067,16 @@ impl FeatureFlagMatcher {
// will be inconsistent because server sdks won't include $anon_distinct_id in their requests.
// In addition, this behavior is consistent with /decide.
None => {
- match get_feature_flag_hash_key_overrides(
- self.router.get_persons_reader().clone(),
- pool_names::PERSONS_READER,
- self.router.get_persons_writer().clone(),
- self.team_id,
- vec![self.distinct_id.clone()],
+ match before_persons_db_deadline(
+ self.persons_db_deadline,
+ db_operations::GET_HASH_KEY_OVERRIDES,
+ get_feature_flag_hash_key_overrides(
+ self.router.get_persons_reader().clone(),
+ pool_names::PERSONS_READER,
+ self.router.get_persons_writer().clone(),
+ self.team_id,
+ vec![self.distinct_id.clone()],
+ ),
)
.await
{
diff --git a/rust/feature-flags/src/flags/flag_matching_utils.rs b/rust/feature-flags/src/flags/flag_matching_utils.rs
index 310416f6ac68..5baa968ce61e 100644
--- a/rust/feature-flags/src/flags/flag_matching_utils.rs
+++ b/rust/feature-flags/src/flags/flag_matching_utils.rs
@@ -603,7 +603,8 @@ pub async fn fetch_and_locally_cache_all_relevant_properties(
let (person_cohort, group) = tokio::try_join!(
fetch_person_and_cohorts(&reader, team_id, &distinct_id, &static_cohort_ids),
fetch_group_properties(&reader, team_id, group_type_to_key),
- )?;
+ )
+ .inspect_err(|e| track_unretried_db_error(e, db_operations::FETCH_PROPERTIES))?;
apply_person_cohort_to_state(flag_evaluation_state, person_cohort);
// Mark every requested index as fetched, not just the ones the query returned a
@@ -619,7 +620,9 @@ pub async fn fetch_and_locally_cache_all_relevant_properties(
}
} else {
let person_cohort =
- fetch_person_and_cohorts(&reader, team_id, &distinct_id, &static_cohort_ids).await?;
+ fetch_person_and_cohorts(&reader, team_id, &distinct_id, &static_cohort_ids)
+ .await
+ .inspect_err(|e| track_unretried_db_error(e, db_operations::FETCH_PROPERTIES))?;
apply_person_cohort_to_state(flag_evaluation_state, person_cohort);
}
@@ -743,6 +746,22 @@ fn track_db_error(error_type: &str, timeout_subtype: Option<&str>, operation: &s
common_metrics::inc(FLAG_DATABASE_ERROR_COUNTER, &labels, 1);
}
+pub(crate) fn track_unretried_db_error(error: &FlagError, operation: &str) {
+ if let Some((error_type, timeout_subtype)) = classify_db_error(error) {
+ track_db_error(error_type, timeout_subtype, operation, false);
+ }
+}
+
+/// `operation` label values for persons DB calls. The deadline wrapper in `flag_matching.rs`
+/// and the call itself both count errors in `flags_database_error_total` under this label.
+/// A mismatched literal splits one operation's errors into two series and fails nothing.
+pub(crate) mod db_operations {
+ pub const SHOULD_WRITE_HASH_KEY_OVERRIDE: &str = "should_write_hash_key_override";
+ pub const SET_HASH_KEY_OVERRIDES: &str = "set_hash_key_overrides";
+ pub const GET_HASH_KEY_OVERRIDES: &str = "get_hash_key_overrides";
+ pub const FETCH_PROPERTIES: &str = "fetch_properties";
+}
+
/// Records `flags_hash_key_retries_total` and the `retried` label on `flags_database_error_total`
/// for one hash key override call.
///
@@ -920,7 +939,7 @@ pub async fn get_feature_flag_hash_key_overrides(
retry_hash_key_call(
team_id,
- "get_hash_key_overrides",
+ db_operations::GET_HASH_KEY_OVERRIDES,
retry_delays,
|| {
try_get_feature_flag_hash_key_overrides(
@@ -1188,7 +1207,7 @@ pub async fn set_feature_flag_hash_key_overrides(
retry_hash_key_call(
team_id,
- "set_hash_key_overrides",
+ db_operations::SET_HASH_KEY_OVERRIDES,
retry_delays,
|| {
try_set_feature_flag_hash_key_overrides(
@@ -1271,7 +1290,7 @@ async fn try_set_feature_flag_hash_key_overrides(
),
(
"operation".to_string(),
- "set_hash_key_overrides".to_string(),
+ db_operations::SET_HASH_KEY_OVERRIDES.to_string(),
),
("pool".to_string(), pool_names::PERSONS_WRITER.to_string()),
("team_id".to_string(), team_id.to_string()),
@@ -1331,7 +1350,7 @@ async fn try_set_feature_flag_hash_key_overrides(
let mut non_persons_conn = get_connection_with_metrics(
router.get_non_persons_reader(),
pool_names::NON_PERSONS_READER,
- "set_hash_key_overrides",
+ db_operations::SET_HASH_KEY_OVERRIDES,
)
.await
.map_err(FlagError::from)?;
@@ -1343,7 +1362,7 @@ async fn try_set_feature_flag_hash_key_overrides(
),
(
"operation".to_string(),
- "set_hash_key_overrides".to_string(),
+ db_operations::SET_HASH_KEY_OVERRIDES.to_string(),
),
(
"pool".to_string(),
@@ -1411,7 +1430,7 @@ async fn try_set_feature_flag_hash_key_overrides(
("query".to_string(), "bulk_insert_overrides".to_string()),
(
"operation".to_string(),
- "set_hash_key_overrides".to_string(),
+ db_operations::SET_HASH_KEY_OVERRIDES.to_string(),
),
("pool".to_string(), pool_names::PERSONS_WRITER.to_string()),
("team_id".to_string(), team_id.to_string()),
@@ -1489,7 +1508,7 @@ pub async fn should_write_hash_key_override(
retry_hash_key_call(
team_id,
- "should_write_hash_key_override",
+ db_operations::SHOULD_WRITE_HASH_KEY_OVERRIDE,
retry_delays,
|| try_should_write_hash_key_override(router, team_id, &distinct_ids),
|_| {},
@@ -1593,7 +1612,7 @@ async fn try_should_write_hash_key_override(
("pool".to_string(), pool_names::PERSONS_READER.to_string()),
(
"operation".to_string(),
- "should_write_hash_key_override".to_string(),
+ db_operations::SHOULD_WRITE_HASH_KEY_OVERRIDE.to_string(),
),
],
1,
@@ -1681,7 +1700,7 @@ async fn try_should_write_hash_key_override(
),
(
"operation".to_string(),
- "should_write_hash_key_override".to_string(),
+ db_operations::SHOULD_WRITE_HASH_KEY_OVERRIDE.to_string(),
),
],
1,
diff --git a/rust/feature-flags/src/flags/test_flag_matching.rs b/rust/feature-flags/src/flags/test_flag_matching.rs
index be2f9ea3f274..8453fbcb9fc7 100644
--- a/rust/feature-flags/src/flags/test_flag_matching.rs
+++ b/rust/feature-flags/src/flags/test_flag_matching.rs
@@ -7,6 +7,7 @@ mod tests {
use std::collections::{HashMap, HashSet};
use std::sync::atomic::{AtomicU32, Ordering};
use std::sync::Arc;
+ use std::time::Duration;
use uuid::Uuid;
use crate::{
@@ -31,17 +32,20 @@ mod tests {
Holdout, MultivariateFlagOptions, MultivariateFlagVariant,
},
},
+ handler::canonical_log::{run_with_canonical_log, FlagsCanonicalLogLine},
+ metrics::consts::FLAG_DATABASE_ERROR_COUNTER,
mock,
properties::property_models::{OperatorType, PropertyFilter, PropertyType},
utils::{
graph_utils::PrecomputedDependencyGraph,
mock::MockInto,
test_utils::{
- failing_group_type_cache, flag_list_with_metadata, mock_group_type_cache,
- setup_invalid_pg_client, TestContext,
+ counter_total, failing_group_type_cache, flag_list_with_metadata,
+ mock_group_type_cache, setup_invalid_pg_client, StalledPgClient, TestContext,
},
},
};
+ use metrics_util::debugging::DebuggingRecorder;
fn empty_group_type_cache() -> Arc<GroupTypeCacheManager> {
mock_group_type_cache(HashMap::new())
@@ -8165,6 +8169,118 @@ mod tests {
);
}
+ // Paused time makes the elapsed assertion exact: the runtime jumps straight to each timer.
+ #[rstest::rstest]
+ #[case::hash_key_read(None, "get_hash_key_overrides")]
+ #[case::hash_key_check(Some("anon_distinct_id"), "should_write_hash_key_override")]
+ #[tokio::test(start_paused = true)]
+ async fn test_stalled_persons_db_degrades_within_one_deadline(
+ #[case] anon_distinct_id: Option<&str>,
+ #[case] first_stopped_call: &str,
+ ) {
+ let recorder = DebuggingRecorder::new();
+ let snapshotter = recorder.snapshotter();
+ let _guard = metrics::set_default_local_recorder(&recorder);
+
+ let stalled_db = Arc::new(StalledPgClient::default());
+ let router = PostgresRouter::new(
+ stalled_db.clone(),
+ stalled_db.clone(),
+ stalled_db.clone(),
+ stalled_db.clone(),
+ );
+ let deadline = Duration::from_millis(500);
+ let mut matcher = FeatureFlagMatcher::new(
+ "stalled_user".to_string(),
+ None,
+ 1,
+ router,
+ Arc::new(CohortCacheManager::new(stalled_db.clone(), None, None)),
+ Arc::new(GroupTypeCacheManager::new(stalled_db.clone(), None, None)),
+ None,
+ )
+ .with_persons_db_deadline(Some(deadline));
+
+ let rollout_flag = mock!(FeatureFlag, id: 1, key: "rollout_flag".mock_into());
+ let person_flag = mock!(FeatureFlag,
+ id: 2,
+ key: "person_flag".mock_into(),
+ filters: mock!(PropertyFilter,
+ key: "email".mock_into(),
+ value: Some(json!("[email protected]")),
+ prop_type: PropertyType::Person
+ ).mock_into()
+ );
+ let continuity_flag = mock!(FeatureFlag,
+ id: 3,
+ key: "continuity_flag".mock_into(),
+ ensure_experience_continuity: Some(true)
+ );
+ let mut flags = flag_list_with_metadata(vec![rollout_flag, person_flag, continuity_flag]);
+ // Preloaded cohorts keep the cohort definitions lookup off the stalled pool.
+ flags.cohorts = Some(Arc::from(Vec::new()));
+
+ let start = tokio::time::Instant::now();
+ let (response, log) = run_with_canonical_log(
+ FlagsCanonicalLogLine::new(Uuid::new_v4(), "127.0.0.1".to_string()),
+ tokio::time::timeout(
+ Duration::from_secs(60),
+ matcher.evaluate_all_feature_flags(
+ flags,
+ None,
+ None,
+ anon_distinct_id.map(str::to_string),
+ Uuid::new_v4(),
+ None,
+ false,
+ ),
+ ),
+ )
+ .await;
+ let response = response
+ .expect("a stalled persons DB must not stall flag evaluation")
+ .unwrap();
+ let elapsed = start.elapsed();
+
+ assert!(response.errors_while_computing_flags);
+ assert_eq!(
+ response.flags["rollout_flag"].to_value(),
+ FlagValue::Boolean(true)
+ );
+ assert_eq!(
+ response.flags["person_flag"].reason.code,
+ "timeout:persons_db_deadline"
+ );
+ assert_eq!(
+ response.flags["continuity_flag"].reason.code,
+ "hash_key_override_error"
+ );
+ assert!(
+ elapsed < deadline * 2,
+ "the hash key lookup and the properties fetch share one deadline, took {elapsed:?}"
+ );
+ assert_eq!(
+ stalled_db.connection_requests.load(Ordering::SeqCst),
+ 1,
+ "a persons call that starts after the deadline must not take a connection"
+ );
+ assert_eq!(log.persons_db_deadline_exceeded, Some(first_stopped_call));
+ for operation in [first_stopped_call, "fetch_properties"] {
+ assert_eq!(
+ counter_total(
+ &snapshotter,
+ FLAG_DATABASE_ERROR_COUNTER,
+ &[
+ ("timeout_type", "persons_db_deadline"),
+ ("operation", operation)
+ ],
+ ),
+ 1,
+ "{operation} stop counted once"
+ );
+ }
+ }
+
#[tokio::test]
async fn test_hash_key_override_error_marks_continuity_flags_as_errors() {
let context = TestContext::new(None).await;
diff --git a/rust/feature-flags/src/handler/canonical_log.rs b/rust/feature-flags/src/handler/canonical_log.rs
index 4ae3a4da0439..b2e59d95272f 100644
--- a/rust/feature-flags/src/handler/canonical_log.rs
+++ b/rust/feature-flags/src/handler/canonical_log.rs
@@ -252,6 +252,9 @@ pub struct FlagsCanonicalLogLine {
/// - "empty": query succeeded, no overrides found
/// - "found": query succeeded, overrides returned
pub hash_key_override_status: Option<&'static str>,
+ /// The first persons DB call that the persons DB deadline stopped, such as
+ /// "fetch_properties". The flags that needed persons data returned an error.
+ pub persons_db_deadline_exceeded: Option<&'static str>,
/// Which evaluation strategy was used for this request.
/// Set to `Parallel` if any dependency level triggered parallel evaluation.
@@ -353,6 +356,7 @@ impl Default for FlagsCanonicalLogLine {
flags_errored: 0,
dependency_graph_errors: 0,
hash_key_override_status: None,
+ persons_db_deadline_exceeded: None,
evaluation_type: None,
rate_limited: false,
rate_limit_warned: false,
@@ -428,6 +432,7 @@ impl FlagsCanonicalLogLine {
flags_errored = self.flags_errored,
dependency_graph_errors = self.dependency_graph_errors,
hash_key_override_status = self.hash_key_override_status,
+ persons_db_deadline_exceeded = self.persons_db_deadline_exceeded,
evaluation_type = self.evaluation_type.map(|t| t.as_str()),
rate_limited = self.rate_limited,
rate_limit_warned = self.rate_limit_warned,
diff --git a/rust/feature-flags/src/handler/evaluation.rs b/rust/feature-flags/src/handler/evaluation.rs
index c8218a2d320b..04906658e8cb 100644
--- a/rust/feature-flags/src/handler/evaluation.rs
+++ b/rust/feature-flags/src/handler/evaluation.rs
@@ -38,7 +38,8 @@ pub async fn evaluate_feature_flags(
.with_membership_stamp_policy(context.membership_stamp_policy)
.with_detailed_analysis(context.detailed_analysis)
.with_only_use_override_person_properties(context.only_use_override_person_properties)
- .with_timezone(context.team_timezone);
+ .with_timezone(context.team_timezone)
+ .with_persons_db_deadline(context.persons_db_deadline);
matcher
.evaluate_all_feature_flags(
diff --git a/rust/feature-flags/src/handler/flags.rs b/rust/feature-flags/src/handler/flags.rs
index 34b594cd9bf1..993cb3e3907b 100644
--- a/rust/feature-flags/src/handler/flags.rs
+++ b/rust/feature-flags/src/handler/flags.rs
@@ -397,6 +397,7 @@ pub async fn evaluate_for_request(
membership_stamp_policy: state.config.realtime_cohort_membership_stamp_policy,
detailed_analysis: detailed_analysis.unwrap_or(false),
only_use_override_person_properties: only_use_override_person_properties.unwrap_or(false),
+ persons_db_deadline: state.config.persons_db_deadline(),
};
evaluation::evaluate_feature_flags(ctx, request_id).await
diff --git a/rust/feature-flags/src/handler/tests.rs b/rust/feature-flags/src/handler/tests.rs
index 0625336ec944..21b903e277e1 100644
--- a/rust/feature-flags/src/handler/tests.rs
+++ b/rust/feature-flags/src/handler/tests.rs
@@ -333,6 +333,7 @@ async fn test_evaluate_feature_flags() {
membership_stamp_policy: MembershipStampPolicy::default(),
detailed_analysis: false,
only_use_override_person_properties: false,
+ persons_db_deadline: None,
};
let request_id = Uuid::new_v4();
@@ -420,6 +421,7 @@ async fn test_evaluate_feature_flags_with_errors() {
membership_stamp_policy: MembershipStampPolicy::default(),
detailed_analysis: false,
only_use_override_person_properties: false,
+ persons_db_deadline: None,
};
let request_id = Uuid::new_v4();
@@ -815,6 +817,7 @@ async fn test_evaluate_feature_flags_multiple_flags() {
membership_stamp_policy: MembershipStampPolicy::default(),
detailed_analysis: false,
only_use_override_person_properties: false,
+ persons_db_deadline: None,
};
let request_id = Uuid::new_v4();
@@ -900,6 +903,7 @@ async fn test_evaluate_feature_flags_details() {
membership_stamp_policy: MembershipStampPolicy::default(),
detailed_analysis: false,
only_use_override_person_properties: false,
+ persons_db_deadline: None,
};
let request_id = Uuid::new_v4();
@@ -1060,6 +1064,7 @@ async fn test_evaluate_feature_flags_with_overrides() {
membership_stamp_policy: MembershipStampPolicy::default(),
detailed_analysis: false,
only_use_override_person_properties: false,
+ persons_db_deadline: None,
};
let request_id = Uuid::new_v4();
@@ -1144,6 +1149,7 @@ async fn test_long_distinct_id() {
membership_stamp_policy: MembershipStampPolicy::default(),
detailed_analysis: false,
only_use_override_person_properties: false,
+ persons_db_deadline: None,
};
let request_id = Uuid::new_v4();
@@ -1753,6 +1759,7 @@ async fn test_parallel_path_matches_sequential_results() {
membership_stamp_policy: MembershipStampPolicy::default(),
detailed_analysis: false,
only_use_override_person_properties: false,
+ persons_db_deadline: None,
};
let sequential_result = evaluate_feature_flags(sequential_context, Uuid::new_v4())
.await
@@ -1786,6 +1793,7 @@ async fn test_parallel_path_matches_sequential_results() {
membership_stamp_policy: MembershipStampPolicy::default(),
detailed_analysis: false,
only_use_override_person_properties: false,
+ persons_db_deadline: None,
};
let parallel_result = evaluate_feature_flags(parallel_context, Uuid::new_v4())
.await
@@ -1880,6 +1888,7 @@ async fn test_realtime_cohort_evaluation_setting_behavior() {
membership_stamp_policy: MembershipStampPolicy::default(),
detailed_analysis: false,
only_use_override_person_properties: false,
+ persons_db_deadline: None,
};
// Test with realtime cohort evaluation ENABLED
@@ -1919,6 +1928,7 @@ async fn test_realtime_cohort_evaluation_setting_behavior() {
membership_stamp_policy: MembershipStampPolicy::default(),
detailed_analysis: false,
only_use_override_person_properties: false,
+ persons_db_deadline: None,
};
let request_id = Uuid::new_v4();
diff --git a/rust/feature-flags/src/handler/types.rs b/rust/feature-flags/src/handler/types.rs
index 6d827ee45b0c..1af10d30feba 100644
--- a/rust/feature-flags/src/handler/types.rs
+++ b/rust/feature-flags/src/handler/types.rs
@@ -103,6 +103,8 @@ pub struct FeatureFlagEvaluationContext {
pub detailed_analysis: bool,
/// Whether to only use person properties from request payload, ignoring database properties.
pub only_use_override_person_properties: bool,
+ /// Budget shared by all persons DB work in this evaluation. `None` disables the deadline.
+ pub persons_db_deadline: Option<std::time::Duration>,
}
/// SDK type classification based on user-agent parsing.
diff --git a/rust/feature-flags/src/utils/deadline.rs b/rust/feature-flags/src/utils/deadline.rs
new file mode 100644
index 000000000000..8c5bc6e8d37a
--- /dev/null
+++ b/rust/feature-flags/src/utils/deadline.rs
@@ -0,0 +1,24 @@
+use std::future::Future;
+
+use tokio::time::Instant;
+
+pub async fn before_deadline<T, E>(
+ deadline: Option<Instant>,
+ call: impl Future<Output = Result<T, E>>,
+ expired: impl FnOnce() -> E,
+) -> Result<T, E> {
+ let Some(deadline) = deadline else {
+ return call.await;
+ };
+ // `timeout_at` polls `call` once before it checks the timer. Without this check, an
+ // expired deadline still starts the call. A database call then takes a connection and
+ // drops it mid-query. When a caller drops a connection mid-query, sqlx pings the
+ // connection before it returns the connection to the pool. On a frozen database, that
+ // ping never completes.
+ if Instant::now() >= deadline {
+ return Err(expired());
+ }
+ tokio::time::timeout_at(deadline, call)
+ .await
+ .unwrap_or_else(|_| Err(expired()))
+}
diff --git a/rust/feature-flags/src/utils/mod.rs b/rust/feature-flags/src/utils/mod.rs
index 08528274295e..9988dd992e1f 100644
--- a/rust/feature-flags/src/utils/mod.rs
+++ b/rust/feature-flags/src/utils/mod.rs
@@ -1,4 +1,5 @@
pub mod bot_detection;
+pub mod deadline;
pub mod graph_utils;
pub mod json_size;
#[cfg(test)]
diff --git a/rust/feature-flags/src/utils/test_utils.rs b/rust/feature-flags/src/utils/test_utils.rs
index f5176fddc3d0..437f63c2b7cb 100644
--- a/rust/feature-flags/src/utils/test_utils.rs
+++ b/rust/feature-flags/src/utils/test_utils.rs
@@ -693,6 +693,24 @@ pub async fn setup_invalid_pg_client() -> Arc<dyn Client + Send + Sync> {
Arc::new(MockPgClient)
}
+/// A database that never answers: every connection request waits forever.
+#[derive(Default)]
+pub struct StalledPgClient {
+ pub connection_requests: AtomicUsize,
+}
+
+#[async_trait]
+impl Client for StalledPgClient {
+ async fn get_connection(&self) -> Result<PoolConnection<Postgres>, CustomDatabaseError> {
+ self.connection_requests.fetch_add(1, Ordering::SeqCst);
+ std::future::pending().await
+ }
+
+ fn get_pool_stats(&self) -> Option<common_database::PoolStats> {
+ None
+ }
+}
+
/// Inserts an organization if it doesn't exist
/// If slug is not provided, generates one from the org_id
async fn insert_organization_if_not_exists(
diff --git a/rust/feature-flags/tests/test_flags.rs b/rust/feature-flags/tests/test_flags.rs
index fe60d096c1ad..d6967f30b539 100644
--- a/rust/feature-flags/tests/test_flags.rs
+++ b/rust/feature-flags/tests/test_flags.rs
@@ -6334,3 +6334,65 @@ async fn test_realtime_cohort_without_backfill_falls_through_to_dynamic_eval() -
Ok(())
}
+
+#[tokio::test]
+async fn it_degrades_person_flags_when_the_persons_db_stops_answering() -> Result<()> {
+ // Accepted connections sit in the listen backlog and never get a reply, like a frozen database.
+ let stalled_persons_db = std::net::TcpListener::bind("127.0.0.1:0")?;
+ let mut config = DEFAULT_TEST_CONFIG.clone();
+ config.persons_read_database_url = format!(
+ "postgres://posthog:posthog@{}/posthog_persons",
+ stalled_persons_db.local_addr()?
+ );
+ // The deadline is shorter than the pool acquire timeout. Only the deadline can then produce
+ // the reason code that the test asserts below.
+ config.persons_db_deadline_ms = 500;
+
+ let client = setup_redis_client(Some(config.redis_url.clone())).await;
+ let team = insert_new_team_in_redis(client.clone()).await.unwrap();
+ let context = TestContext::new(None).await;
+ context.insert_new_team(Some(team.id)).await.unwrap();
+
+ let flag_json = json!([
+ {
+ "id": 1,
+ "key": "rollout-flag",
+ "active": true,
+ "deleted": false,
+ "team_id": team.id,
+ "filters": {"groups": [{"properties": [], "rollout_percentage": 100}]}
+ },
+ {
+ "id": 2,
+ "key": "person-flag",
+ "active": true,
+ "deleted": false,
+ "team_id": team.id,
+ "filters": {"groups": [{
+ "properties": [{"key": "email", "value": "[email protected]", "operator": "exact", "type": "person"}],
+ "rollout_percentage": 100
+ }]}
+ }
+ ]);
+ insert_flags_for_team_in_redis(client, team.id, Some(flag_json.to_string())).await?;
+
+ let server = ServerHandle::for_config(config).await;
+ let payload = json!({"token": team.api_token, "distinct_id": "stalled_user"});
+ let res = server
+ .send_flags_request(payload.to_string(), Some("2"), None)
+ .await;
+
+ assert_eq!(res.status(), StatusCode::OK);
+ assert_json_include!(
+ actual: res.json::<Value>().await?,
+ expected: json!({
+ "errorsWhileComputingFlags": true,
+ "flags": {
+ "rollout-flag": {"enabled": true},
+ "person-flag": {"enabled": false, "reason": {"code": "timeout:persons_db_deadline"}}
+ }
+ })
+ );
+
+ Ok(())
+}