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(capture): faster burst detection for the global rate limiter (#89757)

Eli Reisman2ec554d7d6fb
diff --git a/.agents/skills/monitoring-capture-service/SKILL.md b/.agents/skills/monitoring-capture-service/SKILL.md
index fe4490f9aba5..c049f6844fac 100644
--- a/.agents/skills/monitoring-capture-service/SKILL.md
+++ b/.agents/skills/monitoring-capture-service/SKILL.md
@@ -108,6 +108,7 @@ metrics and CloudWatch ElastiCache metrics.
- Optional read replica: `GLOBAL_RATE_LIMIT_REDIS_READER_URL`
- Toggle: `GLOBAL_RATE_LIMIT_ENABLED` (may be off in some envs during rollout)
- Metrics: `global_rate_limiter_*` (direct), `capture_events_rerouted_overflow{reason="rate_limited"}` (proxy signal)
+- `global_rate_limiter_window_seconds{scope}` publishes each process's window. capture-analytics and capture-ai share the AI byte budget, so if they disagree on this gauge the shared budget has split
- CloudWatch cluster id: `capture-globalratelimit-prod-redis`
**3. Event Restrictions Redis** (`EVENT_RESTRICTIONS_REDIS_URL`)
diff --git a/rust/capture/src/config.rs b/rust/capture/src/config.rs
index 18bf2642f117..01ad1093c3e6 100644
--- a/rust/capture/src/config.rs
+++ b/rust/capture/src/config.rs
@@ -469,6 +469,15 @@ pub struct Config {
#[envconfig(default = "false")]
pub ai_byte_limit_dry_run: bool,
+ /// Window the AI byte budget is enforced over. Falls back to
+ /// `GLOBAL_RATE_LIMIT_WINDOW_INTERVAL_SECS` when unset.
+ ///
+ /// The AI byte budget is shared across capture deployments through one
+ /// Redis counter, and the epoch key derives from this window, so every
+ /// deployment must set the same value or the shared budget splits. Kept
+ /// separate so the token+distinct_id window can be tuned per deployment.
+ pub ai_byte_limit_window_interval_secs: Option<u64>,
+
/// Max local cache entries for the AI byte limiter. Keyed per token, so this
/// is bounded by the number of projects sending AI traffic — far smaller
/// than the per-(token, distinct_id) limiter's key space.
diff --git a/rust/capture/src/events/analytics.rs b/rust/capture/src/events/analytics.rs
index b53754aa1853..4529114c7f1d 100644
--- a/rust/capture/src/events/analytics.rs
+++ b/rust/capture/src/events/analytics.rs
@@ -497,46 +497,34 @@ async fn process_events_inner(
// end state matches, but the pass order differs.
// 2. Lane assignment is a single `DataType::from_event_name` match in
// legacy versus assign-then-reroute in v1.
- // 3. Events whose person processing was already off: v1 skips its stamps
- // entirely (so such an event is never rerouted to overflow) and reports
- // it as outcome="already_disabled". Legacy still stamps and reroutes it,
- // and still counts it in the metric and log below; only the warning
- // excludes it. So legacy's limited count can exceed its warned count,
- // where v1's cannot.
- // Both paths consult the same shared limiter for every non-dropped event, so
- // per-key counts are identical regardless of which pipeline serves the key.
+ // Both paths charge the same shared limiter for every non-dropped event,
+ // including events whose person processing is already off, so per-key counts
+ // are identical regardless of which pipeline serves the key.
// Import is unaffected by both: the GRL never runs (guard below) and no
// overflowable lane is reachable, so behavior is identical across paths.
if context.capture_mode.applies_global_rate_limit() {
if let Some(ref limiter) = global_rate_limiter {
let mut limited_distinct_ids: HashSet<&str> = HashSet::new();
let mut limited_event_count: u64 = 0;
- // Narrower than the tallies above: events an upstream event
- // restriction had already taken person processing away from are
- // excluded. The limiter didn't change their fate, so telling the
- // customer we skipped person processing for them would inflate the
- // count and name distinct_ids the limit never affected. v1 draws the
- // same line via `already_disabled` in
- // `v1::analytics::process::apply_token_distinct_id_limits`.
- let mut warned_distinct_ids: HashSet<&str> = HashSet::new();
- let mut warned_event_count: u64 = 0;
let mut already_disabled_event_count: u64 = 0;
for event in events.iter_mut() {
- // Person processing is already off, which at this point can only
- // come from an event restriction: the burst limiter runs after
- // this stage in `stamp_overflow_reason`, and the limiter's own
- // stamp is set below. The limiter has nothing left to take away
- // from this event, so consulting it would change nothing and
- // still cost a local cache miss and a Redis round trip.
+ let cache_key =
+ GlobalRateLimitKey::TokenDistinctId(&context.token, &event.event.distinct_id)
+ .to_cache_key();
+ // Charge every event, even one an event restriction already
+ // stripped of person processing: its volume belongs in the
+ // key's fleet count, or a covered key starts from zero when the
+ // restriction lifts. The check reads only the local cache.
+ let limited = limiter.is_limited(&cache_key, 1).await.is_some();
+
+ // Person processing is already off: nothing left to take away,
+ // so stamp nothing and keep it out of the customer-facing tallies.
if event.metadata.skip_person_processing {
already_disabled_event_count += 1;
continue;
}
- let cache_key =
- GlobalRateLimitKey::TokenDistinctId(&context.token, &event.event.distinct_id)
- .to_cache_key();
- if limiter.is_limited(&cache_key, 1).await.is_some() {
- let already_disabled = event.metadata.skip_person_processing;
+
+ if limited {
event.metadata.skip_person_processing = true;
// Reroute the hot key to overflow. AnalyticsMain only: historical
// never overflows, the AI lane keeps its dedicated topic (v1
@@ -547,10 +535,6 @@ async fn process_events_inner(
}
limited_distinct_ids.insert(&event.event.distinct_id);
limited_event_count += 1;
- if !already_disabled {
- warned_distinct_ids.insert(&event.event.distinct_id);
- warned_event_count += 1;
- }
}
}
if limited_event_count > 0 {
@@ -575,20 +559,18 @@ async fn process_events_inner(
}
if already_disabled_event_count > 0 {
- counter!(
- "capture_global_rate_limiter_skipped",
- "reason" => "person_processing_already_disabled",
- )
- .increment(already_disabled_event_count);
+ // Charged against the limiter but not re-stamped.
+ counter!("capture_global_rate_limiter_already_disabled")
+ .increment(already_disabled_event_count);
}
- if warned_event_count > 0 {
+ if limited_event_count > 0 {
emit_rate_limit_warning(
ingestion_warning_emitter.as_deref(),
&request_context(context),
CAPTURE_LEGACY_RATE_LIMIT,
- &warned_distinct_ids,
- warned_event_count,
+ &limited_distinct_ids,
+ limited_event_count,
);
}
}
diff --git a/rust/capture/src/global_rate_limiter.rs b/rust/capture/src/global_rate_limiter.rs
index d3d64d97816d..77ab8f1bafd6 100644
--- a/rust/capture/src/global_rate_limiter.rs
+++ b/rust/capture/src/global_rate_limiter.rs
@@ -56,6 +56,12 @@ const AI_BYTES_REDIS_KEY_PREFIX: &str = "@ph/grl/capture/ai_bytes";
/// Named fields rather than positional arguments: several are same-typed (two
/// `&str`, two `bool`) and a swap would silently misconfigure a limiter.
struct LimiterSpec<'a> {
+ /// Sliding window this limiter counts over. Sets Redis epoch numbering, so
+ /// limiters that share a key prefix must agree on it.
+ window_secs: u64,
+ /// Env var that supplied `window_secs`, so a zero window names the knob the
+ /// operator has to fix rather than the limiter that noticed.
+ window_env_var: &'a str,
/// Default budget per window for keys with no custom override.
threshold: u64,
/// Static `key=value` CSV seeding the custom-key map.
@@ -78,6 +84,21 @@ struct LimiterSpec<'a> {
dry_run: bool,
}
+/// The window the AI byte budget is enforced over, and the env var that
+/// supplied it. `AI_BYTE_LIMIT_WINDOW_INTERVAL_SECS` wins when set; otherwise
+/// the shared limiter window applies. Every place that derives the AI byte
+/// budget from a window must call this, so the enforced budget and any
+/// diagnostic computed from it cannot disagree.
+pub fn ai_byte_limit_window(config: &Config) -> (u64, &'static str) {
+ match config.ai_byte_limit_window_interval_secs {
+ Some(secs) => (secs, "AI_BYTE_LIMIT_WINDOW_INTERVAL_SECS"),
+ None => (
+ config.global_rate_limit_window_interval_secs,
+ "GLOBAL_RATE_LIMIT_WINDOW_INTERVAL_SECS",
+ ),
+ }
+}
+
pub struct GlobalRateLimiter {
limiter: Box<dyn CommonGlobalRateLimiter>,
dry_run: bool,
@@ -98,6 +119,8 @@ impl GlobalRateLimiter {
config,
redis_instances,
LimiterSpec {
+ window_secs: config.global_rate_limit_window_interval_secs,
+ window_env_var: "GLOBAL_RATE_LIMIT_WINDOW_INTERVAL_SECS",
threshold: config.global_rate_limit_token_distinctid_threshold,
custom_keys_csv: config
.global_rate_limit_token_distinctid_overrides_csv
@@ -126,6 +149,8 @@ impl GlobalRateLimiter {
config,
redis_instances,
LimiterSpec {
+ window_secs: config.global_rate_limit_window_interval_secs,
+ window_env_var: "GLOBAL_RATE_LIMIT_WINDOW_INTERVAL_SECS",
threshold: config.global_rate_limit_token_threshold,
custom_keys_csv: config.global_rate_limit_token_overrides_csv.as_ref(),
custom_key_scale: 1,
@@ -158,12 +183,14 @@ impl GlobalRateLimiter {
) -> anyhow::Result<Self> {
// `build` refuses to boot on a zero window, so this scaling never
// divides a budget down to nothing.
- let window_secs = config.global_rate_limit_window_interval_secs;
+ let (window_secs, window_env_var) = ai_byte_limit_window(config);
let metrics_scope = format!("{}_ai_bytes", config.capture_mode.as_tag());
Self::build(
config,
redis_instances,
LimiterSpec {
+ window_secs,
+ window_env_var,
threshold: config.ai_byte_limit_per_second.saturating_mul(window_secs),
custom_keys_csv: config.ai_byte_limit_overrides_csv.as_ref(),
custom_key_scale: window_secs,
@@ -212,10 +239,12 @@ impl GlobalRateLimiter {
// gives every bucket an infinite leak rate and the limiter admits
// everything. That is the opposite of what an operator setting a limit
// asked for, and it fails silently, so refuse to boot on it.
- if config.global_rate_limit_window_interval_secs == 0 {
+ if spec.window_secs == 0 {
anyhow::bail!(
- "invalid configuration: GLOBAL_RATE_LIMIT_WINDOW_INTERVAL_SECS must be greater than 0; \
- a zero window gives every key an infinite leak rate, so no limit is ever enforced"
+ "invalid configuration: {} must be greater than 0 (limiter {}); \
+ a zero window gives every key an infinite leak rate, so no limit is ever enforced",
+ spec.window_env_var,
+ spec.metrics_scope
);
}
@@ -266,7 +295,7 @@ impl GlobalRateLimiter {
let grl_config = GlobalRateLimiterConfig {
global_threshold: spec.threshold,
- window_interval: Duration::from_secs(config.global_rate_limit_window_interval_secs),
+ window_interval: Duration::from_secs(spec.window_secs),
sync_interval: Duration::from_secs(config.global_rate_limit_sync_interval_secs),
tick_interval: Duration::from_millis(config.global_rate_limit_tick_interval_ms),
redis_key_prefix: spec.redis_key_prefix.to_string(),
diff --git a/rust/capture/src/setup.rs b/rust/capture/src/setup.rs
index 1bf6ddd78477..9034b3c0509c 100644
--- a/rust/capture/src/setup.rs
+++ b/rust/capture/src/setup.rs
@@ -15,7 +15,7 @@ use tracing::{info, warn};
use crate::config::{CaptureMode, Config};
use crate::event_restrictions::{EventRestrictionService, Pipeline, RedisRestrictionsRepository};
-use crate::global_rate_limiter::GlobalRateLimiter;
+use crate::global_rate_limiter::{ai_byte_limit_window, GlobalRateLimiter};
use crate::prometheus::setup_metrics_recorder;
use crate::quota_limiters::{
is_exception_event, is_llm_event, is_survey_event, CaptureQuotaLimiter,
@@ -493,7 +493,7 @@ fn warn_if_ai_byte_budget_below_max_event(config: &Config) {
if max_event_bytes == 0 {
return;
}
- let window_secs = config.global_rate_limit_window_interval_secs;
+ let (window_secs, _) = ai_byte_limit_window(config);
let window_budget = ai_byte_limit_per_second(config).saturating_mul(window_secs);
if window_budget < max_event_bytes {
warn!(
@@ -1005,6 +1005,43 @@ mod tests {
);
}
+ /// The AI byte limiter takes its window from its own knob when one is set,
+ /// so a zero there has to be caught and named separately. Naming the wrong
+ /// variable sends an operator to a setting that is already correct.
+ #[test]
+ fn ai_byte_limiter_rejects_a_zero_window_from_its_own_knob() {
+ let cfg_env: HashMap<String, String> = [
+ ("REDIS_URL", "redis://localhost:6379/"),
+ ("CAPTURE_MODE", "events"),
+ ("KAFKA_HOSTS", "localhost:9092"),
+ ("KAFKA_TOPIC", "events_plugin_ingestion"),
+ ("GLOBAL_RATE_LIMIT_WINDOW_INTERVAL_SECS", "180"),
+ ("AI_BYTE_LIMIT_WINDOW_INTERVAL_SECS", "0"),
+ ]
+ .into_iter()
+ .map(|(k, v)| (k.to_string(), v.to_string()))
+ .collect();
+ let config: Config =
+ envconfig::Envconfig::init_from_hashmap(&cfg_env).expect("test config");
+
+ let err = match GlobalRateLimiter::new_ai_bytes(&config, vec![]) {
+ Ok(_) => panic!("a zero AI byte window must not build a limiter"),
+ Err(err) => err,
+ };
+ assert!(
+ err.to_string()
+ .contains("AI_BYTE_LIMIT_WINDOW_INTERVAL_SECS"),
+ "the error must name the AI byte knob, not the shared one, got: {err}"
+ );
+
+ // The shared window is valid here, so the token+distinct_id limiter is
+ // unaffected by the AI byte knob being wrong.
+ assert!(
+ GlobalRateLimiter::new_token_distinct_id(&config, vec![]).is_err(),
+ "an empty redis instance list still fails, but not on the window"
+ );
+ }
+
#[test]
#[should_panic(expected = "imports must never overflow")]
fn ai_events_overflow_valve_rejects_armed_valve_in_import_mode() {
diff --git a/rust/capture/src/v1/analytics/process.rs b/rust/capture/src/v1/analytics/process.rs
index f255029f1292..ab3e84f50bd0 100644
--- a/rust/capture/src/v1/analytics/process.rs
+++ b/rust/capture/src/v1/analytics/process.rs
@@ -163,8 +163,9 @@ pub async fn process_batch(
// `crate::overflow_parity` pins that across the whole matrix.
// 2. Lane assignment is assign-then-reroute in v1 versus a single
// `DataType::from_event_name` match in legacy.
- // Both paths consult the same shared limiter for every non-dropped event, so
- // per-key counts are identical regardless of which pipeline serves the key.
+ // Both paths charge the same shared limiter for every non-dropped event,
+ // including events whose person processing is already off, so per-key counts
+ // are identical regardless of which pipeline serves the key.
// Import is unaffected by both: the GRL never runs (guard below) and no
// overflowable lane is reachable, so behavior is identical across paths.
if state.capture_mode.applies_global_rate_limit() {
@@ -917,11 +918,9 @@ async fn apply_ai_byte_limits(
}
/// Per-batch tally of how the shared global rate limiter classified each
-/// evaluated event. All three fields count events (not distinct_ids), so
-/// `allowed + limited + already_disabled` equals the number of non-Drop events
-/// reaching this stage. Only `allowed + limited` were consulted against the
-/// limiter: an `already_disabled` event is skipped before the call, so it does
-/// not appear in the limiter's own per-key counts.
+/// evaluated event. All three fields count events (not distinct_ids) and all
+/// three charge the limiter, so `allowed + limited + already_disabled` equals
+/// the non-Drop events reaching this stage.
#[derive(Debug, Default, PartialEq, Eq)]
struct TokenDistinctIdTally {
allowed: u64,
@@ -944,26 +943,22 @@ async fn apply_token_distinct_id_limits(
if event.result != EventResult::Ok {
continue;
}
- // Person processing is already off for this event (illegal distinct_id,
- // an ops restriction, or a force-limited key upstream). The limiter has
- // nothing left to take away, so it is not consulted at all: the stamps
- // below would be redundant, and the call itself would cost a local cache
- // miss and a Redis round trip for a decision that cannot be acted on.
- // The event's volume therefore does not count toward the shared window.
- //
- // A merely rate-limited burst does NOT land here: it sets
- // `spread_partitions` without touching person processing, so such an
- // event still gets its warning stamped below, as it does on the v0 path.
- if event.force_disable_person_processing {
- already_disabled_count += 1;
- continue;
- }
-
let cache_key =
GlobalRateLimitKey::TokenDistinctId(&context.api_token, &event.event.distinct_id)
.to_cache_key();
+ // Charge every event, even one whose person processing is already off:
+ // its volume belongs in the key's fleet count, and the v0 path charges
+ // it too. The check reads only the local cache.
let limited = limiter.is_limited(&cache_key, 1).await.is_some();
+ // Nothing left to take away, so stamp nothing. A merely rate-limited
+ // burst does NOT land here: it sets `spread_partitions` without touching
+ // person processing, so it still gets its warning stamped below.
+ if event.force_disable_person_processing {
+ already_disabled_count += 1;
+ continue;
+ }
+
if limited {
event.result = EventResult::Warning;
// Disabling person processing also drops the ordering guarantee on
@@ -2744,10 +2739,10 @@ mod tests {
#[tokio::test]
async fn td_limits_skips_events_with_person_processing_already_off() {
// An event that already has person processing disabled (illegal
- // distinct_id, ops restriction, or burst overflow) is not consulted
- // against the shared limiter at all: the limiter has nothing left to take
- // away, so the call would cost a Redis round trip for a decision that
- // cannot be acted on. Its stamping is left untouched.
+ // distinct_id, ops restriction, or burst overflow) is still charged
+ // against the shared limiter, because its volume belongs in the key's
+ // fleet count. Its stamping is left untouched, because the limiter has
+ // nothing left to take away.
let (limiter, calls) = mock_limiter_with_log(vec!["phc_tok:user-1"]);
let ctx = td_context();
let mut events = vec![
@@ -2760,13 +2755,12 @@ mod tests {
apply_token_distinct_id_limits(&limiter, &ctx, None, &mut events).await;
- // The already-flagged event was never consulted, so it costs no Redis work.
assert!(
- !calls
+ calls
.lock()
.unwrap()
.contains(&"phc_tok:user-1".to_string()),
- "already-disabled event must not be consulted"
+ "already-disabled event must still charge the key's fleet count"
);
// Its stamping is untouched: result stays Ok, no overflow reroute.
let flagged = find_by_did(&events, "user-1");
@@ -2783,12 +2777,11 @@ mod tests {
#[tokio::test]
async fn td_limits_evaluates_only_events_it_can_act_on() {
- // Parity with legacy (`events::analytics`): the shared limiter is
- // consulted for every event whose fate it can still change, so per-key
- // counts are identical regardless of which pipeline serves the key. A
- // dropped event and one whose person processing is already off are both
- // excluded, for opposite reasons: one is gone, the other is already at
- // the outcome the limiter would impose.
+ // Parity with legacy (`events::analytics`): the shared limiter is charged
+ // for every event that reaches this stage, including one whose person
+ // processing is already off, so per-key counts are identical regardless
+ // of which pipeline serves the key. Only a dropped event is excluded,
+ // because its bytes never reach a topic.
let (limiter, calls) = mock_limiter_with_log(vec![]);
let ctx = td_context();
let mut events = vec![
@@ -2808,8 +2801,8 @@ mod tests {
seen.sort();
assert_eq!(
seen,
- vec!["phc_tok:user-1".to_string()],
- "limiter must be consulted only for events it can still act on"
+ vec!["phc_tok:user-1".to_string(), "phc_tok:user-2".to_string()],
+ "every event reaching this stage charges the limiter; only drops are excluded"
);
assert_eq!(
tally,
@@ -2819,9 +2812,13 @@ mod tests {
already_disabled: 1,
}
);
- // Invariant: `allowed + limited` accounts for exactly the consulted events,
- // so the emitted counters stay commensurable with the limiter's own counts.
- assert_eq!(tally.allowed + tally.limited, seen.len() as u64);
+ // Invariant: the three tally fields account for exactly the charged
+ // events, so the emitted counters stay commensurable with the limiter's
+ // own per-key counts.
+ assert_eq!(
+ tally.allowed + tally.limited + tally.already_disabled,
+ seen.len() as u64
+ );
}
#[tokio::test]
diff --git a/rust/capture/src/v1/quota_limiter_shim.rs b/rust/capture/src/v1/quota_limiter_shim.rs
index aefc96cfb7c4..ce4f1250a2aa 100644
--- a/rust/capture/src/v1/quota_limiter_shim.rs
+++ b/rust/capture/src/v1/quota_limiter_shim.rs
@@ -261,6 +261,7 @@ mod tests {
ai_byte_limit_per_second: 0,
ai_byte_limit_overrides_csv: None,
ai_byte_limit_dry_run: false,
+ ai_byte_limit_window_interval_secs: None,
ai_byte_limit_local_cache_max_entries: 300_000,
}
}
diff --git a/rust/capture/tests/common/utils.rs b/rust/capture/tests/common/utils.rs
index f6cdcda83d73..84e1427910f0 100644
--- a/rust/capture/tests/common/utils.rs
+++ b/rust/capture/tests/common/utils.rs
@@ -179,6 +179,7 @@ pub static DEFAULT_CONFIG: Lazy<Config> = Lazy::new(|| Config {
ai_byte_limit_per_second: 0,
ai_byte_limit_overrides_csv: None,
ai_byte_limit_dry_run: false,
+ ai_byte_limit_window_interval_secs: None,
ai_byte_limit_local_cache_max_entries: 300_000,
});
diff --git a/rust/capture/tests/integration_person_processing_matrix.rs b/rust/capture/tests/integration_person_processing_matrix.rs
index 599ca77b5a1c..99b3efd14d3a 100644
--- a/rust/capture/tests/integration_person_processing_matrix.rs
+++ b/rust/capture/tests/integration_person_processing_matrix.rs
@@ -139,9 +139,8 @@ impl Batch {
}
}
-/// Count limiter evaluations on the recorder the caller installed. Each
-/// evaluation increments this counter exactly once, so it measures the Redis
-/// work the skip exists to avoid.
+/// Count limiter evaluations on the recorder the caller installed. Every event
+/// that reaches the stage charges the limiter, restrictions included.
fn consultations(snapshotter: &metrics_util::debugging::Snapshotter) -> u64 {
snapshotter
.snapshot()
@@ -443,24 +442,25 @@ fn v1_lane(topic: &str) -> Lane {
Observed { record: Record { lane: Lane::Overflow, has_key: false, force_disable_person_processing: Some(true) }, limiter_consultations: 2 }
)]
// The skip-person restriction alone: person processing off and the key dropped,
-// on the main lane, and the limiter is never consulted.
+// on the main lane. The limiter is still charged, but it stamps nothing.
#[case::skip_person(
Inputs { skip_person_restriction: true, ..Inputs::default() },
- Observed { record: Record { lane: Lane::Main, has_key: false, force_disable_person_processing: Some(true) }, limiter_consultations: 0 }
+ Observed { record: Record { lane: Lane::Main, has_key: false, force_disable_person_processing: Some(true) }, limiter_consultations: 2 }
)]
#[case::skip_person_personless(
Inputs { skip_person_restriction: true, personless: true, ..Inputs::default() },
- Observed { record: Record { lane: Lane::Main, has_key: false, force_disable_person_processing: Some(true) }, limiter_consultations: 0 }
+ Observed { record: Record { lane: Lane::Main, has_key: false, force_disable_person_processing: Some(true) }, limiter_consultations: 2 }
)]
-// The restriction shadows the limiter entirely: the key is over its window, but
-// the limiter is skipped, so nothing reroutes it.
+// The restriction shadows the limiter's stamps: the key is over its window, but
+// the restriction already took person processing away, so nothing reroutes it.
+// The charge still lands.
#[case::skip_person_and_rate_limited(
Inputs { skip_person_restriction: true, over_rate_limit: true, ..Inputs::default() },
- Observed { record: Record { lane: Lane::Main, has_key: false, force_disable_person_processing: Some(true) }, limiter_consultations: 0 }
+ Observed { record: Record { lane: Lane::Main, has_key: false, force_disable_person_processing: Some(true) }, limiter_consultations: 2 }
)]
#[case::skip_person_and_rate_limited_personless(
Inputs { skip_person_restriction: true, over_rate_limit: true, personless: true, ..Inputs::default() },
- Observed { record: Record { lane: Lane::Main, has_key: false, force_disable_person_processing: Some(true) }, limiter_consultations: 0 }
+ Observed { record: Record { lane: Lane::Main, has_key: false, force_disable_person_processing: Some(true) }, limiter_consultations: 2 }
)]
// The overflow restriction alone moves the lane but leaves person processing on,
// so the key survives.
@@ -485,21 +485,21 @@ fn v1_lane(topic: &str) -> Lane {
// Both restrictions: the overflow lane from one, the dropped key from the other.
#[case::both_restrictions(
Inputs { skip_person_restriction: true, overflow_restriction: true, ..Inputs::default() },
- Observed { record: Record { lane: Lane::Overflow, has_key: false, force_disable_person_processing: Some(true) }, limiter_consultations: 0 }
+ Observed { record: Record { lane: Lane::Overflow, has_key: false, force_disable_person_processing: Some(true) }, limiter_consultations: 2 }
)]
#[case::both_restrictions_personless(
Inputs { skip_person_restriction: true, overflow_restriction: true, personless: true, ..Inputs::default() },
- Observed { record: Record { lane: Lane::Overflow, has_key: false, force_disable_person_processing: Some(true) }, limiter_consultations: 0 }
+ Observed { record: Record { lane: Lane::Overflow, has_key: false, force_disable_person_processing: Some(true) }, limiter_consultations: 2 }
)]
-// All three: the limiter is still skipped, and the restrictions alone produce
-// the same wire outcome the limiter would have.
+// All three: the limiter stamps nothing, and the restrictions alone produce the
+// same wire outcome the limiter would have.
#[case::everything(
Inputs { skip_person_restriction: true, overflow_restriction: true, over_rate_limit: true, ..Inputs::default() },
- Observed { record: Record { lane: Lane::Overflow, has_key: false, force_disable_person_processing: Some(true) }, limiter_consultations: 0 }
+ Observed { record: Record { lane: Lane::Overflow, has_key: false, force_disable_person_processing: Some(true) }, limiter_consultations: 2 }
)]
#[case::everything_personless(
Inputs { skip_person_restriction: true, overflow_restriction: true, over_rate_limit: true, personless: true, restricted_distinct_id: None },
- Observed { record: Record { lane: Lane::Overflow, has_key: false, force_disable_person_processing: Some(true) }, limiter_consultations: 0 }
+ Observed { record: Record { lane: Lane::Overflow, has_key: false, force_disable_person_processing: Some(true) }, limiter_consultations: 2 }
)]
#[tokio::test]
async fn person_processing_and_routing_matrix(#[case] inputs: Inputs, #[case] expected: Observed) {
@@ -522,11 +522,14 @@ async fn person_processing_and_routing_matrix(#[case] inputs: Inputs, #[case] ex
/// keys from the limiter.
///
/// The skip is a per-event decision, so a batch mixing a restricted key with an
-/// unrestricted one has to split: the restricted events skip the limiter and
-/// keep the main lane, while the unrestricted ones are still consulted and still
-/// rerouted once they exceed the window. Hoisting the check to the batch, or
-/// keying it on the token rather than the event, would silently stop rate
-/// limiting every other key belonging to a token that has any restriction at all.
+/// unrestricted one has to split: the restricted events keep the main lane and
+/// take no stamps, while the unrestricted ones are still rerouted once they
+/// exceed the window. Hoisting the check to the batch, or keying it on the token
+/// rather than the event, would silently stop rate limiting every other key
+/// belonging to a token that has any restriction at all.
+///
+/// Every event charges the limiter, restricted or not, so the consultation count
+/// covers the whole batch.
#[rstest]
#[case::skip_person(false)]
#[case::skip_person_and_force_overflow(true)]
@@ -559,10 +562,10 @@ async fn restriction_filtered_to_one_distinct_id_leaves_other_keys_rate_limited(
("v0", run_v0(inputs, &batch).await),
("v1", run_v1(inputs, &batch).await),
] {
- // Only the two unrestricted events cost a limiter evaluation.
assert_eq!(
- observed.limiter_consultations, 2,
- "{path}: the limiter must be consulted for the unrestricted key only"
+ observed.limiter_consultations, 4,
+ "{path}: every event charges the limiter, so a restricted key's volume \
+ stays in its own fleet count"
);
for i in 0..2 {
diff --git a/rust/common/limiters/GLOBAL_RATE_LIMITER.md b/rust/common/limiters/GLOBAL_RATE_LIMITER.md
index d1cf81662975..709009f7f7bd 100644
--- a/rust/common/limiters/GLOBAL_RATE_LIMITER.md
+++ b/rust/common/limiters/GLOBAL_RATE_LIMITER.md
@@ -110,6 +110,20 @@ This produces a smooth, continuously-updating estimate that's more accurate than
Each `CacheEntry` stores the last-known weighted count from Redis (`estimated_count`)
and the time it was synced (`synced_at`).
+
+`synced_at` is `None` until the first Redis read lands. A never-synced entry is
+due for a sync as soon as it clears `min_sync_floor`; a synced one waits out its
+pressure tier. Collapsing the two delays a new key's first read by a full tier
+interval, during which the node cannot see the fleet.
+
+**A known, tolerated race.** The request path's get-modify-insert can overwrite
+the entry a Redis read just refreshed. The effect is bounded: the clobbered
+entry is due for a sync at once (recovery is one tick), the stale estimate is
+never higher than the fresh one (it only under-counts), and the collision
+window is microseconds per event against one read per key every 7.5 to 60
+seconds. A fix via moka's per-key entry API cost ~0.3 µs per evaluation (+31%
+on this crate's bench) for no measurable change in decisions, so it is
+deliberately not applied.
Between syncs, the estimate **decays** at the configured leak rate:
```text
@@ -210,7 +224,7 @@ Tier boundaries are pressure-based (level / threshold), so they apply correctly
```rust
struct CacheEntry {
estimated_count: f64, // weighted count from last Redis sync
- synced_at: Instant, // when we last read from Redis
+ synced_at: Option<Instant>, // when we last read from Redis; None until the first read
local_pending: u64, // events counted locally since last sync, reset to 0 on sync
pressure: f64, // effective_level / threshold at last sync
}
@@ -232,6 +246,13 @@ TTL: 2 × window_interval (120s for 60s window)
Only 2 keys per entity exist at any time (current + previous epoch).
+**Two deployments that share a key prefix must agree on `window_interval`.**
+The epoch number is `floor(unix / window_interval)`, so a mismatch splits the
+shared counter into separate key namespaces. Capture's AI byte budget is one
+such namespace (its prefix carries no `capture_mode`). The
+`global_rate_limiter_window_seconds{scope}` gauge publishes each process's
+running value so an alert can compare them.
+
### Configuration
#### Rate limiting behavior
@@ -301,13 +322,16 @@ only if you're also changing the window/sync intervals.
a shorter idle timeout reclaims slots faster, keeping the cache responsive.
- `local_cache_ttl` acts as an upper bound on how stale an entry can get
before being forced to re-sync from scratch on next access.
-- `global_cache_ttl` is an enforcement requirement, not only Redis hygiene.
- Reads consult the current and previous epoch, so the previous epoch's key is
- still needed for a full window after its last write. Below 2 × `window_interval`
- it expires early, `weighted_count` reads `prev_count` as 0, and the fleet
- estimate is understated for the rest of every window — always toward
- under-limiting. `GlobalRateLimiterImpl::new` clamps it up and logs a warning.
- Making it much larger than 2 × `window_interval` wastes Redis memory on dead keys.
+- **`min_sync_floor` gates reads only.** Every event's count reaches Redis
+ regardless of the floor; the floor only suppresses the `MGET` for keys too far
+ under their threshold to be limited. Writes are bounded separately:
+ `absorb_update` merges by `(key, epoch)` per tick, so write volume scales with
+ distinct active keys, not event rate.
+- `global_cache_ttl` is an enforcement requirement, not only Redis hygiene: the
+ previous epoch's key is read for a full window after its last write, and a
+ TTL under 2 × `window_interval` zeroes `prev_count` early, understating the
+ estimate. `new` clamps it up and warns. Much larger values only waste Redis
+ memory on dead keys.
**All three TTLs are clamped at construction**, because each one expiring inside
the window it serves causes silent under-enforcement:
@@ -392,6 +416,7 @@ When multiple Redis instances are configured, work is partitioned by consistent
| `global_rate_limiter_sync_tier_gauge` | Gauge | Entity distribution across tiers (scanned every `TIER_SCAN_INTERVAL_TICKS`) |
| `global_rate_limiter_tier_transitions_total` | Counter | Tier promotion/demotion events |
| `global_rate_limiter_cache_size` | Gauge | Live local cache entry count vs cap |
+| `global_rate_limiter_window_seconds` | Gauge | Configured `window_interval` per scope. Deployments that share a Redis key prefix must report the same value, or their epoch keys diverge and the shared counter splits |
| `global_rate_limiter_eviction_total` | Counter | Cache evictions by cause (size/expired/explicit) |
| `global_rate_limiter_estimate_drift` | Histogram | Local vs Redis accuracy |
| `global_rate_limiter_sync_staleness_ms` | Histogram | Real staleness at access time |
diff --git a/rust/common/limiters/src/global_rate_limiter.rs b/rust/common/limiters/src/global_rate_limiter.rs
index af12e946c3fa..17dcac6f0b88 100644
--- a/rust/common/limiters/src/global_rate_limiter.rs
+++ b/rust/common/limiters/src/global_rate_limiter.rs
@@ -35,6 +35,7 @@ const GLOBAL_RATE_LIMITER_PIPELINE_HISTOGRAM: &str = "global_rate_limiter_pipeli
const GLOBAL_RATE_LIMITER_TICK_HISTOGRAM: &str = "global_rate_limiter_tick_ms";
const GLOBAL_RATE_LIMITER_PIPELINE_SIZE_HISTOGRAM: &str = "global_rate_limiter_pipeline_size";
const GLOBAL_RATE_LIMITER_PENDING_SYNC_SIZE_GAUGE: &str = "global_rate_limiter_pending_sync_size";
+const GLOBAL_RATE_LIMITER_WINDOW_GAUGE: &str = "global_rate_limiter_window_seconds";
const GLOBAL_RATE_LIMITER_SYNC_TIER_GAUGE: &str = "global_rate_limiter_sync_tier_gauge";
const GLOBAL_RATE_LIMITER_TIER_TRANSITIONS_COUNTER: &str =
"global_rate_limiter_tier_transitions_total";
@@ -318,8 +319,10 @@ impl Default for GlobalRateLimiterConfig {
pub struct CacheEntry {
/// Weighted count from last Redis sync (decays over time via leak_rate)
pub estimated_count: f64,
- /// When we last read from Redis
- pub synced_at: Instant,
+ /// When we last read from Redis; `None` until the first read lands. A
+ /// never-synced entry is due for a sync as soon as it clears the floor,
+ /// where a freshly synced one waits out its tier.
+ pub synced_at: Option<Instant>,
/// Events counted locally since last sync
pub local_pending: u64,
/// effective_level / threshold at last sync, determines adaptive sync tier
@@ -332,7 +335,11 @@ pub struct CacheEntry {
/// locally observed events. This keeps the estimate conservative (includes all
/// local events) while allowing the global contribution to drain away.
pub fn effective_level(entry: &CacheEntry, leak_rate: f64, now: Instant) -> f64 {
- let elapsed = now.duration_since(entry.synced_at).as_secs_f64();
+ // Never synced: nothing to decay yet, so the level is local counts alone.
+ let Some(synced_at) = entry.synced_at else {
+ return entry.local_pending as f64;
+ };
+ let elapsed = now.duration_since(synced_at).as_secs_f64();
let drained = leak_rate * elapsed;
(entry.estimated_count - drained).max(0.0) + entry.local_pending as f64
}
@@ -543,14 +550,11 @@ impl GlobalRateLimiterImpl {
);
config.local_cache_ttl = config.window_interval;
}
- // Reads consult the current and the previous epoch, so the previous
- // epoch's Redis key is still needed for a full window after its last
- // write. A TTL below 2 x window_interval expires that key while it is
- // still being read, and `weighted_count` then takes `prev_count` as 0.
- // That understates the fleet estimate for the rest of the window and
- // under-enforces. `global_cache_ttl` has a default derived from the
- // default window, so any caller that changes the window without
- // changing the TTL lands here.
+ // The previous epoch's Redis key is read for a full window after its
+ // last write, so a TTL under 2x the window zeroes `prev_count` early
+ // and under-enforces. The default TTL derives from the default window,
+ // so a caller that raises only the window lands here. Details in
+ // GLOBAL_RATE_LIMITER.md.
let min_global_cache_ttl = config.window_interval * 2;
if config.global_cache_ttl < min_global_cache_ttl {
warn!(
@@ -653,9 +657,10 @@ impl GlobalRateLimiterImpl {
let (level, entry_exists) = if let Some(mut entry) = self.cache.get(key) {
let level = effective_level(&entry, leak_rate, now_instant);
- // Record staleness for observability
- let staleness_ms = now_instant.duration_since(entry.synced_at).as_millis() as f64;
- metrics::histogram!(GLOBAL_RATE_LIMITER_SYNC_STALENESS_HISTOGRAM, "scope" => self.scope).record(staleness_ms);
+ if let Some(synced_at) = entry.synced_at {
+ let staleness_ms = now_instant.duration_since(synced_at).as_millis() as f64;
+ metrics::histogram!(GLOBAL_RATE_LIMITER_SYNC_STALENESS_HISTOGRAM, "scope" => self.scope).record(staleness_ms);
+ }
// Sync decision. The absolute floor is checked first: a key this far
// under its threshold cannot be limited whatever the other nodes
@@ -674,7 +679,14 @@ impl GlobalRateLimiterImpl {
tier_sync_interval(effective_pressure, self.config.sync_interval)
.unwrap_or_else(|| self.config.sync_interval.mul_f64(4.0));
- if now_instant.duration_since(entry.synced_at) > tier_interval {
+ // A never-synced entry is due immediately: its level is local
+ // only, and waiting a tier interval to learn the fleet count
+ // delays every verdict on the key by that long.
+ let due = match entry.synced_at {
+ None => true,
+ Some(synced_at) => now_instant.duration_since(synced_at) > tier_interval,
+ };
+ if due {
self.queue_sync(key);
metrics::counter!(GLOBAL_RATE_LIMITER_CACHE_COUNTER, "scope" => self.scope, "result" => "sync_queued")
.increment(1);
@@ -697,7 +709,7 @@ impl GlobalRateLimiterImpl {
// Insert a fresh entry so subsequent requests have local_pending tracked
let entry = CacheEntry {
estimated_count: 0.0,
- synced_at: now_instant,
+ synced_at: None,
local_pending: count,
pressure: 0.0,
};
@@ -996,7 +1008,7 @@ impl GlobalRateLimiterImpl {
// Cache-size gauge every tick (O(1)); per-tier distribution via a
// throttled full scan (slow-moving, see TIER_SCAN_INTERVAL_TICKS).
- Self::emit_cache_gauges(cache, scope, tick_n);
+ Self::emit_cache_gauges(cache, scope, tick_n, config.window_interval);
// Take a bounded slice of the pending set rather than all of it. The
// remainder stays queued, so a backlog surfaces as sync staleness instead
@@ -1418,7 +1430,7 @@ impl GlobalRateLimiterImpl {
key.clone(),
CacheEntry {
estimated_count: estimated,
- synced_at: now_instant,
+ synced_at: Some(now_instant),
local_pending: 0,
pressure,
},
@@ -1432,10 +1444,21 @@ impl GlobalRateLimiterImpl {
/// distribution needs a full `cache.iter()` scan, so it runs only every
/// `TIER_SCAN_INTERVAL_TICKS`: the distribution moves slowly and prod metrics
/// dedup to 60s, so scanning every tick would be wasted work under load.
- fn emit_cache_gauges(cache: &Cache<String, CacheEntry>, scope: &'static str, tick_n: u64) {
+ fn emit_cache_gauges(
+ cache: &Cache<String, CacheEntry>,
+ scope: &'static str,
+ tick_n: u64,
+ window_interval: Duration,
+ ) {
metrics::gauge!(GLOBAL_RATE_LIMITER_CACHE_SIZE_GAUGE, "scope" => scope)
.set(cache.entry_count() as f64);
+ // Deployments that share a Redis key prefix must agree on the window,
+ // or their epoch keys diverge and the shared counter silently splits.
+ // Publish the running value so an alert can compare deployments.
+ metrics::gauge!(GLOBAL_RATE_LIMITER_WINDOW_GAUGE, "scope" => scope)
+ .set(window_interval.as_secs_f64());
+
if tick_n.is_multiple_of(TIER_SCAN_INTERVAL_TICKS) {
let tier_counts = Self::scan_tier_counts(cache);
for i in 0..4 {
@@ -1591,20 +1614,24 @@ mod tests {
fn test_effective_level_decay() {
let base = Instant::now();
let cases = vec![
- // (estimated_count, elapsed_secs, local_pending, leak_rate, expected)
- (100.0, 0.0, 0, 10.0, 100.0), // no elapsed: full count
- (100.0, 10.0, 0, 10.0, 0.0), // full drain
- (100.0, 5.0, 0, 10.0, 50.0), // partial drain
- (100.0, 0.0, 50, 10.0, 150.0), // local_pending adds
- (100.0, 5.0, 30, 10.0, 80.0), // drain + pending: (100-50)+30
- (10.0, 20.0, 0, 10.0, 0.0), // over-drain floors at 0
- (10.0, 20.0, 5, 10.0, 5.0), // over-drain + pending
+ // (estimated_count, elapsed_secs, local_pending, leak_rate, synced, expected)
+ (100.0, 0.0, 0, 10.0, true, 100.0), // no elapsed: full count
+ (100.0, 10.0, 0, 10.0, true, 0.0), // full drain
+ (100.0, 5.0, 0, 10.0, true, 50.0), // partial drain
+ (100.0, 0.0, 50, 10.0, true, 150.0), // local_pending adds
+ (100.0, 5.0, 30, 10.0, true, 80.0), // drain + pending: (100-50)+30
+ (10.0, 20.0, 0, 10.0, true, 0.0), // over-drain floors at 0
+ (10.0, 20.0, 5, 10.0, true, 5.0), // over-drain + pending
+ // Never synced: no fleet estimate exists yet, so nothing decays and
+ // the level is the local count alone, whatever the other fields say.
+ (100.0, 10.0, 7, 10.0, false, 7.0),
+ (0.0, 0.0, 0, 10.0, false, 0.0),
];
- for (est, elapsed, pending, rate, expected) in cases {
+ for (est, elapsed, pending, rate, synced, expected) in cases {
let entry = CacheEntry {
estimated_count: est,
- synced_at: base,
+ synced_at: synced.then_some(base),
local_pending: pending,
pressure: 0.0,
};
@@ -1612,7 +1639,7 @@ mod tests {
let result = effective_level(&entry, rate, now);
assert!(
(result - expected).abs() < 0.01,
- "effective_level(est={est}, elapsed={elapsed}s, pending={pending}, rate={rate}) = {result}, expected {expected}"
+ "effective_level(est={est}, elapsed={elapsed}s, pending={pending}, rate={rate}, synced={synced}) = {result}, expected {expected}"
);
}
}
@@ -1713,7 +1740,7 @@ mod tests {
"test_key".to_string(),
CacheEntry {
estimated_count: 5.0,
- synced_at: Instant::now(),
+ synced_at: Some(Instant::now()),
local_pending: 0,
pressure: 0.5,
},
@@ -1736,7 +1763,7 @@ mod tests {
"test_key".to_string(),
CacheEntry {
estimated_count: 10.0,
- synced_at: Instant::now(),
+ synced_at: Some(Instant::now()),
local_pending: 0,
pressure: 1.0,
},
@@ -1759,7 +1786,7 @@ mod tests {
"test_key".to_string(),
CacheEntry {
estimated_count: 15.0,
- synced_at: Instant::now(),
+ synced_at: Some(Instant::now()),
local_pending: 0,
pressure: 1.5,
},
@@ -1810,7 +1837,7 @@ mod tests {
"cached_key".to_string(),
CacheEntry {
estimated_count: 5.0,
- synced_at: Instant::now(),
+ synced_at: Some(Instant::now()),
local_pending: 0,
pressure: 0.5,
},
@@ -1841,7 +1868,7 @@ mod tests {
"key_a".to_string(),
CacheEntry {
estimated_count: 1.0,
- synced_at: Instant::now(),
+ synced_at: Some(Instant::now()),
local_pending: 0,
pressure: 0.1,
},
@@ -1866,7 +1893,7 @@ mod tests {
"limited_key".to_string(),
CacheEntry {
estimated_count: 10.0,
- synced_at: Instant::now(),
+ synced_at: Some(Instant::now()),
local_pending: 0,
pressure: 1.0,
},
@@ -1919,7 +1946,7 @@ mod tests {
"custom_key".to_string(),
CacheEntry {
estimated_count: 5.0,
- synced_at: Instant::now(),
+ synced_at: Some(Instant::now()),
local_pending: 0,
pressure: 1.0,
},
@@ -1944,7 +1971,7 @@ mod tests {
"custom_key".to_string(),
CacheEntry {
estimated_count: 5.0,
- synced_at: Instant::now(),
+ synced_at: Some(Instant::now()),
local_pending: 0,
pressure: 0.5,
},
@@ -1989,7 +2016,7 @@ mod tests {
"custom_a".to_string(),
CacheEntry {
estimated_count: 10.0,
- synced_at: Instant::now(),
+ synced_at: Some(Instant::now()),
local_pending: 0,
pressure: 2.0,
},
@@ -2027,7 +2054,7 @@ mod tests {
"stale_key".to_string(),
CacheEntry {
estimated_count: 5.0,
- synced_at: Instant::now() - Duration::from_secs(60),
+ synced_at: Some(Instant::now() - Duration::from_secs(60)),
local_pending: 0,
pressure: 0.5,
},
@@ -2051,7 +2078,7 @@ mod tests {
"fresh_key".to_string(),
CacheEntry {
estimated_count: 5.0,
- synced_at: Instant::now(),
+ synced_at: Some(Instant::now()),
local_pending: 0,
pressure: 0.5,
},
@@ -2105,6 +2132,52 @@ mod tests {
}
}
+ #[tokio::test]
+ async fn test_sync_due_immediately_only_when_never_synced() {
+ // (label, synced_at, expect_queued)
+ let cases = vec![
+ ("never synced", None, true),
+ ("synced just now", Some(Instant::now()), false),
+ ];
+
+ for (label, synced_at, expect_queued) in cases {
+ let client = Arc::new(MockRedisClient::new());
+ let config = GlobalRateLimiterConfig {
+ // 1% of the threshold is 10, so the configured floor of 5 applies.
+ global_threshold: 1000,
+ min_sync_floor: 5,
+ // Park the background drain so pending_sync shows only what
+ // check_limit queued.
+ tick_interval: Duration::from_secs(3600),
+ ..test_config()
+ };
+ let limiter = GlobalRateLimiterImpl::new(config, vec![client]).unwrap();
+
+ // local_pending is above the floor, so the sync decision comes down
+ // to synced_at alone. Pressure stays Idle, whose tier interval is
+ // 4 x sync_interval = 60s, far longer than this test takes.
+ limiter.cache.insert(
+ "above_floor".to_string(),
+ CacheEntry {
+ estimated_count: 0.0,
+ synced_at,
+ local_pending: 11,
+ pressure: 0.0,
+ },
+ );
+
+ let _ = limiter.check_limit("above_floor", 1, None).await;
+
+ assert_eq!(
+ limiter.pending_sync.contains("above_floor"),
+ expect_queued,
+ "an entry {label} and above the floor should queue a sync={expect_queued} -- \
+ a never-synced entry has no fleet count behind it, so making it wait out a \
+ tier interval hides the key from the limiter for that long"
+ );
+ }
+ }
+
#[tokio::test]
async fn test_idle_timeout_clamped_up_to_window_interval() {
// (idle_timeout_secs, expected_secs)
@@ -2389,7 +2462,7 @@ mod tests {
"fleet_hot".to_string(),
CacheEntry {
estimated_count: 0.0,
- synced_at: Instant::now() - Duration::from_secs(120),
+ synced_at: Some(Instant::now() - Duration::from_secs(120)),
local_pending: 50,
pressure: 0.05,
},
@@ -2463,7 +2536,7 @@ mod tests {
"dedup_key".to_string(),
CacheEntry {
estimated_count: 5.0,
- synced_at: Instant::now() - Duration::from_secs(60),
+ synced_at: Some(Instant::now() - Duration::from_secs(60)),
local_pending: 0,
pressure: 0.5,
},
@@ -2561,7 +2634,7 @@ mod tests {
"entity_a".to_string(),
CacheEntry {
estimated_count: 0.0,
- synced_at: Instant::now() - Duration::from_secs(30),
+ synced_at: Some(Instant::now() - Duration::from_secs(30)),
local_pending: 3,
pressure: 0.0,
},
@@ -2607,7 +2680,7 @@ mod tests {
"custom_entity".to_string(),
CacheEntry {
estimated_count: 0.0,
- synced_at: Instant::now() - Duration::from_secs(30),
+ synced_at: Some(Instant::now() - Duration::from_secs(30)),
local_pending: 3,
pressure: 0.0,
},
@@ -2651,7 +2724,7 @@ mod tests {
"key".to_string(),
CacheEntry {
estimated_count: 0.0,
- synced_at: Instant::now() - Duration::from_secs(30),
+ synced_at: Some(Instant::now() - Duration::from_secs(30)),
local_pending: prior_pending,
pressure: 0.0,
},
@@ -2676,7 +2749,7 @@ mod tests {
fn seed_entry(pressure: f64) -> CacheEntry {
CacheEntry {
estimated_count: 0.0,
- synced_at: Instant::now() - Duration::from_secs(30),
+ synced_at: Some(Instant::now() - Duration::from_secs(30)),
local_pending: 0,
pressure,
}
diff --git a/rust/common/limiters/tests/global_rate_limiter_integration_tests.rs b/rust/common/limiters/tests/global_rate_limiter_integration_tests.rs
index 3068ed3792b0..dfbb7c03d5ce 100644
--- a/rust/common/limiters/tests/global_rate_limiter_integration_tests.rs
+++ b/rust/common/limiters/tests/global_rate_limiter_integration_tests.rs
@@ -105,19 +105,16 @@ async fn test_epoch_key_ttl_expiry() {
};
let mut config = test_config("ttl_expiry");
- // `new()` holds global_cache_ttl at 2 x window_interval, so a TTL short
- // enough to observe inside a test needs a short window too. The tick purges
- // any deferred write whose epoch has aged past the readable pair, which at
- // a 2s window is 2-4s after the write. The tick runs every 100ms, so that
- // margin holds even on a loaded CI runner; a 1s window would not.
+ // `new()` clamps global_cache_ttl to 2x the window, so observing expiry
+ // needs a short window. 2s (not 1s) keeps the tick's stale-epoch purge
+ // 2-4s away from the write, safe on a loaded runner.
config.window_interval = Duration::from_secs(2);
config.global_cache_ttl = Duration::from_secs(4);
let redis_arc: Arc<dyn Client + Send + Sync> = Arc::new(redis.clone());
let limiter = GlobalRateLimiterImpl::new(config.clone(), vec![redis_arc]).unwrap();
- // Pin the write and the epoch lookup to one timestamp. A short window rolls
- // the epoch between the two otherwise, and the test reads a key the write
- // never touched.
+ // Pin the write and the epoch lookup to one timestamp, or a short window
+ // rolls the epoch between them.
let now = Utc::now();
let _ = limiter.check_limit("ttl_key", 10, Some(now)).await;