: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
feat(capture): add dry run mode to GlobalRateLimiter wrapper (#59940)
Eli Reisman12c33c889b14
diff --git a/rust/capture/src/config.rs b/rust/capture/src/config.rsindex 7225322a540f..315664514fb1 100644--- a/rust/capture/src/config.rs+++ b/rust/capture/src/config.rs@@ -56,6 +56,11 @@ pub struct Config {#[envconfig(default = "false")]pub global_rate_limit_enabled: bool,+ /// When true, the global rate limiter evaluates and emits metrics/logs+ /// but does not enforce (events pass through as if not limited).+ #[envconfig(default = "false")]+ pub global_rate_limit_dry_run: bool,+/// Sliding window interval to apply global rate limiting threshold to#[envconfig(default = "60")]pub global_rate_limit_window_interval_secs: u64,diff --git a/rust/capture/src/global_rate_limiter.rs b/rust/capture/src/global_rate_limiter.rsindex ed85152e20bb..fdb93f6561f3 100644--- a/rust/capture/src/global_rate_limiter.rs+++ b/rust/capture/src/global_rate_limiter.rs@@ -10,7 +10,8 @@ use limiters::global_rate_limiter::{EvalResult, GlobalRateLimitResponse, GlobalRateLimiter as CommonGlobalRateLimiter,GlobalRateLimiterConfig, GlobalRateLimiterImpl as CommonGlobalRateLimiterImpl,};-use tracing::{error, info};+use metrics::counter;+use tracing::{error, info, warn};#[cfg(test)]use chrono::DateTime;@@ -43,6 +44,7 @@ impl<'a> GlobalRateLimitKey<'a> {pub struct GlobalRateLimiter {limiter: Box<dyn CommonGlobalRateLimiter>,+ dry_run: bool,}impl GlobalRateLimiter {@@ -122,6 +124,8 @@ impl GlobalRateLimiter {..Default::default()};+ let dry_run = config.global_rate_limit_dry_run;+let limiter = match CommonGlobalRateLimiterImpl::new(grl_config, redis_instances) {Ok(l) => l,Err(e) => {@@ -130,19 +134,48 @@ impl GlobalRateLimiter {}};+ if dry_run {+ info!("GlobalRateLimiter initialized in dry-run mode (evaluating but not enforcing)");+ }+Ok(Self {limiter: Box::new(limiter),+ dry_run,})}/// Check if a key is rate limited. Routes to custom or global check based on/// whether the key is registered in the custom_keys map. Exactly one check/// fires per call — no double-enqueue to the Redis batch channel.+ ///+ /// In dry-run mode the underlying limiter is still evaluated (counts are+ /// tracked, Redis is synced) but the result is suppressed: metrics and a+ /// warn log are emitted, then `None` is returned so callers never enforce.pub async fn is_limited(&self, key: &str, count: u64) -> Option<GlobalRateLimitResponse> {- if self.limiter.is_custom_key(key) {+ let result = if self.limiter.is_custom_key(key) {self.is_custom_key_limited(key, count).await} else {self.is_global_key_limited(key, count).await+ };++ match (result, self.dry_run) {+ (Some(response), true) => {+ counter!(+ "capture_global_rate_limiter_dry_run",+ "key_type" => if response.is_custom_limited { "custom" } else { "global" },+ )+ .increment(1);+ warn!(+ key = key,+ current_count = response.current_count,+ threshold = response.threshold,+ is_custom_limited = response.is_custom_limited,+ dry_run = true,+ "global rate limiter would have limited (dry run)"+ );+ None+ }+ (result, _) => result,}}@@ -231,6 +264,15 @@ impl GlobalRateLimiter {pub(crate) fn new_with(limiter: impl CommonGlobalRateLimiter + 'static) -> Self {Self {limiter: Box::new(limiter),+ dry_run: false,+ }+ }++ #[cfg(test)]+ pub(crate) fn new_with_dry_run(limiter: impl CommonGlobalRateLimiter + 'static) -> Self {+ Self {+ limiter: Box::new(limiter),+ dry_run: true,}}@@ -557,4 +599,84 @@ mod tests {let result2 = key2.to_cache_key();assert_eq!(&*result2, &format!("t:{prefix_129}"));}++ // --- dry-run mode tests ---++ #[tokio::test]+ async fn test_dry_run_global_limited_returns_none() {+ let (mock, calls) = MockLimiter::new(+ HashSet::new(),+ make_limited_response(false),+ EvalResult::NotApplicable,+ );+ let wrapper = GlobalRateLimiter::new_with_dry_run(mock);++ let result = wrapper.is_limited("some_key", 1).await;++ assert!(+ result.is_none(),+ "dry-run should suppress Limited → None, got {result:?}"+ );+ assert_eq!(+ *calls.lock().unwrap(),+ vec!["is_custom_key", "check_limit"],+ "underlying limiter must still be called in dry-run mode"+ );+ }++ #[tokio::test]+ async fn test_dry_run_custom_limited_returns_none() {+ let (mock, calls) = MockLimiter::new(+ HashSet::from(["custom_key".to_string()]),+ EvalResult::Allowed,+ make_limited_response(true),+ );+ let wrapper = GlobalRateLimiter::new_with_dry_run(mock);++ let result = wrapper.is_limited("custom_key", 1).await;++ assert!(+ result.is_none(),+ "dry-run should suppress custom Limited → None, got {result:?}"+ );+ assert_eq!(+ *calls.lock().unwrap(),+ vec!["is_custom_key", "check_custom_limit"],+ "underlying limiter must still be called in dry-run mode"+ );+ }++ #[tokio::test]+ async fn test_dry_run_allowed_stays_none() {+ let (mock, _calls) = MockLimiter::new(+ HashSet::new(),+ EvalResult::Allowed,+ EvalResult::NotApplicable,+ );+ let wrapper = GlobalRateLimiter::new_with_dry_run(mock);++ let result = wrapper.is_limited("some_key", 1).await;++ assert!(+ result.is_none(),+ "allowed result should remain None in dry-run mode"+ );+ }++ #[tokio::test]+ async fn test_non_dry_run_limited_still_returns_some() {+ let (mock, _calls) = MockLimiter::new(+ HashSet::new(),+ make_limited_response(false),+ EvalResult::NotApplicable,+ );+ let wrapper = GlobalRateLimiter::new_with(mock);++ let result = wrapper.is_limited("some_key", 1).await;++ assert!(+ result.is_some(),+ "non-dry-run should return Some(response) when limited"+ );+ }}diff --git a/rust/capture/src/v1/quota_limiter_shim.rs b/rust/capture/src/v1/quota_limiter_shim.rsindex 9b7035a1a7b6..b686e2cd8f2a 100644--- a/rust/capture/src/v1/quota_limiter_shim.rs+++ b/rust/capture/src/v1/quota_limiter_shim.rs@@ -116,6 +116,7 @@ mod tests {redis_response_timeout_ms: 100,redis_connection_timeout_ms: 5000,global_rate_limit_enabled: false,+ global_rate_limit_dry_run: false,global_rate_limit_window_interval_secs: 60,global_rate_limit_sync_interval_secs: 15,global_rate_limit_tick_interval_ms: 1000,diff --git a/rust/capture/tests/common/utils.rs b/rust/capture/tests/common/utils.rsindex aa478e3d8684..a336445035d6 100644--- a/rust/capture/tests/common/utils.rs+++ b/rust/capture/tests/common/utils.rs@@ -39,6 +39,7 @@ pub static DEFAULT_CONFIG: Lazy<Config> = Lazy::new(|| Config {redis_response_timeout_ms: 100,redis_connection_timeout_ms: 5000,global_rate_limit_enabled: false,+ global_rate_limit_dry_run: false,global_rate_limit_window_interval_secs: 60,global_rate_limit_sync_interval_secs: 15,global_rate_limit_tick_interval_ms: 1000,