:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
chore(flags): make rate-limit replenishment test deterministic (#95520)
Phil Haack65ab79a657b4
diff --git a/rust/feature-flags/src/api/endpoint.rs b/rust/feature-flags/src/api/endpoint.rsindex e38707e066ab..8945c040511d 100644--- a/rust/feature-flags/src/api/endpoint.rs+++ b/rust/feature-flags/src/api/endpoint.rs@@ -23,9 +23,10 @@ use crate::{use axum::extract::{Extension, MatchedPath, Query, State};use axum::http::{HeaderMap, HeaderValue, Method, StatusCode};use axum::response::{IntoResponse, Response};-use axum::{debug_handler, Json};+use axum::Json;use axum_client_ip::InsecureClientIp;use bytes::Bytes;+use governor::clock;use serde_json;use std::collections::HashMap;use std::net::IpAddr;@@ -254,10 +255,10 @@ fn get_versioned_response(/// Feature flag evaluation endpoint./// Only supports a specific shape of data, and rejects any malformed data.-#[debug_handler]#[allow(clippy::too_many_arguments)]-pub async fn flags(+pub async fn flags<C>(state: State<router::State>,+ Extension(rate_limiters): Extension<router::FlagsEndpointRateLimiters<C>>,InsecureClientIp(direct_ip): InsecureClientIp,Query(query_params): Query<FlagsQueryParams>,// Populated by the `record_concurrency_wait` middleware after@@ -273,7 +274,10 @@ pub async fn flags(method: Method,path: MatchedPath,body: Bytes,-) -> Result<Response, FlagError> {+) -> Result<Response, FlagError>+where+ C: clock::Clock + Clone + Send + Sync + 'static,+{let request_id = extract_request_id(&headers);// Extract client IP, checking X-Forwarded-For header first@@ -394,7 +398,7 @@ pub async fn flags(let ip_rl_result = {let _t = common_metrics::timing_guard_high_precision(FLAG_RATE_LIMIT_CHECK_TIME_MS, &[]).label("kind", "ip");- state.ip_rate_limiter.allow_request(&ip_string)+ rate_limiters.ip.allow_request(&ip_string)};match ip_rl_result {RateLimitResult::Blocked => {@@ -502,7 +506,7 @@ pub async fn flags(let _t =common_metrics::timing_guard_high_precision(FLAG_RATE_LIMIT_CHECK_TIME_MS, &[]).label("kind", "token");- state.flags_rate_limiter.allow_request(&rate_limit_key)+ rate_limiters.token.allow_request(&rate_limit_key)};match token_rl_result {RateLimitResult::Blocked => {diff --git a/rust/feature-flags/src/api/flags_rate_limiter.rs b/rust/feature-flags/src/api/flags_rate_limiter.rsindex 1999244682c9..ea36d7cd1bc4 100644--- a/rust/feature-flags/src/api/flags_rate_limiter.rs+++ b/rust/feature-flags/src/api/flags_rate_limiter.rs@@ -291,6 +291,7 @@ wherecustom_limiters: Arc<HashMap<String, GovernorLimiter<C>>>,}+#[cfg(test)]impl FlagsRateLimiter {/// Creates a new FlagsRateLimiter with the specified configuration.///@@ -746,6 +747,7 @@ whereinner: KeyedRateLimiter<C>,}+#[cfg(test)]impl IpRateLimiter {/// Creates a new IpRateLimiter with the specified configuration.///diff --git a/rust/feature-flags/src/router.rs b/rust/feature-flags/src/router.rsindex 60961faef560..6752ad27ebf6 100644--- a/rust/feature-flags/src/router.rs+++ b/rust/feature-flags/src/router.rs@@ -9,7 +9,7 @@ use crate::billing::{BillingAggregator, FeatureFlagsLimiter, SessionReplayLimiteuse crate::database_pools::DatabasePools;use axum::{error_handling::HandleErrorLayer,- extract::DefaultBodyLimit,+ extract::{DefaultBodyLimit, Extension},http::{Method, StatusCode},routing::{any, get, post},Router,@@ -21,6 +21,7 @@ use common_hypercache::HyperCacheReader;use common_metrics::inc;use common_metrics::setup_metrics_routes_for_product_with_overrides;use common_redis::Client as RedisClient;+use governor::clock;use lifecycle::{LivenessHandler, ReadinessHandler};use metrics::gauge;use sqlx::PgPool;@@ -65,6 +66,15 @@ use crate::{utils::bot_detection,};+#[derive(Clone)]+pub struct FlagsEndpointRateLimiters<C = clock::DefaultClock>+where+ C: clock::Clock,+{+ pub(crate) token: FlagsRateLimiter<C>,+ pub(crate) ip: IpRateLimiter<C>,+}+#[derive(Clone)]pub struct State {// Shared Redis for non-critical path (analytics counters, billing limits)@@ -87,8 +97,6 @@ pub struct State {/// mirroring Django's RemoteConfigThrottle. Separate budget from flag definitions.pub(crate) remote_config_limiter: RemoteConfigRateLimiter,pub config: Config,- pub(crate) flags_rate_limiter: FlagsRateLimiter,- pub(crate) ip_rate_limiter: IpRateLimiter,/// Pre-initialized HyperCacheReader for feature flags (flags.json)/// Initialized once at startup to avoid per-request AWS SDK initializationpub flags_hypercache_reader: Arc<HyperCacheReader>,@@ -182,6 +190,62 @@ pub fn router(billing_aggregator: Arc<BillingAggregator>,config: Config,) -> Router {+ router_with_rate_limiter_clock(+ redis_client,+ dedicated_redis_client,+ database_pools,+ cohort_cache,+ group_type_cache,+ geoip,+ readiness,+ liveness,+ feature_flags_billing_limiter,+ session_replay_billing_limiter,+ cookieless_manager,+ flags_hypercache_reader,+ flag_definitions_cache,+ flags_with_cohorts_hypercache_reader,+ team_hypercache_reader,+ config_hypercache_reader,+ rayon_dispatcher,+ team_negative_cache,+ auth_token_cache,+ cohort_membership_provider,+ billing_aggregator,+ config,+ clock::DefaultClock::default(),+ )+}++#[allow(clippy::too_many_arguments)]+pub(crate) fn router_with_rate_limiter_clock<C>(+ redis_client: Arc<dyn RedisClient + Send + Sync>,+ dedicated_redis_client: Option<Arc<dyn RedisClient + Send + Sync>>,+ database_pools: Arc<DatabasePools>,+ cohort_cache: Arc<CohortCacheManager>,+ group_type_cache: Arc<GroupTypeCacheManager>,+ geoip: Arc<GeoIpClient>,+ readiness: ReadinessHandler,+ liveness: LivenessHandler,+ feature_flags_billing_limiter: FeatureFlagsLimiter,+ session_replay_billing_limiter: SessionReplayLimiter,+ cookieless_manager: Arc<CookielessManager>,+ flags_hypercache_reader: Arc<HyperCacheReader>,+ flag_definitions_cache: Arc<FlagDefinitionsCache>,+ flags_with_cohorts_hypercache_reader: Arc<HyperCacheReader>,+ team_hypercache_reader: Arc<HyperCacheReader>,+ config_hypercache_reader: Arc<HyperCacheReader>,+ rayon_dispatcher: RayonDispatcher,+ team_negative_cache: NegativeCache,+ auth_token_cache: Arc<ReadThroughCacheWithMetrics>,+ cohort_membership_provider: Arc<dyn CohortMembershipProvider>,+ billing_aggregator: Arc<BillingAggregator>,+ config: Config,+ rate_limiter_clock: C,+) -> Router+where+ C: clock::Clock + Clone + Send + Sync + 'static,+{// Initialize flag definitions rate limiter with default and custom team rateslet flag_definitions_limiter = FlagDefinitionsRateLimiter::new(config.flag_definitions_default_rate_per_minute,@@ -215,13 +279,14 @@ pub fn router(config.flags_warn_capacity_ratio,*config.flags_rate_limit_log_only,);- let flags_rate_limiter = FlagsRateLimiter::new(+ let flags_rate_limiter = FlagsRateLimiter::new_with_clock(*config.flags_rate_limit_enabled,config.flags_bucket_replenish_rate,flags_warn_cap,flags_enforce_cap,flags_warn_only,config.flags_token_rate_limit_overrides.0.clone(),+ rate_limiter_clock.clone(),).unwrap_or_else(|e| {panic!(@@ -236,12 +301,13 @@ pub fn router(config.flags_warn_capacity_ratio,*config.flags_ip_rate_limit_log_only,);- let ip_rate_limiter = IpRateLimiter::new(+ let ip_rate_limiter = IpRateLimiter::new_with_clock(*config.flags_ip_rate_limit_enabled,config.flags_ip_replenish_rate,ip_warn_cap,ip_enforce_cap,ip_warn_only,+ rate_limiter_clock,).unwrap_or_else(|e| {panic!(@@ -257,6 +323,10 @@ pub fn router(remote_config_limiter.clone(),config.rate_limiter_cleanup_interval_secs,);+ let rate_limiters = FlagsEndpointRateLimiters {+ token: flags_rate_limiter,+ ip: ip_rate_limiter,+ };// Force eager construction of the bot UA matcher and IP-range table so// the first `/flags` request after a pod restart doesn't pay the@@ -304,8 +374,6 @@ pub fn router(flag_definitions_limiter,remote_config_limiter,config: config.clone(),- flags_rate_limiter,- ip_rate_limiter,flags_hypercache_reader,flag_definitions_cache,flags_with_cohorts_hypercache_reader,@@ -369,12 +437,13 @@ pub fn router(let mut flags_endpoints: Router<State> = Router::new();if matches!(config.service_mode, ServiceMode::All | ServiceMode::Flags) {flags_endpoints = flags_endpoints- .route("/flags", any(endpoint::flags))- .route("/flags/", any(endpoint::flags))- .route("/decide", any(endpoint::flags))- .route("/decide/", any(endpoint::flags))+ .route("/flags", any(endpoint::flags::<C>))+ .route("/flags/", any(endpoint::flags::<C>))+ .route("/decide", any(endpoint::flags::<C>))+ .route("/decide/", any(endpoint::flags::<C>)).layer(axum::middleware::from_fn(record_body_read))- .layer(DefaultBodyLimit::max(MAX_FLAGS_BODY_BYTES));+ .layer(DefaultBodyLimit::max(MAX_FLAGS_BODY_BYTES))+ .layer(Extension(rate_limiters));}// Internal-only batch flag evaluation for static cohort generation. Kept outside@@ -526,13 +595,15 @@ fn resolve_rate_limit_capacities(/// Without this, the rate limiters would accumulate entries for every unique/// token/IP that makes a request, leading to unbounded memory growth./// See: https://docs.rs/governor/latest/governor/struct.RateLimiter.html#method.retain_recent-fn spawn_rate_limiter_cleanup_task(- flags_rate_limiter: FlagsRateLimiter,- ip_rate_limiter: IpRateLimiter,+fn spawn_rate_limiter_cleanup_task<C>(+ flags_rate_limiter: FlagsRateLimiter<C>,+ ip_rate_limiter: IpRateLimiter<C>,flag_definitions_limiter: FlagDefinitionsRateLimiter,remote_config_limiter: RemoteConfigRateLimiter,cleanup_interval_secs: u64,-) {+) where+ C: clock::Clock + Clone + Send + Sync + 'static,+{tokio::spawn(async move {let mut interval = tokio::time::interval(Duration::from_secs(cleanup_interval_secs));loop {diff --git a/rust/feature-flags/src/server.rs b/rust/feature-flags/src/server.rsindex 075ac5b39f8f..f894ce6d53e0 100644--- a/rust/feature-flags/src/server.rs+++ b/rust/feature-flags/src/server.rs@@ -23,6 +23,7 @@ use common_hypercache::{HyperCacheConfig, HyperCacheReader, S3Client};use common_redis::{Client, CompressionConfig, ReadWriteClient, ReadWriteClientConfig, RedisClient,};+use governor::clock;use lifecycle::{ComponentOptions, Handle, LivenessHandler, Manager, ReadinessHandler};use limiters::redis::QUOTA_LIMITER_CACHE_KEY;use tokio::net::TcpListener;@@ -113,6 +114,27 @@ pub async fn serve(// a real object store. Uses the `new_with_s3_client` testing seam on HyperCacheReader.flags_with_cohorts_s3: Option<Arc<dyn S3Client + Send + Sync>>,) {+ serve_with_rate_limiter_clock(+ config,+ listener,+ rayon_dispatcher,+ handles,+ flags_with_cohorts_s3,+ clock::DefaultClock::default(),+ )+ .await;+}++pub async fn serve_with_rate_limiter_clock<C>(+ config: Config,+ listener: TcpListener,+ rayon_dispatcher: RayonDispatcher,+ handles: LifecycleHandles,+ flags_with_cohorts_s3: Option<Arc<dyn S3Client + Send + Sync>>,+ rate_limiter_clock: C,+) where+ C: clock::Clock + Clone + Send + Sync + 'static,+{// Configure compression based on environment variablelet compression_config = if *config.redis_compression_enabled {let config = CompressionConfig::default();@@ -560,7 +582,7 @@ pub async fn serve(usage_reporter,);- let app = router::router(+ let app = router::router_with_rate_limiter_clock(redis_client,dedicated_redis_client,database_pools,@@ -583,6 +605,7 @@ pub async fn serve(cohort_membership_provider,billing_aggregator.clone(),config,+ rate_limiter_clock,);tracing::info!(diff --git a/rust/feature-flags/tests/common/mod.rs b/rust/feature-flags/tests/common/mod.rsindex 619fb545553f..3be33d78f1f1 100644--- a/rust/feature-flags/tests/common/mod.rs+++ b/rust/feature-flags/tests/common/mod.rs@@ -8,6 +8,7 @@ use common_hypercache::{HyperCacheConfig, HyperCacheReader};use common_redis::MockRedisClient;use feature_flags::team::team_models::Team;use feature_flags::utils::test_utils::team_token_hypercache_key;+use governor::clock;use lifecycle::Manager;use limiters::redis::QUOTA_LIMITER_CACHE_KEY;use reqwest::header::CONTENT_TYPE;@@ -17,7 +18,7 @@ use tokio_util::sync::CancellationToken;use feature_flags::cohorts::membership::NoOpCohortMembershipProvider;use feature_flags::config::Config;use feature_flags::rayon_dispatcher::RayonDispatcher;-use feature_flags::server::{register_components, serve};+use feature_flags::server::{register_components, serve_with_rate_limiter_clock};pub struct ServerHandle {pub addr: SocketAddr,@@ -55,6 +56,33 @@ impl ServerHandle {config: Config,flags_with_cohorts_s3: Option<Arc<dyn common_hypercache::S3Client + Send + Sync>>,) -> ServerHandle {+ Self::for_config_with_s3_and_rate_limiter_clock(+ config,+ flags_with_cohorts_s3,+ clock::DefaultClock::default(),+ )+ .await+ }++ #[allow(dead_code)]+ pub async fn for_config_with_rate_limiter_clock<C>(+ config: Config,+ rate_limiter_clock: C,+ ) -> ServerHandle+ where+ C: clock::Clock + Clone + Send + Sync + 'static,+ {+ Self::for_config_with_s3_and_rate_limiter_clock(config, None, rate_limiter_clock).await+ }++ async fn for_config_with_s3_and_rate_limiter_clock<C>(+ config: Config,+ flags_with_cohorts_s3: Option<Arc<dyn common_hypercache::S3Client + Send + Sync>>,+ rate_limiter_clock: C,+ ) -> ServerHandle+ where+ C: clock::Clock + Clone + Send + Sync + 'static,+ {let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();let addr = listener.local_addr().unwrap();let shutdown = CancellationToken::new();@@ -64,12 +92,13 @@ impl ServerHandle {let rayon_dispatcher = RayonDispatcher::new(2, None);tokio::spawn(async move {- serve(+ serve_with_rate_limiter_clock(config,listener,rayon_dispatcher,handles,flags_with_cohorts_s3,+ rate_limiter_clock,).await;// Drain the lifecycle monitor after serve returns so the supervisordiff --git a/rust/feature-flags/tests/test_rate_limiting.rs b/rust/feature-flags/tests/test_rate_limiting.rsindex bb61a1b2e725..794f931d7d6e 100644--- a/rust/feature-flags/tests/test_rate_limiting.rs+++ b/rust/feature-flags/tests/test_rate_limiting.rs@@ -1,7 +1,9 @@use anyhow::Result;+use governor::clock::FakeRelativeClock;use reqwest::StatusCode;use serde_json::json;use std::collections::HashMap;+use std::time::Duration;use crate::common::*;use feature_flags::config::{Config, FlexBool};@@ -372,7 +374,8 @@ async fn test_rate_limit_replenishment() -> Result<()> {});insert_config_in_hypercache(redis_client.clone(), &token, remote_config).await?;- let server = ServerHandle::for_config(config).await;+ let clock = FakeRelativeClock::default();+ let server = ServerHandle::for_config_with_rate_limiter_clock(config, clock.clone()).await;let client = reqwest::Client::new();let payload = json!({@@ -380,38 +383,29 @@ async fn test_rate_limit_replenishment() -> Result<()> {"distinct_id": "user123",});- // Capacity is one token and a denial does not extend the window. Only a grant moves the- // window forward by one second, so the whole burst is served without a block only if it- // spans BURST - 1 seconds. The check tolerates a total burst latency below BURST - 1- // seconds, which no run of six localhost round trips reaches on a loaded runner.- const BURST: usize = 6;- let mut statuses = Vec::with_capacity(BURST);- for _ in 0..BURST {- let response = client- .post(format!("http://{}/flags", server.addr))- .header("content-type", "application/json")- .json(&payload)- .send()- .await?;- statuses.push(response.status());- }+ let response = client+ .post(format!("http://{}/flags", server.addr))+ .header("content-type", "application/json")+ .json(&payload)+ .send()+ .await?;- // Only allow and block are valid here, so a 5xx means the endpoint broke rather than- // rate limited. Fail on it instead of letting a server error hide behind the burst.- assert!(- statuses- .iter()- .all(|s| *s == StatusCode::OK || *s == StatusCode::TOO_MANY_REQUESTS),- "Burst returned an unexpected status: {statuses:?}"- );- assert_eq!(statuses[0], StatusCode::OK, "First request allowed");- assert!(- statuses.contains(&StatusCode::TOO_MANY_REQUESTS),- "Burst blocked once the bucket is empty: {statuses:?}"+ assert_eq!(response.status(), StatusCode::OK, "First request allowed");++ let response = client+ .post(format!("http://{}/flags", server.addr))+ .header("content-type", "application/json")+ .json(&payload)+ .send()+ .await?;++ assert_eq!(+ response.status(),+ StatusCode::TOO_MANY_REQUESTS,+ "Second request blocked");- // 1100ms clears the one-second window the last grant opened. A slow burst only adds margin.- tokio::time::sleep(tokio::time::Duration::from_millis(1100)).await;+ clock.advance(Duration::from_secs(1));let response = client.post(format!("http://{}/flags", server.addr))@@ -423,7 +417,7 @@ async fn test_rate_limit_replenishment() -> Result<()> {assert_eq!(response.status(),StatusCode::OK,- "Request allowed after replenishment"+ "Third request allowed after replenishment");Ok(())