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.

feat(flags): add realtime cohort metrics and lookup timeout (#69410)

Gustavo H. Strassburger3e6dde51d8c1
diff --git a/docs/internal/feature-flags/database-interaction-patterns.md b/docs/internal/feature-flags/database-interaction-patterns.md
index d58acee8bdcb..1d57a4f2a57a 100644
--- a/docs/internal/feature-flags/database-interaction-patterns.md
+++ b/docs/internal/feature-flags/database-interaction-patterns.md
@@ -28,7 +28,7 @@ The service uses a four-pool architecture (with an optional fifth pool for behav
When the persons database is not configured separately, the persons pools alias to the non-persons pools, effectively creating a two-pool architecture.
-When `BEHAVIORAL_COHORTS_READ_DATABASE_URL` is configured, a separate reader pool is created for realtime cohort membership lookups. This pool has tight limits (max 5 connections, 1s statement timeout) to avoid impacting flag evaluation latency. When not configured, realtime cohort evaluation is disabled with no impact on existing flag evaluation.
+When `BEHAVIORAL_COHORTS_READ_DATABASE_URL` is configured, a separate reader pool is created for realtime cohort membership lookups. This pool has tight limits (max 5 connections, 1s statement timeout, and a configurable `REALTIME_COHORT_LOOKUP_TIMEOUT_MS` bound covering pool acquire + query, default 1s to match the statement timeout) to avoid impacting flag evaluation latency. When not configured, no pool is created and a NoOp provider resolves every realtime cohort lookup to non-membership, with no impact on existing flag evaluation.
## Connection pooling
@@ -284,25 +284,33 @@ 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` | Retry counter |
-| `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`) |
+| 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` | Retry counter |
+| `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) |
### Example PromQL queries
diff --git a/docs/internal/feature-flags/rust-service-overview.md b/docs/internal/feature-flags/rust-service-overview.md
index 2d7a36beca58..1cc725972f43 100644
--- a/docs/internal/feature-flags/rust-service-overview.md
+++ b/docs/internal/feature-flags/rust-service-overview.md
@@ -239,13 +239,19 @@ All values come from environment variables via the `envconfig` crate. Defined in
### Behavioral cohorts
-| Variable | Default | Purpose |
-| -------------------------------------- | -------- | ------------------------------------------------------------------------------------------------------------------------- |
-| `BEHAVIORAL_COHORTS_READ_DATABASE_URL` | (empty) | Optional PostgreSQL connection for realtime cohort membership lookups. When empty, realtime cohort evaluation is disabled |
-| `COHORT_MEMBERSHIP_CACHE_TTL_SECONDS` | `60` | Cache TTL for cohort membership lookups |
-| `COHORT_MEMBERSHIP_CACHE_MAX_ENTRIES` | `500000` | Max entries in cohort membership cache |
-
-The behavioral cohorts pool uses tight limits (max 5 connections, 1s statement timeout) since it only performs simple key lookups against the `cohort_membership` table. When `BEHAVIORAL_COHORTS_READ_DATABASE_URL` is not set, a `NoOpCohortMembershipProvider` is used and all realtime cohort checks return `false` (graceful degradation).
+| Variable | Default | Purpose |
+| -------------------------------------- | -------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| `BEHAVIORAL_COHORTS_READ_DATABASE_URL` | (empty) | Optional PostgreSQL connection for realtime cohort membership lookups. When empty, no pool is created and a NoOp provider resolves every realtime cohort lookup to non-membership |
+| `REALTIME_COHORT_EVALUATION_TEAM_IDS` | `none` | Rollout gate for realtime cohort evaluation: `none`, `all`, or specific team IDs / ranges (e.g. `1,5,300:400`) |
+| `COHORT_MEMBERSHIP_CACHE_TTL_SECONDS` | `60` | Cache TTL for cohort membership lookups |
+| `COHORT_MEMBERSHIP_CACHE_MAX_ENTRIES` | `500000` | Max entries in cohort membership cache |
+| `REALTIME_COHORT_LOOKUP_TIMEOUT_MS` | `1000` | Upper bound on one membership lookup (pool acquire + query), matching the pool's 1s statement timeout; on timeout the lookup degrades to non-membership |
+
+The behavioral cohorts pool uses tight limits (max 5 connections, 1s statement timeout) since it only performs simple key lookups against the `cohort_membership` table.
+Realtime cohort evaluation degrades gracefully at every layer, always treating people as non-members rather than failing flag evaluation:
+when `BEHAVIORAL_COHORTS_READ_DATABASE_URL` is not set a `NoOpCohortMembershipProvider` returns `false` for all checks (with a startup warning if `REALTIME_COHORT_EVALUATION_TEAM_IDS` is set at the same time),
+and when the database is unavailable at runtime, query errors and lookups exceeding `REALTIME_COHORT_LOOKUP_TIMEOUT_MS` also resolve to non-membership.
+Cache and query health are observable via the `flags_cohort_membership_cache_*` and `flags_realtime_cohort_*` metrics — see [database-interaction-patterns.md](database-interaction-patterns.md#prometheus-metrics).
### Redis
diff --git a/rust/feature-flags/src/cohorts/membership/cached_provider.rs b/rust/feature-flags/src/cohorts/membership/cached_provider.rs
index c6f2139f1109..71b14ba47c92 100644
--- a/rust/feature-flags/src/cohorts/membership/cached_provider.rs
+++ b/rust/feature-flags/src/cohorts/membership/cached_provider.rs
@@ -6,6 +6,10 @@ use std::time::Duration;
use uuid::Uuid;
use crate::cohorts::cohort_models::CohortId;
+use crate::metrics::consts::{
+ COHORT_MEMBERSHIP_CACHE_ENTRIES_GAUGE, COHORT_MEMBERSHIP_CACHE_HIT_COUNTER,
+ COHORT_MEMBERSHIP_CACHE_MISS_COUNTER,
+};
use common_types::TeamId;
use super::provider::{CohortMembershipError, CohortMembershipProvider};
@@ -41,6 +45,14 @@ impl<P: CohortMembershipProvider> CachedCohortMembershipProvider<P> {
cache,
}
}
+
+ fn report_entries_gauge(&self) {
+ common_metrics::gauge(
+ COHORT_MEMBERSHIP_CACHE_ENTRIES_GAUGE,
+ &[],
+ self.cache.entry_count() as f64,
+ );
+ }
}
#[async_trait]
@@ -67,12 +79,17 @@ impl<P: CohortMembershipProvider> CohortMembershipProvider for CachedCohortMembe
.collect();
if uncached_ids.is_empty() {
+ common_metrics::inc(COHORT_MEMBERSHIP_CACHE_HIT_COUNTER, &[], 1);
+ // Also refresh the gauge on hits: entry_count shrinks on TTL expiry
+ // and eviction, which insert-only reporting would never surface.
+ self.report_entries_gauge();
return Ok(cohort_ids
.iter()
.map(|id| (*id, cached.get(id).copied().unwrap_or(false)))
.collect());
}
+ common_metrics::inc(COHORT_MEMBERSHIP_CACHE_MISS_COUNTER, &[], 1);
let fresh = self
.inner
.check_memberships(team_id, person_uuid, &uncached_ids)
@@ -81,6 +98,7 @@ impl<P: CohortMembershipProvider> CohortMembershipProvider for CachedCohortMembe
let mut merged = cached;
merged.extend(fresh);
self.cache.insert(cache_key, merged.clone()).await;
+ self.report_entries_gauge();
return Ok(cohort_ids
.iter()
@@ -88,12 +106,14 @@ impl<P: CohortMembershipProvider> CohortMembershipProvider for CachedCohortMembe
.collect());
}
+ common_metrics::inc(COHORT_MEMBERSHIP_CACHE_MISS_COUNTER, &[], 1);
let result = self
.inner
.check_memberships(team_id, person_uuid, cohort_ids)
.await?;
self.cache.insert(cache_key, result.clone()).await;
+ self.report_entries_gauge();
Ok(result)
}
diff --git a/rust/feature-flags/src/cohorts/membership/realtime_provider.rs b/rust/feature-flags/src/cohorts/membership/realtime_provider.rs
index ab38418aeac8..ac9b8659bfd9 100644
--- a/rust/feature-flags/src/cohorts/membership/realtime_provider.rs
+++ b/rust/feature-flags/src/cohorts/membership/realtime_provider.rs
@@ -2,9 +2,14 @@ use async_trait::async_trait;
use sqlx::PgPool;
use std::collections::HashMap;
use std::sync::Arc;
+use std::time::Duration;
use uuid::Uuid;
use crate::cohorts::cohort_models::CohortId;
+use crate::metrics::consts::{
+ DB_COHORT_MEMBERSHIP_ERRORS_COUNTER, DB_COHORT_MEMBERSHIP_READS_COUNTER,
+ FLAG_REALTIME_COHORT_DB_QUERY_TIME,
+};
use common_types::TeamId;
use super::provider::{CohortMembershipError, CohortMembershipProvider};
@@ -16,11 +21,29 @@ use super::provider::{CohortMembershipError, CohortMembershipProvider};
#[derive(Clone)]
pub struct RealtimeCohortMembershipProvider {
pool: Arc<PgPool>,
+ lookup_timeout: Duration,
}
impl RealtimeCohortMembershipProvider {
+ /// Upper bound on one membership lookup, covering pool acquire + query. Matches the
+ /// behavioral cohorts pool's 1s statement timeout: a tighter bound would discard
+ /// answers the DB would still deliver, degrading the person to non-member and
+ /// flipping any flag targeting them. Its job is to cover what statement_timeout
+ /// cannot — pool acquire stalls (2s acquire timeout by default) and network black
+ /// holes — so an unreachable DB costs at most 1s of the 4.5s flags request budget.
+ /// On timeout the lookup fails like any query error and the caller degrades to
+ /// non-membership.
+ const DEFAULT_LOOKUP_TIMEOUT: Duration = Duration::from_millis(1000);
+
pub fn new(pool: Arc<PgPool>) -> Self {
- Self { pool }
+ Self::with_lookup_timeout(pool, Self::DEFAULT_LOOKUP_TIMEOUT)
+ }
+
+ pub fn with_lookup_timeout(pool: Arc<PgPool>, lookup_timeout: Duration) -> Self {
+ Self {
+ pool,
+ lookup_timeout,
+ }
}
}
@@ -41,7 +64,9 @@ impl CohortMembershipProvider for RealtimeCohortMembershipProvider {
// IDs stay below ~2.1 billion; if that ceiling is ever reached, CohortId
// should be widened to i64 across the codebase.
let cohort_ids_i64: Vec<i64> = cohort_ids.iter().map(|&id| i64::from(id)).collect();
- let rows: Vec<CohortMembershipRow> = sqlx::query_as(
+ let query_timer =
+ common_metrics::timing_guard_high_precision(FLAG_REALTIME_COHORT_DB_QUERY_TIME, &[]);
+ let query_future = sqlx::query_as::<_, CohortMembershipRow>(
r#"
SELECT cohort_id
FROM cohort_membership
@@ -54,9 +79,28 @@ impl CohortMembershipProvider for RealtimeCohortMembershipProvider {
.bind(i64::from(team_id))
.bind(person_uuid)
.bind(&cohort_ids_i64)
- .fetch_all(self.pool.as_ref())
- .await
- .map_err(|e| CohortMembershipError::QueryFailed(e.to_string()))?;
+ .fetch_all(self.pool.as_ref());
+
+ let rows = match tokio::time::timeout(self.lookup_timeout, query_future).await {
+ Ok(Ok(rows)) => {
+ common_metrics::inc(DB_COHORT_MEMBERSHIP_READS_COUNTER, &[], 1);
+ query_timer.label("outcome", "success").fin();
+ rows
+ }
+ Ok(Err(e)) => {
+ common_metrics::inc(DB_COHORT_MEMBERSHIP_ERRORS_COUNTER, &[], 1);
+ query_timer.label("outcome", "error").fin();
+ return Err(CohortMembershipError::QueryFailed(e.to_string()));
+ }
+ Err(_elapsed) => {
+ common_metrics::inc(DB_COHORT_MEMBERSHIP_ERRORS_COUNTER, &[], 1);
+ query_timer.label("outcome", "timeout").fin();
+ return Err(CohortMembershipError::QueryFailed(format!(
+ "membership lookup timed out after {:?}",
+ self.lookup_timeout
+ )));
+ }
+ };
let matched_set: std::collections::HashSet<CohortId> = rows
.iter()
@@ -96,6 +140,48 @@ impl CohortMembershipProvider for NoOpCohortMembershipProvider {
#[cfg(test)]
mod tests {
use super::*;
+ use crate::utils::test_utils::TestContext;
+
+ /// Exercises the real SQL against the behavioral cohorts DB: schema drift on
+ /// `cohort_membership`, a broken `in_cohort` predicate, or lost team scoping
+ /// would surface only here — no other test runs this query.
+ #[tokio::test]
+ async fn test_realtime_provider_queries_cohort_membership_table() {
+ let context = TestContext::new(None).await;
+ let Some(pool) = context.behavioral_cohorts_pool.clone() else {
+ eprintln!("behavioral cohorts DB not available, skipping");
+ return;
+ };
+
+ let team_id = 1;
+ let person = Uuid::new_v4();
+ context
+ .insert_cohort_membership(team_id, 101, person, true)
+ .await
+ .unwrap();
+ context
+ .insert_cohort_membership(team_id, 102, person, false)
+ .await
+ .unwrap();
+ context
+ .insert_cohort_membership(team_id + 1, 103, person, true)
+ .await
+ .unwrap();
+
+ let provider = RealtimeCohortMembershipProvider::new(pool);
+ let result = provider
+ .check_memberships(team_id, person, &[101, 102, 103, 104])
+ .await
+ .unwrap();
+
+ assert!(result[&101], "in_cohort=true row should be a member");
+ assert!(!result[&102], "in_cohort=false row should not be a member");
+ assert!(
+ !result[&103],
+ "membership under another team must not leak across teams"
+ );
+ assert!(!result[&104], "cohort with no row should not be a member");
+ }
#[tokio::test]
async fn test_noop_provider_returns_false_for_all() {
diff --git a/rust/feature-flags/src/config.rs b/rust/feature-flags/src/config.rs
index 1af5c42bf1b0..24b88c569810 100644
--- a/rust/feature-flags/src/config.rs
+++ b/rust/feature-flags/src/config.rs
@@ -404,6 +404,16 @@ pub struct Config {
#[envconfig(from = "COHORT_MEMBERSHIP_CACHE_MAX_ENTRIES", default = "500000")]
pub cohort_membership_cache_max_entries: u64,
+ // 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.
+ // 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
+ // stalls, network black holes).
+ #[envconfig(from = "REALTIME_COHORT_LOOKUP_TIMEOUT_MS", default = "1000")]
+ pub realtime_cohort_lookup_timeout_ms: u64,
+
#[envconfig(default = "1000")]
pub max_concurrency: usize,
@@ -1038,6 +1048,7 @@ impl Config {
realtime_cohort_evaluation_team_ids: TeamIdCollection::None,
cohort_membership_cache_ttl_seconds: 60,
cohort_membership_cache_max_entries: 50_000,
+ realtime_cohort_lookup_timeout_ms: 1000,
max_concurrency: 1000,
max_pg_connections: 10,
min_non_persons_reader_connections: 0,
diff --git a/rust/feature-flags/src/flags/flag_matching.rs b/rust/feature-flags/src/flags/flag_matching.rs
index 488e7e4a4d9c..dbf1a46e056c 100644
--- a/rust/feature-flags/src/flags/flag_matching.rs
+++ b/rust/feature-flags/src/flags/flag_matching.rs
@@ -38,7 +38,7 @@ use crate::rayon_dispatcher::RayonDispatcher;
use crate::utils::graph_utils::PrecomputedDependencyGraph;
use anyhow::Result;
use chrono_tz::Tz;
-use common_metrics::{histogram, inc, timing_guard};
+use common_metrics::{histogram, inc, timing_guard, timing_guard_high_precision};
use common_types::collections::HashMapExt;
use common_types::{PersonId, TeamId};
use rayon::prelude::*;
@@ -2119,7 +2119,10 @@ impl FeatureFlagMatcher {
self.flag_evaluation_state.get_person_uuid()
{
let query_labels = [("team_id".to_string(), self.team_id.to_string())];
- let realtime_timer = timing_guard(FLAG_REALTIME_COHORT_QUERY_TIME, &query_labels);
+ // High precision: cache hits complete in microseconds, and plain
+ // timing_guard truncates to integer ms, collapsing them all to 0.
+ let realtime_timer =
+ timing_guard_high_precision(FLAG_REALTIME_COHORT_QUERY_TIME, &query_labels);
let realtime_start = std::time::Instant::now();
let result = self
diff --git a/rust/feature-flags/src/flags/test_flag_matching.rs b/rust/feature-flags/src/flags/test_flag_matching.rs
index c91ec747b684..47ca724ce3da 100644
--- a/rust/feature-flags/src/flags/test_flag_matching.rs
+++ b/rust/feature-flags/src/flags/test_flag_matching.rs
@@ -1,14 +1,21 @@
#[cfg(test)]
mod tests {
+ use async_trait::async_trait;
+ use chrono::Utc;
use common_types::TeamId;
use serde_json::json;
use std::collections::{HashMap, HashSet};
+ use std::sync::atomic::{AtomicU32, Ordering};
use std::sync::Arc;
use uuid::Uuid;
use crate::{
api::types::{FlagValue, LegacyFlagsResponse},
- cohorts::cohort_cache_manager::CohortCacheManager,
+ cohorts::{
+ cohort_cache_manager::CohortCacheManager,
+ cohort_models::{CohortId, CohortType},
+ membership::{CohortMembershipError, CohortMembershipProvider},
+ },
flags::{
feature_flag_list::PreparedFlags,
flag_group_type_mapping::GroupTypeCacheManager,
@@ -3449,6 +3456,304 @@ mod tests {
);
}
+ /// Membership provider that returns a fixed membership map and counts calls,
+ /// standing in for the behavioral cohorts DB in realtime cohort tests.
+ struct FixedMembershipProvider {
+ memberships: HashMap<CohortId, bool>,
+ calls: AtomicU32,
+ }
+
+ impl FixedMembershipProvider {
+ fn new(memberships: HashMap<CohortId, bool>) -> Self {
+ Self {
+ memberships,
+ calls: AtomicU32::new(0),
+ }
+ }
+ }
+
+ #[async_trait]
+ impl CohortMembershipProvider for FixedMembershipProvider {
+ async fn check_memberships(
+ &self,
+ _team_id: TeamId,
+ _person_uuid: Uuid,
+ cohort_ids: &[CohortId],
+ ) -> Result<HashMap<CohortId, bool>, CohortMembershipError> {
+ self.calls.fetch_add(1, Ordering::SeqCst);
+ Ok(cohort_ids
+ .iter()
+ .map(|id| (*id, self.memberships.get(id).copied().unwrap_or(false)))
+ .collect())
+ }
+ }
+
+ /// Membership provider that always fails, simulating an unavailable
+ /// behavioral cohorts database.
+ struct FailingMembershipProvider;
+
+ #[async_trait]
+ impl CohortMembershipProvider for FailingMembershipProvider {
+ async fn check_memberships(
+ &self,
+ _team_id: TeamId,
+ _person_uuid: Uuid,
+ _cohort_ids: &[CohortId],
+ ) -> Result<HashMap<CohortId, bool>, CohortMembershipError> {
+ Err(CohortMembershipError::QueryFailed(
+ "behavioral cohorts DB unavailable".to_string(),
+ ))
+ }
+ }
+
+ /// Cohort filters requiring person property plan == `plan`, used so tests can
+ /// tell provider-driven results apart from dynamic filter evaluation.
+ fn plan_cohort_filters(plan: &str) -> serde_json::Value {
+ json!({
+ "properties": {
+ "type": "OR",
+ "values": [{
+ "type": "AND",
+ "values": [{
+ "key": "plan",
+ "type": "person",
+ "value": [plan],
+ "operator": "exact",
+ "negation": false
+ }]
+ }]
+ }
+ })
+ }
+
+ fn flag_targeting_cohort(team_id: TeamId, cohort_id: CohortId) -> FeatureFlag {
+ mock!(FeatureFlag,
+ team_id: team_id,
+ filters: FlagFilters {
+ groups: vec![FlagPropertyGroup {
+ properties: Some(vec![PropertyFilter {
+ key: "id".to_string(),
+ value: Some(json!(cohort_id)),
+ operator: Some(OperatorType::In),
+ prop_type: PropertyType::Cohort,
+ group_type_index: None,
+ negation: Some(false),
+ compiled_regex: None,
+ extra: Default::default(),
+ }]),
+ rollout_percentage: Some(100.0),
+ variant: None,
+ ..Default::default()
+ }],
+ multivariate: None,
+ aggregation_group_type_index: None,
+ payloads: None,
+
+ feature_enrollment: None,
+
+ holdout: None,
+ early_exit: None,
+ extra: Default::default(),
+ }
+ )
+ }
+
+ #[tokio::test]
+ async fn test_realtime_cohort_membership_from_provider_matches_flag() {
+ let context = TestContext::new(None).await;
+ let cohort_cache = Arc::new(CohortCacheManager::new(
+ context.non_persons_reader.clone(),
+ None,
+ None,
+ ));
+ let team = context.insert_new_team(None).await.unwrap();
+
+ // Realtime cohort with a backfill timestamp, so membership comes from the
+ // provider. Its filters require plan=enterprise, which the person does NOT
+ // satisfy — a match can only come from the provider.
+ let cohort = context
+ .insert_cohort_with_type(
+ team.id,
+ Some("Realtime Cohort".to_string()),
+ plan_cohort_filters("enterprise"),
+ false,
+ Some(CohortType::Realtime),
+ Some(Utc::now()),
+ None,
+ )
+ .await
+ .unwrap();
+
+ let distinct_id = "realtime_member_user".to_string();
+ context
+ .insert_person(team.id, distinct_id.clone(), Some(json!({"plan": "free"})))
+ .await
+ .unwrap();
+
+ let flag = flag_targeting_cohort(team.id, cohort.id);
+
+ let provider = Arc::new(FixedMembershipProvider::new(HashMap::from([(
+ cohort.id, true,
+ )])));
+ let mut matcher = FeatureFlagMatcher::new(
+ distinct_id.clone(),
+ None,
+ team.id,
+ context.create_postgres_router(),
+ cohort_cache,
+ empty_group_type_cache(),
+ None,
+ )
+ .with_cohort_membership_provider(provider.clone())
+ .with_realtime_cohort_evaluation(true);
+
+ matcher
+ .prepare_flag_evaluation_state(&[&flag])
+ .await
+ .unwrap();
+
+ let result = matcher.get_match(&flag, None, None, None, &None).unwrap();
+
+ assert!(
+ result.matches,
+ "Provider-reported membership should match the flag even though dynamic filter evaluation would not"
+ );
+ assert_eq!(provider.calls.load(Ordering::SeqCst), 1);
+ }
+
+ #[tokio::test]
+ async fn test_realtime_cohort_provider_error_degrades_to_non_member() {
+ let context = TestContext::new(None).await;
+ let cohort_cache = Arc::new(CohortCacheManager::new(
+ context.non_persons_reader.clone(),
+ None,
+ None,
+ ));
+ let team = context.insert_new_team(None).await.unwrap();
+
+ // The person DOES satisfy the cohort's filters (plan=enterprise), so if a
+ // provider failure wrongly fell through to dynamic evaluation the flag
+ // would match. Graceful degradation must treat the person as a non-member.
+ let cohort = context
+ .insert_cohort_with_type(
+ team.id,
+ Some("Realtime Cohort Degraded".to_string()),
+ plan_cohort_filters("enterprise"),
+ false,
+ Some(CohortType::Realtime),
+ Some(Utc::now()),
+ None,
+ )
+ .await
+ .unwrap();
+
+ let distinct_id = "realtime_degraded_user".to_string();
+ context
+ .insert_person(
+ team.id,
+ distinct_id.clone(),
+ Some(json!({"plan": "enterprise"})),
+ )
+ .await
+ .unwrap();
+
+ let flag = flag_targeting_cohort(team.id, cohort.id);
+
+ let mut matcher = FeatureFlagMatcher::new(
+ distinct_id.clone(),
+ None,
+ team.id,
+ context.create_postgres_router(),
+ cohort_cache,
+ empty_group_type_cache(),
+ None,
+ )
+ .with_cohort_membership_provider(Arc::new(FailingMembershipProvider))
+ .with_realtime_cohort_evaluation(true);
+
+ matcher
+ .prepare_flag_evaluation_state(&[&flag])
+ .await
+ .expect("provider failure must not fail flag evaluation");
+
+ let result = matcher.get_match(&flag, None, None, None, &None).unwrap();
+
+ assert!(
+ !result.matches,
+ "On provider failure the person must be treated as a non-member, not re-evaluated dynamically"
+ );
+ }
+
+ #[tokio::test]
+ async fn test_realtime_cohort_gate_off_skips_provider_and_falls_back_to_dynamic() {
+ let context = TestContext::new(None).await;
+ let cohort_cache = Arc::new(CohortCacheManager::new(
+ context.non_persons_reader.clone(),
+ None,
+ None,
+ ));
+ let team = context.insert_new_team(None).await.unwrap();
+
+ let cohort = context
+ .insert_cohort_with_type(
+ team.id,
+ Some("Realtime Cohort Gated".to_string()),
+ plan_cohort_filters("enterprise"),
+ false,
+ Some(CohortType::Realtime),
+ Some(Utc::now()),
+ None,
+ )
+ .await
+ .unwrap();
+
+ let distinct_id = "realtime_gated_user".to_string();
+ context
+ .insert_person(
+ team.id,
+ distinct_id.clone(),
+ Some(json!({"plan": "enterprise"})),
+ )
+ .await
+ .unwrap();
+
+ let flag = flag_targeting_cohort(team.id, cohort.id);
+
+ // The provider would report non-membership; with the rollout gate off it
+ // must never be consulted and the cohort evaluates dynamically instead.
+ let provider = Arc::new(FixedMembershipProvider::new(HashMap::from([(
+ cohort.id, false,
+ )])));
+ let mut matcher = FeatureFlagMatcher::new(
+ distinct_id.clone(),
+ None,
+ team.id,
+ context.create_postgres_router(),
+ cohort_cache,
+ empty_group_type_cache(),
+ None,
+ )
+ .with_cohort_membership_provider(provider.clone())
+ .with_realtime_cohort_evaluation(false);
+
+ matcher
+ .prepare_flag_evaluation_state(&[&flag])
+ .await
+ .unwrap();
+
+ let result = matcher.get_match(&flag, None, None, None, &None).unwrap();
+
+ assert!(
+ result.matches,
+ "With the gate off the cohort should fall back to dynamic filter evaluation"
+ );
+ assert_eq!(
+ provider.calls.load(Ordering::SeqCst),
+ 0,
+ "Provider must not be consulted when realtime cohort evaluation is disabled"
+ );
+ }
+
#[tokio::test]
async fn test_evaluate_feature_flags_with_experience_continuity() {
let context = TestContext::new(None).await;
diff --git a/rust/feature-flags/src/metrics/buckets.rs b/rust/feature-flags/src/metrics/buckets.rs
index 04eac71f7850..a8e130cec138 100644
--- a/rust/feature-flags/src/metrics/buckets.rs
+++ b/rust/feature-flags/src/metrics/buckets.rs
@@ -70,6 +70,26 @@ const S3_OP_BUCKETS_MS: &[f64] = &[
1.0, 2.5, 5.0, 10.0, 25.0, 50.0, 100.0, 250.0, 500.0, 1000.0, 2500.0, 5000.0, 10000.0,
];
+// Realtime cohort membership lookups at the evaluation site
+// (`flags_realtime_cohort_query_time`, recorded with
+// `timing_guard_high_precision` — the sub-ms floor is only meaningful because
+// of that; plain `timing_guard` truncates to integer ms and would collapse
+// every Moka cache hit to 0). The rollout SLO is p99 < 20ms, which the
+// default ladder cannot resolve (it jumps 10ms → 50ms), so carry an explicit
+// 20ms boundary. Sub-ms floor separates cache hits from DB round trips;
+// 1s ceiling matches the behavioral cohorts pool's statement timeout.
+const REALTIME_COHORT_LOOKUP_BUCKETS_MS: &[f64] = &[
+ 0.05, 0.1, 0.5, 1.0, 2.5, 5.0, 10.0, 20.0, 50.0, 100.0, 250.0, 500.0, 1000.0,
+];
+
+// Behavioral cohorts DB round trips alone (`flags_realtime_cohort_db_query_time`).
+// Same 20ms SLO boundary and 1s ceiling, but a 0.5ms floor instead of sub-ms:
+// every observation here is a pool acquire + network round trip, so the
+// 0.05/0.1ms buckets would stay permanently empty.
+const REALTIME_COHORT_DB_QUERY_BUCKETS_MS: &[f64] = &[
+ 0.5, 1.0, 2.5, 5.0, 10.0, 20.0, 50.0, 100.0, 250.0, 500.0, 1000.0,
+];
+
/// Returns the bucket-override matrix for the feature-flags recorder.
///
/// `Matcher::Suffix` is used for `_queue_time_ms` / `_pre_handler_time_ms`
@@ -124,5 +144,13 @@ pub fn bucket_overrides() -> Vec<(Matcher, &'static [f64])> {
Matcher::Full("posthog_hypercache_s3_op_ms".into()),
S3_OP_BUCKETS_MS,
),
+ (
+ Matcher::Full("flags_realtime_cohort_query_time".into()),
+ REALTIME_COHORT_LOOKUP_BUCKETS_MS,
+ ),
+ (
+ Matcher::Full("flags_realtime_cohort_db_query_time".into()),
+ REALTIME_COHORT_DB_QUERY_BUCKETS_MS,
+ ),
]
}
diff --git a/rust/feature-flags/src/metrics/consts.rs b/rust/feature-flags/src/metrics/consts.rs
index 6202fb36873e..b5a8666978f2 100644
--- a/rust/feature-flags/src/metrics/consts.rs
+++ b/rust/feature-flags/src/metrics/consts.rs
@@ -20,6 +20,16 @@ pub const COHORT_CACHE_HIT_COUNTER: &str = "flags_cohort_cache_hit_total";
pub const COHORT_CACHE_MISS_COUNTER: &str = "flags_cohort_cache_miss_total";
pub const COHORT_CACHE_SIZE_BYTES_GAUGE: &str = "flags_cohort_cache_size_bytes";
pub const COHORT_CACHE_ENTRIES_GAUGE: &str = "flags_cohort_cache_entries";
+// Realtime cohort membership cache (CachedCohortMembershipProvider, keyed on
+// (team_id, person_uuid)). hit = lookup fully served from cache; miss = a
+// behavioral cohorts DB query was issued (no cache entry, or the entry was
+// missing some of the requested cohort IDs).
+pub const COHORT_MEMBERSHIP_CACHE_HIT_COUNTER: &str = "flags_cohort_membership_cache_hit_total";
+pub const COHORT_MEMBERSHIP_CACHE_MISS_COUNTER: &str = "flags_cohort_membership_cache_miss_total";
+pub const COHORT_MEMBERSHIP_CACHE_ENTRIES_GAUGE: &str = "flags_cohort_membership_cache_entries";
+// Behavioral cohorts DB reads for realtime cohort membership (RealtimeCohortMembershipProvider)
+pub const DB_COHORT_MEMBERSHIP_READS_COUNTER: &str = "flags_db_cohort_membership_reads_total";
+pub const DB_COHORT_MEMBERSHIP_ERRORS_COUNTER: &str = "flags_db_cohort_membership_errors_total";
// In-memory flag definitions cache (deserialized + regex-compiled).
// Keyed on `(team_id, etag)` where `etag` is the version tag Django writes
// alongside the hypercache payload (`enable_etag=True`). Cache hits avoid the
@@ -272,6 +282,11 @@ pub const FLAG_COHORT_PROCESSING_TIME: &str = "flags_cohort_processing_time";
pub const FLAG_REALTIME_COHORT_QUERY_TIME: &str = "flags_realtime_cohort_query_time";
pub const FLAG_REALTIME_COHORT_QUERY_ERROR_COUNTER: &str =
"flags_realtime_cohort_query_error_total";
+// Behavioral cohorts DB query latency alone (inside RealtimeCohortMembershipProvider),
+// as opposed to FLAG_REALTIME_COHORT_QUERY_TIME above which wraps the whole provider
+// call at the evaluation site and so mixes cache hits with DB round trips.
+// Labels: outcome="success" | "error" | "timeout". Recorded with sub-ms precision.
+pub const FLAG_REALTIME_COHORT_DB_QUERY_TIME: &str = "flags_realtime_cohort_db_query_time";
pub const FLAG_GROUP_QUERY_TIME: &str = "flags_group_query_time";
pub const FLAG_GROUP_PROCESSING_TIME: &str = "flags_group_processing_time";
pub const FLAG_DB_CONNECTION_TIME: &str = "flags_db_connection_time";
diff --git a/rust/feature-flags/src/server.rs b/rust/feature-flags/src/server.rs
index 86ae846bf847..d552ef0c6d24 100644
--- a/rust/feature-flags/src/server.rs
+++ b/rust/feature-flags/src/server.rs
@@ -217,13 +217,27 @@ pub async fn serve(
let cohort_membership_provider: Arc<dyn CohortMembershipProvider> =
if config.realtime_cohort_evaluation_team_ids != TeamIdCollection::None {
if let Some(pool) = database_pools.behavioral_cohorts_reader.clone() {
- let realtime = RealtimeCohortMembershipProvider::new(pool);
+ tracing::info!(
+ cache_ttl_seconds = config.cohort_membership_cache_ttl_seconds,
+ cache_max_entries = config.cohort_membership_cache_max_entries,
+ lookup_timeout_ms = config.realtime_cohort_lookup_timeout_ms,
+ "Realtime cohort evaluation enabled with behavioral cohorts DB"
+ );
+ let realtime = RealtimeCohortMembershipProvider::with_lookup_timeout(
+ pool,
+ Duration::from_millis(config.realtime_cohort_lookup_timeout_ms),
+ );
Arc::new(CachedCohortMembershipProvider::new(
realtime,
Some(config.cohort_membership_cache_ttl_seconds),
Some(config.cohort_membership_cache_max_entries),
))
} else {
+ tracing::warn!(
+ "REALTIME_COHORT_EVALUATION_TEAM_IDS is set but \
+ BEHAVIORAL_COHORTS_READ_DATABASE_URL is not configured; realtime \
+ cohort lookups will treat everyone as a non-member"
+ );
Arc::new(NoOpCohortMembershipProvider)
}
} else {