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.

chore(flags): add authoritative-mode cutover gate for billing aggregator (#58170)

Phil Haack350a93a1388e
diff --git a/rust/feature-flags/src/billing/aggregator.rs b/rust/feature-flags/src/billing/aggregator.rs
index 9a8db25123aa..34339b7b1863 100644
--- a/rust/feature-flags/src/billing/aggregator.rs
+++ b/rust/feature-flags/src/billing/aggregator.rs
@@ -5,6 +5,16 @@
//! map, and issues pipelined `HINCRBY`s to Redis. On graceful shutdown a
//! final flush runs before the service exits.
//!
+//! # Mode
+//!
+//! `AggregatorMode::Shadow` writes `…:shadow`-suffixed keys for offline
+//! reconciliation against the per-request synchronous HINCRBY path; both
+//! writes happen on every billable request. `AggregatorMode::Authoritative`
+//! writes the production billing keys directly and the per-request path is
+//! skipped — at this point `flags_billing_pending_records` and
+//! `flags_billing_seconds_since_successful_flush` are billing-critical
+//! signals, not just reconciliation hygiene.
+//!
//! # Durability trade-off
//!
//! Aggregation defers writes until the next flush, so failure modes differ
@@ -74,7 +84,8 @@ use tokio::sync::Notify;
use tokio::task::JoinHandle;
use crate::flags::flag_analytics::{
- current_bucket, get_team_request_library_shadow_key, get_team_request_shadow_key,
+ current_bucket, get_team_request_key, get_team_request_library_key,
+ get_team_request_library_shadow_key, get_team_request_shadow_key,
};
use crate::flags::flag_request::FlagRequestType;
use crate::handler::types::Library;
@@ -136,6 +147,39 @@ pub struct AggregationKey {
pub bucket: u64,
}
+/// Which Redis keyspace the aggregator writes to.
+///
+/// `Shadow` writes `…:shadow`-suffixed keys that run in parallel with the
+/// authoritative per-request HINCRBY in `flag_analytics::increment_request_count`,
+/// so its counts can be reconciled before cutover. `Authoritative` writes the
+/// production billing keys directly — at that point the per-request HINCRBY is
+/// skipped (see `handler::billing::record_billing_increment`).
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum AggregatorMode {
+ Shadow,
+ Authoritative,
+}
+
+impl AggregatorMode {
+ fn team_key(self, team_id: i32, request_type: FlagRequestType) -> String {
+ match self {
+ AggregatorMode::Shadow => get_team_request_shadow_key(team_id, request_type),
+ AggregatorMode::Authoritative => get_team_request_key(team_id, request_type),
+ }
+ }
+
+ fn library_key(self, team_id: i32, request_type: FlagRequestType, library: Library) -> String {
+ match self {
+ AggregatorMode::Shadow => {
+ get_team_request_library_shadow_key(team_id, request_type, library)
+ }
+ AggregatorMode::Authoritative => {
+ get_team_request_library_key(team_id, request_type, library)
+ }
+ }
+ }
+}
+
/// Policy for handling a chunk error during a flush. The flusher's normal
/// tick uses `BailOnError` (if Redis is rejecting, save RTTs and retry next
/// interval). The shutdown path uses `BestEffort` — it's our last chance to
@@ -209,6 +253,7 @@ pub struct BillingAggregator {
struct Inner {
config: BillingAggregatorConfig,
+ mode: AggregatorMode,
redis: Arc<dyn RedisClient + Send + Sync>,
pending: Mutex<HashMap<AggregationKey, u64>>,
/// Running sum of `pending.values()`. Updated under the `pending` lock so
@@ -242,9 +287,11 @@ impl Inner {
fn new(
redis: Arc<dyn RedisClient + Send + Sync>,
config: BillingAggregatorConfig,
+ mode: AggregatorMode,
) -> Arc<Self> {
Arc::new(Self {
config,
+ mode,
redis,
pending: Mutex::new(HashMap::new()),
pending_total: AtomicU64::new(0),
@@ -273,6 +320,7 @@ impl BillingAggregator {
pub fn start(
redis: Arc<dyn RedisClient + Send + Sync>,
config: BillingAggregatorConfig,
+ mode: AggregatorMode,
) -> Arc<Self> {
// Fail fast on misconfiguration. A misconfigured FLAGS_BILLING_*
// env var would otherwise panic the flusher task silently, or silently
@@ -285,7 +333,7 @@ impl BillingAggregator {
let max_pending_entries = config.max_pending_entries;
let per_flush_batch_size = config.per_flush_batch_size;
- let inner = Inner::new(redis, config);
+ let inner = Inner::new(redis, config, mode);
let flusher = tokio::spawn(run_flusher(inner.clone()));
let metrics_sampler = tokio::spawn(run_metrics_sampler(inner.clone()));
@@ -293,6 +341,7 @@ impl BillingAggregator {
flush_interval_ms,
max_pending_entries,
per_flush_batch_size,
+ mode = ?mode,
"BillingAggregator started"
);
@@ -463,13 +512,29 @@ impl BillingAggregator {
pub fn for_tests(
redis: Arc<dyn RedisClient + Send + Sync>,
config: BillingAggregatorConfig,
+ ) -> Arc<Self> {
+ Self::for_tests_with_mode(redis, config, AggregatorMode::Shadow)
+ }
+
+ #[doc(hidden)]
+ pub fn for_tests_with_mode(
+ redis: Arc<dyn RedisClient + Send + Sync>,
+ config: BillingAggregatorConfig,
+ mode: AggregatorMode,
) -> Arc<Self> {
Arc::new(Self {
- inner: Inner::new(redis, config),
+ inner: Inner::new(redis, config, mode),
flusher: Mutex::new(None),
metrics_sampler: Mutex::new(None),
})
}
+
+ /// Read-only accessor used by `record_billing_increment` to decide whether
+ /// to skip the per-request HINCRBY (`Authoritative` mode) or run today's
+ /// dual-write coupling (`Shadow` mode).
+ pub fn mode(&self) -> AggregatorMode {
+ self.inner.mode
+ }
}
/// Spawned task: tick → drain → flush, until the shutdown signal fires.
@@ -665,13 +730,15 @@ async fn flush_once(inner: &Arc<Inner>, policy: FlushPolicy) {
// into the team command without an extra clone.
if let Some(library) = key.library {
buffer.push(PipelineCommand::HIncrBy {
- key: get_team_request_library_shadow_key(key.team_id, key.request_type, library),
+ key: inner
+ .mode
+ .library_key(key.team_id, key.request_type, library),
field: field.clone(),
count: count_i64,
});
}
buffer.push(PipelineCommand::HIncrBy {
- key: get_team_request_shadow_key(key.team_id, key.request_type),
+ key: inner.mode.team_key(key.team_id, key.request_type),
field,
count: count_i64,
});
@@ -990,7 +1057,7 @@ mod tests {
) -> (Arc<MockRedisClient>, Arc<BillingAggregator>) {
let redis = Arc::new(redis);
let agg = Arc::new(BillingAggregator {
- inner: Inner::new(redis.clone(), config),
+ inner: Inner::new(redis.clone(), config, AggregatorMode::Shadow),
flusher: Mutex::new(None),
metrics_sampler: Mutex::new(None),
});
@@ -1223,6 +1290,50 @@ mod tests {
assert!(calls.contains(&(expected_sdk, 1)));
}
+ /// Cutover-mode counterpart to `test_flush_once_writes_flag_definitions_keys`:
+ /// in `Authoritative` mode the aggregator writes the production billing
+ /// keys without the `:shadow` suffix, so the existing
+ /// `calculate_decide_usage` reader picks them up unchanged.
+ #[tokio::test]
+ async fn test_flush_once_authoritative_writes_non_shadow_keys() {
+ let redis = Arc::new(MockRedisClient::new());
+ let agg = BillingAggregator::for_tests_with_mode(
+ redis.clone(),
+ test_config(),
+ AggregatorMode::Authoritative,
+ );
+
+ agg.record(
+ 42,
+ FlagRequestType::FlagDefinitions,
+ Some(Library::PosthogJs),
+ );
+ agg.record(7, FlagRequestType::Decide, None);
+
+ let bucket = current_bucket();
+ flush_once(&agg.inner, FlushPolicy::BailOnError).await;
+
+ let calls = hincrby_calls(&redis);
+ let expected_team_42_def = format!("posthog:local_evaluation_requests:42:{bucket}");
+ let expected_sdk_42_def =
+ format!("posthog:local_evaluation_requests:sdk:42:posthog-js:{bucket}");
+ let expected_team_7_decide = format!("posthog:decide_requests:7:{bucket}");
+ assert_eq!(calls.len(), 3);
+ assert!(calls.contains(&(expected_team_42_def, 1)));
+ assert!(calls.contains(&(expected_sdk_42_def, 1)));
+ assert!(calls.contains(&(expected_team_7_decide, 1)));
+
+ // Belt-and-braces: no key the aggregator writes in authoritative mode
+ // should ever carry the `:shadow` suffix. A regression here would
+ // double-count once the per-request HINCRBY is removed.
+ for (key, _) in &calls {
+ assert!(
+ !key.contains(":shadow"),
+ "authoritative mode wrote a shadow-suffixed key: {key}"
+ );
+ }
+ }
+
#[tokio::test]
async fn test_flush_once_drains_pending() {
let (_, agg) = new_test_aggregator(test_config());
@@ -1307,6 +1418,7 @@ mod tests {
flush_interval: Duration::from_secs(60),
..test_config()
},
+ AggregatorMode::Shadow,
);
agg.record(1, FlagRequestType::Decide, None);
@@ -1333,6 +1445,7 @@ mod tests {
flush_interval: Duration::from_secs(60),
..test_config()
},
+ AggregatorMode::Shadow,
);
agg.record(1, FlagRequestType::Decide, None);
@@ -1360,6 +1473,7 @@ mod tests {
shutdown_flush_timeout: Duration::from_millis(100),
..test_config()
},
+ AggregatorMode::Shadow,
);
agg.record(1, FlagRequestType::Decide, None);
@@ -1699,6 +1813,7 @@ mod tests {
per_flush_batch_size: 2,
..test_config()
},
+ AggregatorMode::Shadow,
);
record_n_decide_with_library(&agg, 5);
@@ -1842,7 +1957,7 @@ mod tests {
shutdown_flush_timeout: Duration::from_millis(50),
..test_config()
};
- let agg = BillingAggregator::start(redis, config);
+ let agg = BillingAggregator::start(redis, config, AggregatorMode::Shadow);
for _ in 0..7 {
agg.record(1, FlagRequestType::Decide, None);
@@ -2172,6 +2287,7 @@ mod tests {
flush_interval: Duration::ZERO,
..test_config()
},
+ AggregatorMode::Shadow,
);
}
}
diff --git a/rust/feature-flags/src/billing/mod.rs b/rust/feature-flags/src/billing/mod.rs
index dd2b7024b0a5..48dd2335daed 100644
--- a/rust/feature-flags/src/billing/mod.rs
+++ b/rust/feature-flags/src/billing/mod.rs
@@ -1,14 +1,19 @@
//! Billing counters for the feature-flags service.
//!
-//! - The authoritative billing write is the synchronous per-request
-//! [`crate::flags::flag_analytics::increment_request_count`].
-//! - [`aggregator`] is a *shadow* writer that targets `…:shadow`-suffixed
-//! keys via [`crate::flags::flag_analytics::get_team_request_shadow_key`],
-//! for reconciliation against the authoritative path.
-//! - [`limiters`] reads the production counters to enforce per-tenant quotas.
+//! - In `AggregatorMode::Shadow`, the authoritative billing write is the
+//! synchronous per-request
+//! [`crate::flags::flag_analytics::increment_request_count`], and
+//! [`aggregator`] tees a parallel write to `…:shadow`-suffixed keys via
+//! [`crate::flags::flag_analytics::get_team_request_shadow_key`] for
+//! offline reconciliation.
+//! - In `AggregatorMode::Authoritative`, [`aggregator`] *is* the
+//! authoritative writer — it writes the production billing keys and the
+//! per-request synchronous HINCRBY is skipped.
+//! - [`limiters`] reads the production counters to enforce per-tenant
+//! quotas; the same keys are read regardless of mode.
pub mod aggregator;
pub mod limiters;
-pub use aggregator::{AggregationKey, BillingAggregator, BillingAggregatorConfig};
+pub use aggregator::{AggregationKey, AggregatorMode, BillingAggregator, BillingAggregatorConfig};
pub use limiters::{FeatureFlagsLimiter, SessionReplayLimiter};
diff --git a/rust/feature-flags/src/config.rs b/rust/feature-flags/src/config.rs
index c7e8d2292393..94369b62eb46 100644
--- a/rust/feature-flags/src/config.rs
+++ b/rust/feature-flags/src/config.rs
@@ -11,6 +11,8 @@ use std::path::{Path, PathBuf};
use std::str::FromStr;
use tracing::Level;
+use crate::billing::AggregatorMode;
+
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FlexBool(pub bool);
@@ -62,6 +64,42 @@ impl FromStr for ServiceMode {
}
}
+/// Tristate selector for the in-process billing aggregator. Encoded as one
+/// enum so `(authoritative=true, enabled=false)` is unrepresentable — the
+/// previous two-boolean form allowed it and `server.rs` had to panic on it.
+/// See `AggregatorMode` for what each non-`Off` variant does at runtime.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum AggregatorModeConfig {
+ Off,
+ Shadow,
+ Authoritative,
+}
+
+impl FromStr for AggregatorModeConfig {
+ type Err = String;
+
+ fn from_str(s: &str) -> Result<Self, Self::Err> {
+ match s.trim().to_lowercase().as_str() {
+ "off" => Ok(AggregatorModeConfig::Off),
+ "shadow" => Ok(AggregatorModeConfig::Shadow),
+ "authoritative" => Ok(AggregatorModeConfig::Authoritative),
+ _ => Err(format!(
+ "Invalid FLAGS_BILLING_AGGREGATOR_MODE: '{s}'. Expected 'off', 'shadow', or 'authoritative'"
+ )),
+ }
+ }
+}
+
+impl AggregatorModeConfig {
+ pub fn into_runtime(self) -> Option<AggregatorMode> {
+ match self {
+ AggregatorModeConfig::Off => None,
+ AggregatorModeConfig::Shadow => Some(AggregatorMode::Shadow),
+ AggregatorModeConfig::Authoritative => Some(AggregatorMode::Authoritative),
+ }
+ }
+}
+
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum TeamIdCollection {
All,
@@ -692,9 +730,13 @@ pub struct Config {
#[envconfig(from = "SERVICE_MODE", default = "all")]
pub service_mode: ServiceMode,
- // Shadow-keyspace writer for reconciliation. Off by default.
- #[envconfig(from = "FLAGS_BILLING_AGGREGATOR_ENABLED", default = "false")]
- pub billing_aggregator_enabled: FlexBool,
+ // Selects the in-process billing aggregator mode. See `AggregatorModeConfig`.
+ // Defaults to `shadow` to match what's deployed in dev/prod-eu/prod-us today,
+ // so swapping the old `FLAGS_BILLING_AGGREGATOR_ENABLED=true` env var for
+ // unsetting it leaves runtime behavior unchanged. `default_test_config` keeps
+ // `Off` so tests that don't opt in don't start the aggregator.
+ #[envconfig(from = "FLAGS_BILLING_AGGREGATOR_MODE", default = "shadow")]
+ pub billing_aggregator_mode: AggregatorModeConfig,
// BillingAggregator tuning knobs. `BillingAggregatorConfig::validate`
// rejects zero values at boot — see the module docs on
@@ -932,7 +974,7 @@ impl Config {
service_mode: ServiceMode::All,
auth_token_cache_ttl_seconds: 300,
internal_request_token: None,
- billing_aggregator_enabled: FlexBool(false),
+ billing_aggregator_mode: AggregatorModeConfig::Off,
billing_flush_interval_ms: 10_000,
billing_max_pending_entries: 500_000,
billing_per_flush_batch_size: 200,
@@ -1037,6 +1079,7 @@ pub static DEFAULT_TEST_CONFIG: Lazy<Config> = Lazy::new(Config::default_test_co
#[cfg(test)]
mod tests {
use super::*;
+ use rstest::rstest;
#[test]
fn test_default_config() {
@@ -1074,6 +1117,7 @@ mod tests {
assert_eq!(config.debug, FlexBool(false));
assert!(!config.flags_session_replay_quota_check);
assert_eq!(config.skip_writes, FlexBool(false));
+ assert_eq!(config.billing_aggregator_mode, AggregatorModeConfig::Shadow);
}
#[test]
@@ -1136,6 +1180,40 @@ mod tests {
);
}
+ #[rstest]
+ #[case::off("off", AggregatorModeConfig::Off)]
+ #[case::shadow("shadow", AggregatorModeConfig::Shadow)]
+ #[case::authoritative("authoritative", AggregatorModeConfig::Authoritative)]
+ #[case::trim_and_lowercase(" SHADOW ", AggregatorModeConfig::Shadow)]
+ fn aggregator_mode_config_parses_valid_values(
+ #[case] input: &str,
+ #[case] expected: AggregatorModeConfig,
+ ) {
+ assert_eq!(input.parse::<AggregatorModeConfig>().unwrap(), expected);
+ }
+
+ #[test]
+ fn aggregator_mode_config_rejects_invalid_value() {
+ let err = "yes".parse::<AggregatorModeConfig>().unwrap_err();
+ assert!(
+ err.contains("Invalid FLAGS_BILLING_AGGREGATOR_MODE"),
+ "unexpected error message: {err}"
+ );
+ }
+
+ #[test]
+ fn aggregator_mode_config_into_runtime_maps_correctly() {
+ assert_eq!(AggregatorModeConfig::Off.into_runtime(), None);
+ assert_eq!(
+ AggregatorModeConfig::Shadow.into_runtime(),
+ Some(AggregatorMode::Shadow)
+ );
+ assert_eq!(
+ AggregatorModeConfig::Authoritative.into_runtime(),
+ Some(AggregatorMode::Authoritative)
+ );
+ }
+
#[test]
fn test_team_ids_to_track_all() {
let team_ids: TeamIdCollection = "all".parse().unwrap();
diff --git a/rust/feature-flags/src/handler/billing.rs b/rust/feature-flags/src/handler/billing.rs
index acd351611fbf..18071212e0ff 100644
--- a/rust/feature-flags/src/handler/billing.rs
+++ b/rust/feature-flags/src/handler/billing.rs
@@ -1,6 +1,6 @@
use crate::{
api::{errors::FlagError, types::FlagsResponse},
- billing::{aggregator::classify_redis_error, BillingAggregator},
+ billing::{aggregator::classify_redis_error, AggregatorMode, BillingAggregator},
flags::{
flag_analytics::{increment_request_count, is_billable_flag_key},
flag_models::FeatureFlagList,
@@ -56,20 +56,31 @@ pub async fn check_limits(
Ok(None)
}
-/// Issues the authoritative synchronous billing HINCRBY plus, when present,
-/// the shadow-keyspace tee via the aggregator.
+/// Records a billable request against the production billing keyspace.
///
/// Caller is responsible for the predicate (skip_writes, billable flags,
/// internal requests, etc.) — by the time this is called the request is
/// known to be billable.
///
-/// The shadow tee only fires when the synchronous write succeeds. Recording
-/// a request the production keyspace did not capture would surface as a
-/// false "aggregator over-counted" signal during reconciliation — masking
-/// any real over-count bug in the aggregator behind whatever Redis-error
-/// noise was happening at the same time. Tying the two writes together
-/// keeps the reconciliation invariant a strict equality: if shadow > prod
-/// and `flag_request_redis_error` is flat, the aggregator is the cause.
+/// Behavior depends on the aggregator's mode:
+///
+/// - **No aggregator, or `AggregatorMode::Shadow`**: the authoritative write
+/// is the synchronous per-request `increment_request_count`. The shadow
+/// tee fires only when the synchronous write succeeds — recording a
+/// request the production keyspace did not capture would surface as a
+/// false "aggregator over-counted" signal during reconciliation, masking
+/// any real over-count bug in the aggregator. Tying the two writes
+/// together keeps the reconciliation invariant a strict equality: if
+/// shadow > prod and `flag_request_redis_error` is flat, the aggregator
+/// is the cause.
+/// - **`AggregatorMode::Authoritative`**: the aggregator *is* the
+/// authoritative writer. We skip `increment_request_count` (no
+/// per-request Redis I/O on this path) and `aggregator.record()` is the
+/// only billing write. The reconciliation invariant from shadow mode no
+/// longer applies — pending records live in process memory until the
+/// next flush, so `flags_billing_pending_records` and
+/// `flags_billing_seconds_since_successful_flush` become
+/// billing-critical signals.
pub async fn record_billing_increment(
redis: Arc<dyn RedisClient + Send + Sync>,
aggregator: Option<&Arc<BillingAggregator>>,
@@ -77,6 +88,18 @@ pub async fn record_billing_increment(
request_type: FlagRequestType,
library: Library,
) {
+ if let Some(aggregator) = aggregator {
+ if aggregator.mode() == AggregatorMode::Authoritative {
+ // billing_duration_ms measures in-process record latency (not Redis
+ // RTT) for dashboard continuity across cutover.
+ let start = Instant::now();
+ aggregator.record(team_id, request_type, Some(library));
+ let elapsed_ms = start.elapsed().as_millis() as u64;
+ with_canonical_log(|log| log.billing_duration_ms = Some(elapsed_ms));
+ return;
+ }
+ }
+
let start = Instant::now();
let result = increment_request_count(redis, team_id, 1, request_type, Some(library)).await;
let elapsed_ms = start.elapsed().as_millis() as u64;
@@ -154,6 +177,7 @@ fn contains_billable_flags(filtered_flags: &FeatureFlagList) -> bool {
#[cfg(test)]
mod tests {
use super::*;
+ use crate::billing::BillingAggregatorConfig;
use crate::flags::feature_flag_list::PreparedFlags;
use crate::flags::flag_analytics::{
PRODUCT_TOUR_TARGETING_FLAG_PREFIX, SURVEY_TARGETING_FLAG_PREFIX,
@@ -161,9 +185,52 @@ mod tests {
use crate::flags::flag_models::FeatureFlag;
use crate::mock;
use crate::utils::mock::MockInto;
+ use common_redis::MockRedisClient;
+ use rstest::rstest;
use std::collections::HashSet;
+ /// Pins the cutover branch in `record_billing_increment`: in `Authoritative`
+ /// mode the per-request HINCRBY is skipped (aggregator is the only writer);
+ /// in `Shadow` mode the per-request HINCRBY runs and the aggregator tees the
+ /// record on success.
+ #[rstest]
+ #[case::authoritative(AggregatorMode::Authoritative, false)]
+ #[case::shadow(AggregatorMode::Shadow, true)]
+ #[tokio::test]
+ async fn record_billing_increment_routes_by_mode(
+ #[case] mode: AggregatorMode,
+ #[case] expect_per_request_redis_call: bool,
+ ) {
+ let per_request_redis = Arc::new(MockRedisClient::new());
+ let aggregator_redis = Arc::new(MockRedisClient::new());
+ let aggregator = BillingAggregator::for_tests_with_mode(
+ aggregator_redis,
+ BillingAggregatorConfig::default(),
+ mode,
+ );
+
+ record_billing_increment(
+ per_request_redis.clone(),
+ Some(&aggregator),
+ 42,
+ FlagRequestType::Decide,
+ Library::PosthogJs,
+ )
+ .await;
+
+ assert_eq!(
+ !per_request_redis.get_calls().is_empty(),
+ expect_per_request_redis_call,
+ "per-request Redis call expectation mismatch for mode {mode:?}"
+ );
+ assert_eq!(
+ aggregator.pending_total(),
+ 1,
+ "aggregator must hold the recorded count regardless of mode"
+ );
+ }
+
#[test]
fn test_contains_billable_flags_only_survey_flags() {
let flag_list: FeatureFlagList = vec![
diff --git a/rust/feature-flags/src/server.rs b/rust/feature-flags/src/server.rs
index 2ac130107005..e8b1d471d9dd 100644
--- a/rust/feature-flags/src/server.rs
+++ b/rust/feature-flags/src/server.rs
@@ -500,21 +500,21 @@ pub async fn serve(
tokio_monitor.start_monitoring(tokio_monitor_handle).await;
});
- let billing_aggregator: Option<Arc<BillingAggregator>> = if *config.billing_aggregator_enabled {
- Some(BillingAggregator::start(
- redis_client.clone(),
- BillingAggregatorConfig {
- flush_interval: Duration::from_millis(config.billing_flush_interval_ms),
- max_pending_entries: config.billing_max_pending_entries,
- per_flush_batch_size: config.billing_per_flush_batch_size,
- shutdown_flush_timeout: Duration::from_millis(
- config.billing_shutdown_flush_timeout_ms,
- ),
- },
- ))
- } else {
- None
- };
+ let billing_aggregator: Option<Arc<BillingAggregator>> =
+ config.billing_aggregator_mode.into_runtime().map(|mode| {
+ BillingAggregator::start(
+ redis_client.clone(),
+ BillingAggregatorConfig {
+ flush_interval: Duration::from_millis(config.billing_flush_interval_ms),
+ max_pending_entries: config.billing_max_pending_entries,
+ per_flush_batch_size: config.billing_per_flush_batch_size,
+ shutdown_flush_timeout: Duration::from_millis(
+ config.billing_shutdown_flush_timeout_ms,
+ ),
+ },
+ mode,
+ )
+ });
let app = router::router(
redis_client,
diff --git a/rust/feature-flags/tests/common/mod.rs b/rust/feature-flags/tests/common/mod.rs
index 81ed55579999..2754728aac8d 100644
--- a/rust/feature-flags/tests/common/mod.rs
+++ b/rust/feature-flags/tests/common/mod.rs
@@ -377,15 +377,15 @@ impl ServerHandle {
// (`handler::billing::record_billing_increment`) so mock-Redis
// coverage doesn't silently regress that codepath. End-to-end
// flush behavior lives in the real-Redis tests in `test_flags.rs`
- // (`test_dual_write_*`, `test_shutdown_flush_*`).
- let billing_aggregator = if *config.billing_aggregator_enabled {
- Some(feature_flags::billing::BillingAggregator::for_tests(
+ // (`test_billing_increments_land_in_production_keyspace_per_mode`,
+ // `test_shutdown_flush_lands_aggregator_target_keyspace_in_redis`).
+ let billing_aggregator = config.billing_aggregator_mode.into_runtime().map(|mode| {
+ feature_flags::billing::BillingAggregator::for_tests_with_mode(
redis_writer_client.clone(),
feature_flags::billing::BillingAggregatorConfig::default(),
- ))
- } else {
- None
- };
+ mode,
+ )
+ });
let app = feature_flags::router::router(
redis_writer_client.clone(), // Use writer client for both reads and writes in tests
diff --git a/rust/feature-flags/tests/test_flags.rs b/rust/feature-flags/tests/test_flags.rs
index 6fc7a9cd47e0..0f621e9b5be3 100644
--- a/rust/feature-flags/tests/test_flags.rs
+++ b/rust/feature-flags/tests/test_flags.rs
@@ -13,7 +13,7 @@ use serde_json::{json, Value};
use crate::common::*;
use feature_flags::cohorts::cohort_models::CohortType;
-use feature_flags::config::DEFAULT_TEST_CONFIG;
+use feature_flags::config::{AggregatorModeConfig, DEFAULT_TEST_CONFIG};
use feature_flags::utils::test_utils::{
insert_config_in_hypercache, insert_flags_for_team_in_redis,
insert_flags_with_metadata_for_team_in_redis, insert_new_team_in_redis, setup_pg_reader_client,
@@ -5699,13 +5699,28 @@ async fn test_skip_writes_suppresses_billing_redis_counter(
Ok(())
}
-/// Verifies that an SDK request lands counts in BOTH the team-level and the
-/// library-level Redis hashes via the synchronous billing path, AND — when
-/// the aggregator is enabled — that the same counts also reach the shadow
-/// keyspace via the aggregator's flush path. This is the cross-path
-/// reconciliation invariant that the dual-write design depends on.
+/// Verifies that an SDK request lands counts at the team-level and the
+/// library-level Redis hashes in the production keyspace — the load-bearing
+/// invariant readers (`calculate_decide_usage`) consume.
+///
+/// In `Shadow` mode the production keys are written by the synchronous
+/// `record_usage` path and the aggregator tees the same counts to the
+/// `:shadow` keyspace for offline reconciliation. In `Authoritative` mode
+/// the synchronous path is skipped — the aggregator's flush *is* the
+/// production write, and the shadow keyspace must stay silent (any write
+/// there is a double-count).
+///
+/// Pinning both modes here means the cutover from shadow to authoritative
+/// is observable as a swap of *who* writes the production keys, with the
+/// same end state from the reader's perspective.
+#[rstest]
+#[case::shadow(AggregatorModeConfig::Shadow, Some("1"))]
+#[case::authoritative(AggregatorModeConfig::Authoritative, None)]
#[tokio::test]
-async fn test_dual_write_lands_counts_in_production_and_shadow_keys() -> Result<()> {
+async fn test_billing_increments_land_in_production_keyspace_per_mode(
+ #[case] mode: AggregatorModeConfig,
+ #[case] expected_shadow: Option<&str>,
+) -> Result<()> {
use feature_flags::config::FlexBool;
use feature_flags::flags::flag_analytics::{
current_bucket, get_team_request_key, get_team_request_library_key,
@@ -5716,10 +5731,10 @@ async fn test_dual_write_lands_counts_in_production_and_shadow_keys() -> Result<
let mut config = DEFAULT_TEST_CONFIG.clone();
config.skip_writes = FlexBool(false);
- // Enable the shadow path so we can assert both keyspaces in one go.
- config.billing_aggregator_enabled = FlexBool(true);
- // Tight flush interval so the aggregator lands its shadow write before
- // the assertion polling window expires.
+ config.billing_aggregator_mode = mode;
+ // Tight flush interval so the aggregator lands its write within the
+ // polling window. In authoritative mode the production key has no
+ // synchronous fallback, so this interval bounds the test latency.
config.billing_flush_interval_ms = 100;
let distinct_id = format!("billing_lib_test_{}", rand::thread_rng().gen::<u32>());
@@ -5784,58 +5799,95 @@ async fn test_dual_write_lands_counts_in_production_and_shadow_keys() -> Result<
.await?;
assert_eq!(StatusCode::OK, res.status());
- // Production keyspace — written synchronously by `record_usage`.
- let team_counter = client.hget(team_key, bucket_field.clone()).await.unwrap();
+ // Production keyspace — the load-bearing invariant. In shadow mode
+ // it's written synchronously; in authoritative it lands via the next
+ // aggregator flush. Polling absorbs both timings.
+ let team_counter = poll_for_billing_counter(&client, &team_key, &bucket_field).await;
assert_eq!(team_counter, "1", "team key should reflect one request");
- let library_counter = client
- .hget(library_key, bucket_field.clone())
- .await
- .unwrap();
+ let library_counter = poll_for_billing_counter(&client, &library_key, &bucket_field).await;
assert_eq!(
library_counter, "1",
"library key should reflect one request"
);
- // Shadow keyspace — written by the aggregator's background flush. Poll
- // because we don't know exactly when the flusher tick lands.
- let team_shadow_counter =
- poll_for_billing_counter(&client, &team_shadow_key, &bucket_field).await;
- assert_eq!(
- team_shadow_counter, "1",
- "shadow team key should reflect one request from the aggregator"
- );
+ // Shadow keyspace — populated only in shadow mode. In authoritative
+ // mode the same write must NOT appear here, or we've double-counted
+ // the request once the per-request HINCRBY is removed.
+ match expected_shadow {
+ Some(expected) => {
+ let team_shadow_counter =
+ poll_for_billing_counter(&client, &team_shadow_key, &bucket_field).await;
+ assert_eq!(
+ team_shadow_counter, expected,
+ "shadow team key should reflect the aggregator's tee"
+ );
- let library_shadow_counter =
- poll_for_billing_counter(&client, &library_shadow_key, &bucket_field).await;
- assert_eq!(
- library_shadow_counter, "1",
- "shadow library key should reflect one request from the aggregator"
- );
+ let library_shadow_counter =
+ poll_for_billing_counter(&client, &library_shadow_key, &bucket_field).await;
+ assert_eq!(
+ library_shadow_counter, expected,
+ "shadow library key should reflect the aggregator's tee"
+ );
+ }
+ None => {
+ // The production write has already landed (we polled for it
+ // above). Wait one more flush window so any erroneous shadow
+ // write would have landed too, then assert it didn't.
+ tokio::time::sleep(std::time::Duration::from_millis(200)).await;
+ let team_shadow = client
+ .hget(team_shadow_key.clone(), bucket_field.clone())
+ .await;
+ assert!(
+ team_shadow.is_err(),
+ "authoritative mode must not write the shadow team key, got {team_shadow:?}"
+ );
+ let library_shadow = client
+ .hget(library_shadow_key.clone(), bucket_field.clone())
+ .await;
+ assert!(
+ library_shadow.is_err(),
+ "authoritative mode must not write the shadow library key, got {library_shadow:?}"
+ );
+ }
+ }
Ok(())
}
-/// End-to-end shutdown-flush path *for the shadow aggregator*. Sets a flush
-/// interval much longer than the test's runtime so the periodic flusher
-/// cannot fire — the only way the **shadow** counter can land in Redis is via
+/// End-to-end shutdown-flush path. Sets a flush interval much longer than
+/// the test's runtime so the periodic flusher cannot fire — the only way
+/// the aggregator's target counter can land in Redis is via
/// `BillingAggregator::shutdown()` after axum's graceful drain. Catches a
/// regression that drops the `billing_aggregator.shutdown().await` call in
/// `serve()`, swaps in `for_tests()`, or wires up the lifecycle ordering
-/// wrong (flushing before axum drains). The synchronous production-keyspace
-/// write is unaffected by the aggregator's lifecycle and is verified by
-/// `test_skip_writes_suppresses_billing_redis_counter`.
+/// wrong (flushing before axum drains).
+///
+/// The aggregator's target keyspace differs by mode:
+///
+/// - **Shadow**: target = `:shadow` keys. The synchronous production-
+/// keyspace write is unaffected by the aggregator's lifecycle and is
+/// verified by `test_skip_writes_suppresses_billing_redis_counter`.
+/// - **Authoritative**: target = production keys. The synchronous path is
+/// gone, so the shutdown flush is the *only* path the production key
+/// has — making this case strictly stronger than the shadow one.
+#[rstest]
+#[case::shadow(AggregatorModeConfig::Shadow)]
+#[case::authoritative(AggregatorModeConfig::Authoritative)]
#[tokio::test]
-async fn test_shutdown_flush_lands_shadow_counter_in_redis() -> Result<()> {
+async fn test_shutdown_flush_lands_aggregator_target_keyspace_in_redis(
+ #[case] mode: AggregatorModeConfig,
+) -> Result<()> {
use feature_flags::config::FlexBool;
- use feature_flags::flags::flag_analytics::{current_bucket, get_team_request_shadow_key};
+ use feature_flags::flags::flag_analytics::{
+ current_bucket, get_team_request_key, get_team_request_shadow_key,
+ };
use feature_flags::flags::flag_request::FlagRequestType;
let mut config = DEFAULT_TEST_CONFIG.clone();
config.skip_writes = FlexBool(false);
- // The aggregator must be on for this test to mean anything — the gate is
- // off by default, so explicitly enable it.
- config.billing_aggregator_enabled = FlexBool(true);
+ // The aggregator must be on for this test to mean anything.
+ config.billing_aggregator_mode = mode;
// Long enough that no periodic flush can fire during the test. If the
// counter shows up in Redis, the shutdown path is what put it there.
config.billing_flush_interval_ms = 60_000;
@@ -5866,7 +5918,18 @@ async fn test_shutdown_flush_lands_shadow_counter_in_redis() -> Result<()> {
}]);
insert_flags_for_team_in_redis(client.clone(), team.id, Some(flag_json.to_string())).await?;
- let billing_key = get_team_request_shadow_key(team.id, FlagRequestType::Decide);
+ // The aggregator's target key is the only one the test asserts
+ // against. In authoritative mode that's the production key; in
+ // shadow mode it's the `:shadow` mirror.
+ let billing_key = match mode {
+ AggregatorModeConfig::Shadow => {
+ get_team_request_shadow_key(team.id, FlagRequestType::Decide)
+ }
+ AggregatorModeConfig::Authoritative => {
+ get_team_request_key(team.id, FlagRequestType::Decide)
+ }
+ AggregatorModeConfig::Off => unreachable!("test cases set the mode explicitly"),
+ };
let bucket_field = current_bucket().to_string();
client.del(billing_key.clone()).await.unwrap();
@@ -5878,23 +5941,23 @@ async fn test_shutdown_flush_lands_shadow_counter_in_redis() -> Result<()> {
.await;
assert_eq!(StatusCode::OK, res.status());
- // Confirm the periodic flusher has NOT yet landed the SHADOW write —
- // sanity check that we're really exercising the shutdown path. With a
- // 60s flush interval and immediate-after-request lookup, the shadow
- // counter should still be missing. (The synchronous production-keyspace
- // write *has* already happened by now, but that's a different key.)
+ // Confirm the periodic flusher has NOT yet landed the aggregator's
+ // write — sanity check that we're really exercising the shutdown
+ // path. With a 60s flush interval and immediate-after-request
+ // lookup, the target counter should still be missing.
let pre_shutdown = client.hget(billing_key.clone(), bucket_field.clone()).await;
assert!(
pre_shutdown.is_err(),
- "shadow billing counter should NOT be in Redis before shutdown — \
- the aggregator's periodic flusher is set to 60s and the test is \
- faster than that. Got {pre_shutdown:?}, which means the flush \
- window collapsed and this test no longer proves what it claims."
+ "billing counter at {billing_key} should NOT be in Redis before \
+ shutdown — the aggregator's periodic flusher is set to 60s and \
+ the test is faster than that. Got {pre_shutdown:?}, which means \
+ the flush window collapsed and this test no longer proves what \
+ it claims."
);
// Trigger graceful shutdown. axum drains in-flight requests, then
// `serve()` calls `billing_aggregator.shutdown().await` which performs
- // the final flush to the shadow keyspace.
+ // the final flush to the aggregator's target keyspace.
server.shutdown_now();
// Poll for the counter to land. The helper polls for ~1s
@@ -5903,7 +5966,7 @@ async fn test_shutdown_flush_lands_shadow_counter_in_redis() -> Result<()> {
let counter = poll_for_billing_counter(&client, &billing_key, &bucket_field).await;
assert_eq!(
counter, "1",
- "shadow billing counter must reach Redis via the shutdown flush path"
+ "billing counter must reach Redis via the shutdown flush path"
);
Ok(())