: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
fix(capture): bound global rate limiter redis work to enforceable keys (#83250)
Eli Reisman2b63401228ba
diff --git a/posthog/management/commands/sync_global_rate_limit_thresholds.py b/posthog/management/commands/sync_global_rate_limit_thresholds.pynew file mode 100644index 000000000000..aff1fd016b8a--- /dev/null+++ b/posthog/management/commands/sync_global_rate_limit_thresholds.py@@ -0,0 +1,26 @@+from django.core.management.base import BaseCommand++from posthog.models.global_rate_limit_threshold_config import (+ CUSTOM_THRESHOLDS_REDIS_KEY,+ GlobalRateLimitThresholdConfig,+ regenerate_redis_thresholds,+)+++class Command(BaseCommand):+ help = (+ "Write the capture global rate limiter's custom-threshold blob to Redis from the "+ "current GlobalRateLimitThresholdConfig rows. Normally the post_save/post_delete "+ "signals keep the blob current, but they only fire on row changes: an environment "+ "with zero rows has never written the key at all, and capture treats the absent key "+ "as fail-static (it polls forever without ever loading a map). Run this once per "+ "environment to bootstrap the key (an explicit empty blob is a valid, loadable state), "+ "or to force a resync if the key is lost."+ )++ def handle(self, *args, **options) -> None:+ row_count = GlobalRateLimitThresholdConfig.objects.count()+ regenerate_redis_thresholds()+ self.stdout.write(+ self.style.SUCCESS(f"Wrote {row_count} threshold override(s) to Redis key {CUSTOM_THRESHOLDS_REDIS_KEY!r}")+ )diff --git a/posthog/models/test/test_global_rate_limit_threshold_config.py b/posthog/models/test/test_global_rate_limit_threshold_config.pyindex 052f7388550d..25e343ffd78d 100644--- a/posthog/models/test/test_global_rate_limit_threshold_config.py+++ b/posthog/models/test/test_global_rate_limit_threshold_config.py@@ -2,6 +2,7 @@ import jsonfrom posthog.test.base import BaseTest+from django.core.management import call_commandfrom django.db import transactionfrom parameterized import parameterized@@ -40,6 +41,16 @@ class TestGlobalRateLimitThresholdConfig(BaseTest):config = GlobalRateLimitThresholdConfig(token="phc_abc", distinct_id=long_distinct_id, threshold=10)self.assertEqual(config.resolved_key, f"phc_abc:{'d' * MAX_DISTINCT_ID_CHARS}")+ def test_sync_command_bootstraps_empty_blob(self):+ # An environment with zero rows never fires the signals, so the Redis+ # key stays absent and capture polls not_found forever. The command+ # writes the explicit empty blob, which capture loads as a valid map.+ self.assertIsNone(self.redis_client.get(CUSTOM_THRESHOLDS_REDIS_KEY))++ call_command("sync_global_rate_limit_thresholds")++ self.assertEqual(self._blob(), {})+def test_post_save_writes_blob(self):with self.captureOnCommitCallbacks(execute=True):GlobalRateLimitThresholdConfig.objects.create(token="phc_abc", threshold=1000)diff --git a/rust/Cargo.lock b/rust/Cargo.lockindex 79418b36a860..4ece0d4dd949 100644--- a/rust/Cargo.lock+++ b/rust/Cargo.lock@@ -2912,6 +2912,7 @@ dependencies = [name = "common-redis"version = "0.1.0"dependencies = [+ "arc-swap","async-trait","futures-timer","redis",diff --git a/rust/capture/src/config.rs b/rust/capture/src/config.rsindex a03a2a8817ec..58bfde7fc275 100644--- a/rust/capture/src/config.rs+++ b/rust/capture/src/config.rs@@ -149,6 +149,70 @@ pub struct Config {#[envconfig(default = "5000000")]pub global_rate_limit_token_distinctid_local_cache_max_entries: u64,+ /// Minimum effective event count before a key earns a Redis sync. Keys below+ /// this cannot be limited whatever other nodes report, so syncing them costs+ /// two Redis keys per tick for no enforcement value. With an unbounded key+ /// space this is what keeps the pipeline sized to enforceable keys rather+ /// than to total traffic. 0 syncs every key.+ ///+ /// The level is per-pod, so this must stay well under+ /// `threshold / pod_count` or a key sitting at the threshold but spread+ /// evenly across the fleet would never sync and could never be limited.+ #[envconfig(default = "10")]+ pub global_rate_limit_min_sync_floor: u64,++ /// Max keys drained from the pending-sync set per tick. Excess stays queued,+ /// so a backlog shows up as sync staleness rather than a tick that overruns+ /// its interval.+ #[envconfig(default = "20000")]+ pub global_rate_limit_max_sync_keys_per_tick: usize,++ /// Max Redis keys per individual command. Reads cost two keys per entity, so+ /// an entity chunk is half this. Bounds how long any single command can take,+ /// which is what the per-command timeouts below are budgeting for.+ #[envconfig(default = "2000")]+ pub global_rate_limit_max_keys_per_command: usize,++ /// How many chunked commands may be in flight at once per Redis instance.+ #[envconfig(default = "4")]+ pub global_rate_limit_max_concurrent_commands: usize,++ /// Max distinct (key, epoch) entries held in the deferred write batch per+ /// limiter. Merges are always accepted; at the cap, updates for new keys+ /// are dropped and counted (fail-open). Bounds limiter memory under+ /// unique-key floods that outrun the per-tick write drain.+ #[envconfig(default = "200000")]+ pub global_rate_limit_max_write_batch_entries: usize,++ /// Max keys held in the pending-sync set per limiter. At the cap, new sync+ /// requests drop and re-queue on the key's next request (fail-open).+ /// Bounds limiter memory alongside the write-batch cap.+ #[envconfig(default = "200000")]+ pub global_rate_limit_max_pending_sync_entries: usize,++ /// How long a local cache entry survives regardless of access (seconds).+ /// Bounds how stale a key's cached count can be before it is rebuilt.+ #[envconfig(default = "600")]+ pub global_rate_limit_local_cache_ttl_secs: u64,++ /// Evict local cache entries not accessed within this window (seconds).+ /// This is the main lever on cache cardinality: with a key space dominated+ /// by one-shot identities, most entries are pure churn and hold a slot for+ /// the full idle window. Must stay at or above the rate-limit window, or+ /// entries expire inside the enforcement window and the limiter loses the+ /// counts it is supposed to be accumulating -- values below the window are+ /// clamped up, with a warning.+ #[envconfig(default = "300")]+ pub global_rate_limit_local_cache_idle_timeout_secs: u64,++ /// Timeout for a single global rate limiter Redis read command (milliseconds).+ #[envconfig(default = "250")]+ pub global_rate_limit_read_timeout_ms: u64,++ /// Timeout for a single global rate limiter Redis write command (milliseconds).+ #[envconfig(default = "250")]+ pub global_rate_limit_write_timeout_ms: u64,+// --- Token-only limiter config (not currently used in production, retained for new_token()) ---/// Per-token rate limit threshold per window interval/// Note: default is too high to trigger limiting in productiondiff --git a/rust/capture/src/global_rate_limiter.rs b/rust/capture/src/global_rate_limiter.rsindex 6676d0582c4b..8f158538bc79 100644--- a/rust/capture/src/global_rate_limiter.rs+++ b/rust/capture/src/global_rate_limiter.rs@@ -82,6 +82,7 @@ impl GlobalRateLimiter {.global_rate_limit_token_distinctid_overrides_csv.as_ref(),config.global_rate_limit_token_distinctid_local_cache_max_entries,+ config.global_rate_limit_min_sync_floor,&prefix,&metrics_scope,config.global_rate_limit_custom_threshold_key.is_some(),@@ -102,6 +103,7 @@ impl GlobalRateLimiter {config.global_rate_limit_token_threshold,config.global_rate_limit_token_overrides_csv.as_ref(),config.global_rate_limit_token_local_cache_max_entries,+ config.global_rate_limit_min_sync_floor,&prefix,&metrics_scope,// The token-only limiter is not wired to the dynamic refresh source.@@ -136,6 +138,7 @@ impl GlobalRateLimiter {threshold: u64,custom_keys_csv: Option<&String>,local_cache_max_entries: u64,+ min_sync_floor: u64,redis_key_prefix: &str,metrics_scope: &str,enable_dynamic_source: bool,@@ -197,6 +200,18 @@ impl GlobalRateLimiter {),local_cache_max_entries,metrics_scope: metrics_scope.to_string(),+ min_sync_floor,+ max_sync_keys_per_tick: config.global_rate_limit_max_sync_keys_per_tick,+ max_keys_per_command: config.global_rate_limit_max_keys_per_command,+ max_concurrent_commands: config.global_rate_limit_max_concurrent_commands,+ max_write_batch_entries: config.global_rate_limit_max_write_batch_entries,+ max_pending_sync_entries: config.global_rate_limit_max_pending_sync_entries,+ global_read_timeout: Duration::from_millis(config.global_rate_limit_read_timeout_ms),+ global_write_timeout: Duration::from_millis(config.global_rate_limit_write_timeout_ms),+ local_cache_ttl: Duration::from_secs(config.global_rate_limit_local_cache_ttl_secs),+ local_cache_idle_timeout: Duration::from_secs(+ config.global_rate_limit_local_cache_idle_timeout_secs,+ ),..Default::default()};diff --git a/rust/capture/src/v1/quota_limiter_shim.rs b/rust/capture/src/v1/quota_limiter_shim.rsindex d9231f19e9a1..6f9b67809147 100644--- a/rust/capture/src/v1/quota_limiter_shim.rs+++ b/rust/capture/src/v1/quota_limiter_shim.rs@@ -131,6 +131,16 @@ mod tests {global_rate_limit_token_distinctid_threshold: 10_000,global_rate_limit_token_distinctid_overrides_csv: None,global_rate_limit_token_distinctid_local_cache_max_entries: 300_000,+ global_rate_limit_min_sync_floor: 0,+ global_rate_limit_max_sync_keys_per_tick: 20_000,+ global_rate_limit_max_keys_per_command: 2_000,+ global_rate_limit_max_concurrent_commands: 4,+ global_rate_limit_max_write_batch_entries: 200_000,+ global_rate_limit_max_pending_sync_entries: 200_000,+ global_rate_limit_local_cache_ttl_secs: 600,+ global_rate_limit_local_cache_idle_timeout_secs: 300,+ global_rate_limit_read_timeout_ms: 250,+ global_rate_limit_write_timeout_ms: 250,global_rate_limit_token_threshold: 300_000,global_rate_limit_token_overrides_csv: None,global_rate_limit_token_local_cache_max_entries: 300_000,diff --git a/rust/capture/tests/common/utils.rs b/rust/capture/tests/common/utils.rsindex 03cf7ccfe357..f1e51ab3f31b 100644--- a/rust/capture/tests/common/utils.rs+++ b/rust/capture/tests/common/utils.rs@@ -47,6 +47,18 @@ pub static DEFAULT_CONFIG: Lazy<Config> = Lazy::new(|| Config {global_rate_limit_token_distinctid_threshold: 10_000,global_rate_limit_token_distinctid_overrides_csv: None,global_rate_limit_token_distinctid_local_cache_max_entries: 300_000,+ // Integration tests assert on exact limiter behavior at a threshold of+ // 10_000, so every key syncs and every tick drains fully.+ global_rate_limit_min_sync_floor: 0,+ global_rate_limit_max_sync_keys_per_tick: 20_000,+ global_rate_limit_max_keys_per_command: 2_000,+ global_rate_limit_max_concurrent_commands: 4,+ global_rate_limit_max_write_batch_entries: 200_000,+ global_rate_limit_max_pending_sync_entries: 200_000,+ global_rate_limit_local_cache_ttl_secs: 600,+ global_rate_limit_local_cache_idle_timeout_secs: 300,+ global_rate_limit_read_timeout_ms: 250,+ global_rate_limit_write_timeout_ms: 250,global_rate_limit_token_threshold: 300_000,global_rate_limit_token_overrides_csv: None,global_rate_limit_token_local_cache_max_entries: 300_000,diff --git a/rust/common/limiters/benches/global_rate_limiter.rs b/rust/common/limiters/benches/global_rate_limiter.rsindex d32834345758..9316207c6a9d 100644--- a/rust/common/limiters/benches/global_rate_limiter.rs+++ b/rust/common/limiters/benches/global_rate_limiter.rs@@ -87,6 +87,14 @@ fn bench_config() -> GlobalRateLimiterConfig {global_read_timeout: Duration::from_millis(50),global_write_timeout: Duration::from_millis(50),metrics_scope: "bench".to_string(),+ // The benchmark measures the hot path against a fully-syncing limiter, so+ // the floor and the per-tick bound are both left wide open.+ min_sync_floor: 0,+ max_sync_keys_per_tick: 100_000,+ max_keys_per_command: 2_000,+ max_concurrent_commands: 4,+ max_write_batch_entries: 200_000,+ max_pending_sync_entries: 200_000,}}diff --git a/rust/common/limiters/src/global_rate_limiter.rs b/rust/common/limiters/src/global_rate_limiter.rsindex 625f93d866e2..f00f8b5f1a04 100644--- a/rust/common/limiters/src/global_rate_limiter.rs+++ b/rust/common/limiters/src/global_rate_limiter.rs@@ -42,6 +42,14 @@ const GLOBAL_RATE_LIMITER_ESTIMATE_DRIFT_HISTOGRAM: &str = "global_rate_limiter_const GLOBAL_RATE_LIMITER_SYNC_STALENESS_HISTOGRAM: &str = "global_rate_limiter_sync_staleness_ms";const GLOBAL_RATE_LIMITER_CACHE_SIZE_GAUGE: &str = "global_rate_limiter_cache_size";const GLOBAL_RATE_LIMITER_EVICTION_COUNTER: &str = "global_rate_limiter_eviction_total";+/// Keys still queued for sync after a tick took its bounded slice.+const GLOBAL_RATE_LIMITER_SYNC_DEFERRED_GAUGE: &str = "global_rate_limiter_sync_deferred_size";+/// (key, epoch) write entries still batched after a tick took its bounded slice.+const GLOBAL_RATE_LIMITER_WRITE_DEFERRED_GAUGE: &str = "global_rate_limiter_write_deferred_size";+/// Syncs not queued because the key's level is below `min_sync_floor`.+const GLOBAL_RATE_LIMITER_SYNC_SKIPPED_COUNTER: &str = "global_rate_limiter_sync_skipped_total";+/// Redis commands issued per tick, after chunking.+const GLOBAL_RATE_LIMITER_COMMANDS_HISTOGRAM: &str = "global_rate_limiter_commands_per_tick";/// Number of custom-key thresholds applied at the last successful refresh.const CUSTOM_THRESHOLDS_LOADED_GAUGE: &str = "global_rate_limiter_custom_thresholds_loaded";/// Unix timestamp of the last successful custom-key threshold refresh.@@ -181,6 +189,47 @@ pub struct GlobalRateLimiterConfig {pub local_cache_max_entries: u64,/// Capacity of the mpsc channel for async global cache updatespub channel_capacity: usize,+ /// Minimum effective level before a key is worth a Redis round trip.+ ///+ /// A key far below its threshold cannot be limited no matter what the other+ /// nodes report, so syncing it buys nothing and costs two Redis keys per+ /// tick. With an unbounded key space (e.g. keyed on distinct_id) the+ /// one-shot keys dominate, so this floor is what keeps the pipeline sized to+ /// the keys that can actually be enforced rather than to total traffic.+ ///+ /// The level is per-node, so the ceiling on a safe value is+ /// `global_threshold / node_count` -- above that, a key sitting exactly at+ /// the threshold but spread evenly across the fleet would never sync and so+ /// could never be limited. Keep well under that: the saving is dominated by+ /// the single-event keys, so a small floor captures nearly all of it.+ ///+ /// Set to 0 to sync every key, restoring the pre-floor behavior.+ pub min_sync_floor: u64,+ /// Maximum keys drained from `pending_sync` per tick. The remainder stays+ /// queued for the next tick, so a backlog degrades into staleness instead of+ /// a tick loop that overruns its own interval.+ pub max_sync_keys_per_tick: usize,+ /// Maximum Redis keys per individual command. Reads cost two keys per entity+ /// (current + previous epoch), so an entity chunk is half this. Bounds how+ /// long any single command can take, which is what the per-command timeout+ /// is actually budgeting for.+ pub max_keys_per_command: usize,+ /// How many chunked commands may be in flight at once against one instance.+ /// Trades tick wall-clock against instantaneous Redis load.+ pub max_concurrent_commands: usize,+ /// Maximum distinct (key, epoch) entries held in the deferred write batch.+ /// Merges into existing entries are always accepted (they add no memory);+ /// at the cap, updates for new keys are dropped and counted. Without this,+ /// unique-key inflow faster than the per-tick drain grows the batch without+ /// bound -- the update channel's capacity does not help, because the+ /// receiver moves entries into this map as fast as they arrive.+ pub max_write_batch_entries: usize,+ /// Maximum keys held in the pending-sync set. At the cap, new sync+ /// requests are dropped and counted; the key's next request re-queues it+ /// once the backlog drains. Mirrors `max_write_batch_entries`: without a+ /// cap, keys clearing the sync floor faster than the per-tick drain grow+ /// the set without bound.+ pub max_pending_sync_entries: usize,/// Per-key custom limits. Overrides the default limit for specific *more granular* keys.////// Wrapped in `Arc<ArcSwap<_>>` so the map can be atomically replaced at@@ -245,10 +294,16 @@ impl Default for GlobalRateLimiterConfig {local_cache_ttl: Duration::from_secs(600),local_cache_idle_timeout: Duration::from_secs(300),global_cache_ttl: window_interval.mul_f64(2.0),- global_read_timeout: Duration::from_millis(100),- global_write_timeout: Duration::from_millis(100),+ global_read_timeout: Duration::from_millis(250),+ global_write_timeout: Duration::from_millis(250),local_cache_max_entries: 300_000,channel_capacity: 1_000_000,+ min_sync_floor: 10,+ max_sync_keys_per_tick: 20_000,+ max_keys_per_command: 2_000,+ max_concurrent_commands: 4,+ max_write_batch_entries: 200_000,+ max_pending_sync_entries: 200_000,custom_keys: Arc::new(ArcSwap::from_pointee(HashMap::new())),custom_key_resolver: None,custom_key_source: None,@@ -460,6 +515,36 @@ impl GlobalRateLimiterImpl {let scope: &'static str = Box::leak(config.metrics_scope.clone().into_boxed_str());+ // An idle timeout shorter than the window would expire entries inside the+ // very window they are accumulating counts for, silently under-enforcing.+ // Clamp rather than error: this is deploy-time config, and taking capture+ // down over a tuning value is worse than running with a corrected one.+ let mut config = config;+ if config.local_cache_idle_timeout < config.window_interval {+ warn!(+ scope,+ idle_timeout = ?config.local_cache_idle_timeout,+ window_interval = ?config.window_interval,+ "local_cache_idle_timeout below window_interval would drop counts \+ inside the enforcement window; clamping to window_interval"+ );+ config.local_cache_idle_timeout = config.window_interval;+ }+ // Same hazard for the hard TTL: an entry evicted mid-window discards the+ // counts it was accumulating, and the next request follows the always-+ // allowed miss path.+ if config.local_cache_ttl < config.window_interval {+ warn!(+ scope,+ ttl = ?config.local_cache_ttl,+ window_interval = ?config.window_interval,+ "local_cache_ttl below window_interval would drop counts inside \+ the enforcement window; clamping to window_interval"+ );+ config.local_cache_ttl = config.window_interval;+ }+ let config = config;+let cache = Cache::builder().max_capacity(config.local_cache_max_entries).time_to_live(config.local_cache_ttl)@@ -553,24 +638,25 @@ impl GlobalRateLimiterImpl {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);- // Check if sync is needed based on pressure tier- let current_pressure = level / threshold as f64;- let effective_pressure = current_pressure.max(entry.pressure);- if let Some(tier_interval) =- tier_sync_interval(effective_pressure, self.config.sync_interval)- {- if now_instant.duration_since(entry.synced_at) > tier_interval {- self.pending_sync.insert(key.to_string());- metrics::counter!(GLOBAL_RATE_LIMITER_CACHE_COUNTER, "scope" => self.scope, "result" => "sync_queued")- .increment(1);- } else {- metrics::counter!(GLOBAL_RATE_LIMITER_CACHE_COUNTER, "scope" => self.scope, "result" => "hit")- .increment(1);- }+ // Sync decision. The absolute floor is checked first: a key this far+ // under its threshold cannot be limited whatever the other nodes+ // report, so the round trip buys nothing and the key space is large+ // enough that those round trips are the dominant cost. Above the+ // floor the pressure tier sets the cadence, and a key that clears the+ // floor while still idle-tier syncs on the Low cadence rather than+ // never -- otherwise a key that is hot across the fleet but cold on+ // any single node would never be discovered.+ if self.sync_floor_blocks(level, threshold) {+ metrics::counter!(GLOBAL_RATE_LIMITER_CACHE_COUNTER, "scope" => self.scope, "result" => "hit")+ .increment(1);} else {- // Idle tier: only queue sync if local traffic has pushed us above idle threshold- if current_pressure >= 0.1 {- self.pending_sync.insert(key.to_string());+ let effective_pressure = (level / threshold as f64).max(entry.pressure);+ let tier_interval =+ 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 {+ self.queue_sync(key);metrics::counter!(GLOBAL_RATE_LIMITER_CACHE_COUNTER, "scope" => self.scope, "result" => "sync_queued").increment(1);} else {@@ -597,7 +683,9 @@ impl GlobalRateLimiterImpl {pressure: 0.0,};self.cache.insert(key.to_string(), entry);- self.pending_sync.insert(key.to_string());+ if !self.sync_floor_blocks(count as f64, threshold) {+ self.queue_sync(key);+ }(count as f64, false)};@@ -622,6 +710,56 @@ impl GlobalRateLimiterImpl {}}+ /// True when `level` sits below the sync floor for this key's threshold,+ /// meaning a Redis round trip cannot change any enforcement decision.+ /// Records the skip so the saving is visible next to `cache_counts_total`.+ ///+ /// The configured floor is capped at 1% of the key's own threshold. The+ /// floor is a per-node level, so a fleet of N nodes can hide at most+ /// N * floor events from Redis; the cap keeps that bypass under N% of the+ /// threshold regardless of configuration. Without it, a custom threshold+ /// far below the global one (the exact keys overrides exist to clamp) could+ /// sit entirely below a floor tuned for the global threshold and never+ /// sync, making the override unenforceable.+ ///+ /// A configured floor of 0 disables the check entirely.+ fn sync_floor_blocks(&self, level: f64, threshold: u64) -> bool {+ if self.config.min_sync_floor == 0 {+ return false;+ }+ let effective_floor = self.config.min_sync_floor.min((threshold / 100).max(1));+ if level >= effective_floor as f64 {+ return false;+ }+ metrics::counter!(+ GLOBAL_RATE_LIMITER_SYNC_SKIPPED_COUNTER,+ "scope" => self.scope,+ "reason" => "below_floor",+ )+ .increment(1);+ true+ }++ /// Queue a key for background Redis sync, bounded by+ /// `max_pending_sync_entries`. A dropped request fails open for one round:+ /// the key's next request re-queues it once the backlog drains, and its+ /// counts keep flowing to Redis regardless -- only the read is delayed.+ fn queue_sync(&self, key: &str) {+ if self.pending_sync.len() >= self.config.max_pending_sync_entries+ && !self.pending_sync.contains(key)+ {+ metrics::counter!(+ GLOBAL_RATE_LIMITER_ERROR_COUNTER,+ "scope" => self.scope,+ "step" => "queue_sync",+ "cause" => "pending_sync_full",+ )+ .increment(1);+ return;+ }+ self.pending_sync.insert(key.to_string());+ }+/// Queue an update to be batched and sent to Redisfn enqueue_update(&self, key: &str, count: u64, timestamp: DateTime<Utc>) {let update = UpdateRequest {@@ -752,7 +890,14 @@ impl GlobalRateLimiterImpl {match result {Some(req) => {let epoch = epoch_from_timestamp(req.timestamp, config.window_interval);- *write_batch.entry((req.key, epoch)).or_insert(0) += req.count;+ Self::absorb_update(+ &mut write_batch,+ req.key,+ epoch,+ req.count,+ config.max_write_batch_entries,+ scope,+ );}None => {// Channel closed, do final flush and exit@@ -778,6 +923,43 @@ impl GlobalRateLimiterImpl {});}+ /// Merge one update into the deferred write batch, enforcing the entry cap.+ ///+ /// Merges never grow the map, so they are always accepted; only a brand-new+ /// (key, epoch) entry can be refused. A refused update undercounts the+ /// global tally for that key -- under-enforcement, consistent with every+ /// other overload path here failing open -- and is counted so the loss is+ /// visible. No log line: at the inflow rates that reach the cap, per-drop+ /// logging would itself be a problem.+ fn absorb_update(+ write_batch: &mut HashMap<(String, i64), u64>,+ key: String,+ epoch: i64,+ count: u64,+ max_entries: usize,+ scope: &'static str,+ ) {+ let at_cap = write_batch.len() >= max_entries;+ match write_batch.entry((key, epoch)) {+ std::collections::hash_map::Entry::Occupied(mut entry) => {+ *entry.get_mut() += count;+ }+ std::collections::hash_map::Entry::Vacant(slot) => {+ if at_cap {+ metrics::counter!(+ GLOBAL_RATE_LIMITER_ERROR_COUNTER,+ "scope" => scope,+ "step" => "enqueue_update",+ "cause" => "write_batch_full",+ )+ .increment(1);+ } else {+ slot.insert(count);+ }+ }+ }+ }+/// Execute one tick of the background pipeline.////// Drains pending reads + writes, builds a single pipeline, executes it,@@ -797,12 +979,61 @@ impl GlobalRateLimiterImpl {// throttled full scan (slow-moving, see TIER_SCAN_INTERVAL_TICKS).Self::emit_cache_gauges(cache, scope, tick_n);- // Drain pending sync set (lock-free: iterate then clear)- let sync_keys: Vec<String> = pending_sync.iter().map(|r| r.key().clone()).collect();- pending_sync.clear();+ // 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+ // of a tick that overruns its own interval and starves every other key.+ // `collect` drops the iterator before the removals, which keeps us off+ // dashmap's held-shard-lock path.+ let sync_keys: Vec<String> = pending_sync+ .iter()+ .take(config.max_sync_keys_per_tick)+ .map(|r| r.key().clone())+ .collect();+ for key in &sync_keys {+ pending_sync.remove(key);+ }+ metrics::gauge!(GLOBAL_RATE_LIMITER_SYNC_DEFERRED_GAUGE, "scope" => scope)+ .set(pending_sync.len() as f64);++ // Deferred entries whose epoch has aged out of the readable window can+ // no longer affect any decision: reads consult only the current and+ // previous epochs. Purge them instead of spending write commands (and+ // deferral slots) on counts nothing will ever read.+ let min_live_epoch = epoch_from_timestamp(Utc::now(), config.window_interval) - 1;+ let before_purge = write_batch.len();+ write_batch.retain(|(_, epoch), _| *epoch >= min_live_epoch);+ let purged = before_purge - write_batch.len();+ if purged > 0 {+ metrics::counter!(+ GLOBAL_RATE_LIMITER_ERROR_COUNTER,+ "scope" => scope,+ "step" => "pipeline",+ "cause" => "stale_epoch_purged",+ )+ .increment(purged as u64);+ }- // Take ownership of write batch- let writes = std::mem::take(write_batch);+ // Bound the write drain the same way. The deferred remainder stays in+ // `write_batch`, where new arrivals merge into it by (key, epoch), so no+ // count is lost -- it lands in the same epoch key up to a few ticks late.+ // Without the bound, a high-cardinality burst produces a write batch+ // whose waves consume the whole tick before reads run.+ let writes: HashMap<(String, i64), u64> =+ if write_batch.len() <= config.max_sync_keys_per_tick {+ std::mem::take(write_batch)+ } else {+ let drain_keys: Vec<(String, i64)> = write_batch+ .keys()+ .take(config.max_sync_keys_per_tick)+ .cloned()+ .collect();+ drain_keys+ .into_iter()+ .filter_map(|k| write_batch.remove_entry(&k))+ .collect()+ };+ metrics::gauge!(GLOBAL_RATE_LIMITER_WRITE_DEFERRED_GAUGE, "scope" => scope)+ .set(write_batch.len() as f64);let read_count = sync_keys.len();let write_count = writes.len();@@ -851,131 +1082,206 @@ impl GlobalRateLimiterImpl {writes: &HashMap<(String, i64), u64>,scope: &'static str,) {- let redis_idx_str = redis_idx.to_string();+ let redis_idx_str: Arc<str> = Arc::from(redis_idx.to_string().as_str());let now = Utc::now();let ttl = config.global_cache_ttl.as_secs() as usize;- // --- WRITES ---- if !writes.is_empty() {- let write_items: Vec<(String, i64)> = writes- .iter()- .map(|((key, epoch), count)| {- let redis_key = epoch_key(&config.redis_key_prefix, key, *epoch);- (redis_key, *count as i64)- })- .collect();-- let write_count = write_items.len();- let pipeline_start = Instant::now();-- match tokio::time::timeout(- config.global_write_timeout,- redis.batch_incr_by_expire(write_items, ttl),- )- .await- {- Ok(Ok(_)) => {- metrics::counter!(- GLOBAL_RATE_LIMITER_RECORDS_COUNTER,- "scope" => scope,- "op" => "redis_write",- "redis_idx" => redis_idx_str.clone(),- )- .increment(write_count as u64);- metrics::histogram!(- GLOBAL_RATE_LIMITER_PIPELINE_HISTOGRAM,- "scope" => scope,- "redis_idx" => redis_idx_str.clone(),- )- .record(pipeline_start.elapsed().as_micros() as f64 / 1000.0);- }- Ok(Err(e)) => {- metrics::counter!(- GLOBAL_RATE_LIMITER_ERROR_COUNTER,- "scope" => scope,- "step" => "pipeline",- "cause" => "redis_write",- "redis_idx" => redis_idx_str.clone(),- )- .increment(1);- warn!(error = %e, records = write_count, redis_idx = redis_idx, "Failed to write rate limit batch to Redis");- }- Err(_) => {- metrics::counter!(- GLOBAL_RATE_LIMITER_ERROR_COUNTER,- "scope" => scope,- "step" => "pipeline",- "cause" => "timeout",- "redis_idx" => redis_idx_str.clone(),+ // Writes first, then reads. A read result zeroes each synced key's+ // `local_pending`, so the read must already include this tick's write+ // batch -- reads-first would discard up to a tick of a key's counts+ // until its next sync. Writes-first is safe to wait on now that the+ // write batch is bounded and chunked: the read delay is capped at a few+ // command timeouts, where the old unbounded batch could consume whole+ // ticks. Counts deferred past the write cap are still cleared by the+ // read before they land; that loss is bounded by the cap and fails+ // open, like every other overload path here.+ let writes_issued =+ Self::run_writes(config, redis, &redis_idx_str, writes, ttl, scope).await;+ let reads_issued =+ Self::run_reads(config, redis, &redis_idx_str, cache, sync_keys, now, scope).await;++ metrics::histogram!(GLOBAL_RATE_LIMITER_COMMANDS_HISTOGRAM, "scope" => scope, "op" => "write")+ .record(writes_issued as f64);+ metrics::histogram!(GLOBAL_RATE_LIMITER_COMMANDS_HISTOGRAM, "scope" => scope, "op" => "read")+ .record(reads_issued as f64);+ }++ /// Issue the write half of a tick as size-bounded, concurrently-executed+ /// commands. Returns how many commands were issued.+ ///+ /// One oversized command is the failure mode this exists to prevent: the+ /// per-command timeout can only be a meaningful budget if the command's size+ /// is bounded, otherwise a growing key space silently converts a working+ /// timeout into a guaranteed one.+ async fn run_writes(+ config: &GlobalRateLimiterConfig,+ redis: &Arc<dyn Client + Send + Sync>,+ redis_idx_str: &Arc<str>,+ writes: &HashMap<(String, i64), u64>,+ ttl: usize,+ scope: &'static str,+ ) -> usize {+ if writes.is_empty() {+ return 0;+ }++ let write_items: Vec<(String, i64)> = writes+ .iter()+ .map(|((key, epoch), count)| {+ let redis_key = epoch_key(&config.redis_key_prefix, key, *epoch);+ (redis_key, *count as i64)+ })+ .collect();++ let chunks: Vec<Vec<(String, i64)>> = write_items+ .chunks(config.max_keys_per_command.max(1))+ .map(|chunk| chunk.to_vec())+ .collect();+ let issued = chunks.len();++ // Waves of `max_concurrent_commands` rather than a `buffer_unordered`+ // stream: the stream combinator forces a higher-ranked `Send` bound the+ // spawned tick task cannot satisfy, and this keeps the same bound on+ // in-flight commands.+ for wave in chunks.chunks(config.max_concurrent_commands.max(1)) {+ let futures = wave.iter().map(|chunk| {+ let redis_idx_str = redis_idx_str.clone();+ async move {+ let chunk_len = chunk.len();+ let started = Instant::now();+ match tokio::time::timeout(+ config.global_write_timeout,+ redis.batch_incr_by_expire(chunk.clone(), ttl),)- .increment(1);- warn!(- records = write_count,- redis_idx = redis_idx,- "Redis write timeout in pipeline"- );+ .await+ {+ Ok(Ok(_)) => {+ metrics::counter!(+ GLOBAL_RATE_LIMITER_RECORDS_COUNTER,+ "scope" => scope,+ "op" => "redis_write",+ "redis_idx" => redis_idx_str.clone(),+ )+ .increment(chunk_len as u64);+ metrics::histogram!(+ GLOBAL_RATE_LIMITER_PIPELINE_HISTOGRAM,+ "scope" => scope,+ "redis_idx" => redis_idx_str.clone(),+ )+ .record(started.elapsed().as_micros() as f64 / 1000.0);+ }+ Ok(Err(e)) => {+ Self::record_pipeline_error(scope, &redis_idx_str, "redis_write");+ warn!(error = %e, records = chunk_len, "Failed to write rate limit batch to Redis");+ // A dead MultiplexedConnection never recovers on its+ // own; ask the client to rebuild. Timeouts are+ // transient and never route here.+ if e.is_unrecoverable_error() {+ redis.heal().await;+ }+ }+ Err(_) => {+ Self::record_pipeline_error(scope, &redis_idx_str, "write_timeout");+ warn!(records = chunk_len, "Redis write timeout in pipeline");+ }+ }}- }+ });+ futures::future::join_all(futures).await;}- // --- READS ---- if !sync_keys.is_empty() {- // Build MGET key list: for each entity, we need current + prev epoch key- let mut mget_keys: Vec<String> = Vec::with_capacity(sync_keys.len() * 2);- for key in sync_keys {- let (curr, prev) =- epoch_keys(&config.redis_key_prefix, key, now, config.window_interval);- mget_keys.push(curr);- mget_keys.push(prev);- }+ issued+ }- let pipeline_start = Instant::now();- match tokio::time::timeout(config.global_read_timeout, redis.mget(mget_keys)).await {- Ok(Ok(results)) => {- metrics::counter!(- GLOBAL_RATE_LIMITER_RECORDS_COUNTER,- "scope" => scope,- "op" => "redis_read",- "redis_idx" => redis_idx_str.clone(),- )- .increment(results.len() as u64);- metrics::histogram!(- GLOBAL_RATE_LIMITER_PIPELINE_HISTOGRAM,- "scope" => scope,- "redis_idx" => redis_idx_str.clone(),- )- .record(pipeline_start.elapsed().as_micros() as f64 / 1000.0);+ /// Issue the read half of a tick as size-bounded, concurrently-executed+ /// commands, applying each chunk's results as it lands. Returns how many+ /// commands were issued.+ #[allow(clippy::too_many_arguments)]+ async fn run_reads(+ config: &GlobalRateLimiterConfig,+ redis: &Arc<dyn Client + Send + Sync>,+ redis_idx_str: &Arc<str>,+ cache: &Cache<String, CacheEntry>,+ sync_keys: &[String],+ now: DateTime<Utc>,+ scope: &'static str,+ ) -> usize {+ if sync_keys.is_empty() {+ return 0;+ }- Self::process_read_results(config, cache, sync_keys, &results, now, scope);- }- Ok(Err(e)) => {- metrics::counter!(- GLOBAL_RATE_LIMITER_ERROR_COUNTER,- "scope" => scope,- "step" => "pipeline",- "cause" => "redis_error",- "redis_idx" => redis_idx_str.clone(),- )- .increment(1);- warn!(keys = sync_keys.len(), redis_idx = redis_idx, error = %e, "Failed to read rate limits from Redis");- }- Err(_) => {- metrics::counter!(- GLOBAL_RATE_LIMITER_ERROR_COUNTER,- "scope" => scope,- "step" => "pipeline",- "cause" => "timeout",- "redis_idx" => redis_idx_str.clone(),- )- .increment(1);- warn!(- keys = sync_keys.len(),- redis_idx = redis_idx,- "Redis read timeout in pipeline"- );+ // Each entity costs two Redis keys (current + previous epoch), so the+ // entity chunk is half the per-command key budget.+ let entities_per_chunk = (config.max_keys_per_command / 2).max(1);+ let chunks: Vec<&[String]> = sync_keys.chunks(entities_per_chunk).collect();+ let issued = chunks.len();++ // See `run_writes` for why this is waves of `join_all` rather than a+ // `buffer_unordered` stream.+ for wave in chunks.chunks(config.max_concurrent_commands.max(1)) {+ let futures = wave.iter().map(|chunk| {+ let redis_idx_str = redis_idx_str.clone();+ async move {+ let mut mget_keys: Vec<String> = Vec::with_capacity(chunk.len() * 2);+ for key in chunk.iter() {+ let (curr, prev) =+ epoch_keys(&config.redis_key_prefix, key, now, config.window_interval);+ mget_keys.push(curr);+ mget_keys.push(prev);+ }++ let started = Instant::now();+ match tokio::time::timeout(config.global_read_timeout, redis.mget(mget_keys))+ .await+ {+ Ok(Ok(results)) => {+ metrics::counter!(+ GLOBAL_RATE_LIMITER_RECORDS_COUNTER,+ "scope" => scope,+ "op" => "redis_read",+ "redis_idx" => redis_idx_str.clone(),+ )+ .increment(results.len() as u64);+ metrics::histogram!(+ GLOBAL_RATE_LIMITER_PIPELINE_HISTOGRAM,+ "scope" => scope,+ "redis_idx" => redis_idx_str.clone(),+ )+ .record(started.elapsed().as_micros() as f64 / 1000.0);++ Self::process_read_results(config, cache, chunk, &results, now, scope);+ }+ Ok(Err(e)) => {+ Self::record_pipeline_error(scope, &redis_idx_str, "redis_error");+ warn!(keys = chunk.len(), error = %e, "Failed to read rate limits from Redis");+ if e.is_unrecoverable_error() {+ redis.heal().await;+ }+ }+ Err(_) => {+ Self::record_pipeline_error(scope, &redis_idx_str, "read_timeout");+ warn!(keys = chunk.len(), "Redis read timeout in pipeline");+ }+ }}- }+ });+ futures::future::join_all(futures).await;}++ issued+ }++ /// Record a pipeline-step failure. `cause` distinguishes read from write so+ /// a saturating side is identifiable from the metric alone.+ fn record_pipeline_error(scope: &'static str, redis_idx_str: &Arc<str>, cause: &'static str) {+ metrics::counter!(+ GLOBAL_RATE_LIMITER_ERROR_COUNTER,+ "scope" => scope,+ "step" => "pipeline",+ "cause" => cause,+ "redis_idx" => redis_idx_str.clone(),+ )+ .increment(1);}/// Execute a tick partitioned across multiple Redis instances.@@ -1177,6 +1483,15 @@ mod tests {global_read_timeout: Duration::from_millis(5),global_write_timeout: Duration::from_millis(10),metrics_scope: "test".to_string(),+ // Tests drive a threshold of 10, so a production-sized floor would+ // suppress every sync. 0 keeps the pre-floor behavior; the floor's+ // own behavior is covered by the dedicated tests below.+ min_sync_floor: 0,+ max_sync_keys_per_tick: 20_000,+ max_keys_per_command: 2_000,+ max_concurrent_commands: 4,+ max_write_batch_entries: 200_000,+ max_pending_sync_entries: 200_000,}}@@ -1345,10 +1660,16 @@ mod tests {assert_eq!(config.global_cache_ttl, Duration::from_secs(120));assert_eq!(config.local_cache_ttl, Duration::from_secs(600));assert_eq!(config.local_cache_idle_timeout, Duration::from_secs(300));- assert_eq!(config.global_read_timeout, Duration::from_millis(100));- assert_eq!(config.global_write_timeout, Duration::from_millis(100));+ assert_eq!(config.global_read_timeout, Duration::from_millis(250));+ assert_eq!(config.global_write_timeout, Duration::from_millis(250));assert_eq!(config.local_cache_max_entries, 300_000);assert_eq!(config.channel_capacity, 1_000_000);+ assert_eq!(config.min_sync_floor, 10);+ assert_eq!(config.max_sync_keys_per_tick, 20_000);+ assert_eq!(config.max_keys_per_command, 2_000);+ assert_eq!(config.max_concurrent_commands, 4);+ assert_eq!(config.max_write_batch_entries, 200_000);+ assert_eq!(config.max_pending_sync_entries, 200_000);assert!(config.custom_keys.load().is_empty());assert!(config.custom_key_resolver.is_none());assert_eq!(config.metrics_scope, "default");@@ -1724,6 +2045,365 @@ mod tests {);}+ /// `test_config` with the sync floor set and the background drain parked, so+ /// `pending_sync` assertions observe only what `check_limit` queued.+ fn config_with_floor(floor: u64) -> GlobalRateLimiterConfig {+ GlobalRateLimiterConfig {+ min_sync_floor: floor,+ tick_interval: Duration::from_secs(3600),+ ..test_config()+ }+ }++ #[tokio::test]+ async fn test_min_sync_floor_gates_cold_miss_sync() {+ // (floor, count, expect_queued)+ let cases = vec![+ (0, 1, true), // floor disabled: every miss syncs (pre-floor behavior)+ (5, 1, false), // below floor: no round trip for a key that cannot be limited+ (5, 5, true), // exactly at the floor+ (5, 9, true), // above the floor+ ];++ for (floor, count, expect_queued) in cases {+ let client = Arc::new(MockRedisClient::new());+ // Threshold large enough (floor * 100 or more) that the 1% cap does+ // not reduce the configured floor; the cap has its own test below.+ let config = GlobalRateLimiterConfig {+ global_threshold: 1000,+ ..config_with_floor(floor)+ };+ let limiter = GlobalRateLimiterImpl::new(config, vec![client]).unwrap();+ let key = format!("cold_{floor}_{count}");++ limiter.check_limit(&key, count, None).await;++ assert_eq!(+ limiter.pending_sync.contains(&key),+ expect_queued,+ "floor={floor} count={count} should queue sync = {expect_queued}"+ );+ }+ }++ #[tokio::test]+ async fn test_idle_timeout_clamped_up_to_window_interval() {+ // (idle_timeout_secs, expected_secs)+ let cases = vec![+ (10, 60), // below the 60s window: clamped up+ (59, 60), // just below: clamped up+ (60, 60), // exactly at the window: untouched+ (300, 300), // above: untouched+ ];++ for (idle_secs, expected_secs) in cases {+ let client = Arc::new(MockRedisClient::new());+ let config = GlobalRateLimiterConfig {+ local_cache_idle_timeout: Duration::from_secs(idle_secs),+ ..test_config()+ };+ let limiter = GlobalRateLimiterImpl::new(config, vec![client]).unwrap();++ assert_eq!(+ limiter.config.local_cache_idle_timeout,+ Duration::from_secs(expected_secs),+ "idle_timeout={idle_secs}s against a 60s window should resolve to {expected_secs}s -- \+ an idle timeout inside the window expires entries mid-window and silently under-enforces"+ );+ }+ }++ #[tokio::test]+ async fn test_sync_floor_capped_at_one_percent_of_threshold() {+ // (configured_floor, threshold, count, expect_queued)+ let cases = vec![+ // Custom-style low threshold: cap = max(1, 100/100) = 1, so any+ // counted event syncs. A floor tuned for the global threshold must+ // not make a low custom override unenforceable.+ (10, 100, 1, true),+ // Threshold 500: cap = 5. The configured 10 is reduced to 5.+ (10, 500, 4, false),+ (10, 500, 5, true),+ // Large threshold: cap = 150 leaves the configured 10 in charge.+ (10, 15_000, 9, false),+ (10, 15_000, 10, true),+ ];++ for (floor, threshold, count, expect_queued) in cases {+ let client = Arc::new(MockRedisClient::new());+ let config = GlobalRateLimiterConfig {+ global_threshold: threshold,+ ..config_with_floor(floor)+ };+ let limiter = GlobalRateLimiterImpl::new(config, vec![client]).unwrap();+ let key = format!("cap_{floor}_{threshold}_{count}");++ limiter.check_limit(&key, count, None).await;++ assert_eq!(+ limiter.pending_sync.contains(&key),+ expect_queued,+ "floor={floor} threshold={threshold} count={count} should queue sync = {expect_queued}"+ );+ }+ }++ #[tokio::test]+ async fn test_ttl_clamped_up_to_window_interval() {+ let client = Arc::new(MockRedisClient::new());+ let config = GlobalRateLimiterConfig {+ local_cache_ttl: Duration::from_secs(1),+ ..test_config() // 60s window+ };+ let limiter = GlobalRateLimiterImpl::new(config, vec![client]).unwrap();++ assert_eq!(+ limiter.config.local_cache_ttl,+ Duration::from_secs(60),+ "a TTL below the window evicts entries mid-window; the next request \+ takes the always-allowed miss path and the limiter under-enforces"+ );+ }++ #[tokio::test]+ async fn test_tick_runs_writes_before_reads() {+ let mock = Arc::new(MockRedisClient::new());+ let client: Arc<dyn Client + Send + Sync> = mock.clone();+ let config = config_with_floor(0);+ let cache: Cache<String, CacheEntry> = Cache::builder().max_capacity(100).build();+ let pending: Arc<DashSet<String>> = Arc::new(DashSet::new());+ pending.insert("read_key".to_string());+ let mut writes: HashMap<(String, i64), u64> = HashMap::new();+ // Current epoch: a stale epoch would be purged before the write runs.+ let epoch = epoch_from_timestamp(Utc::now(), config.window_interval);+ writes.insert(("write_key".to_string(), epoch), 5);++ GlobalRateLimiterImpl::tick(+ &config,+ std::slice::from_ref(&client),+ &cache,+ &pending,+ &mut writes,+ "test",+ 1,+ )+ .await;++ let calls = mock.get_calls();+ let first_read = calls.iter().position(|c| c.op == "mget");+ let first_write = calls.iter().position(|c| c.op.starts_with("batch_incr"));+ assert!(+ first_read.is_some() && first_write.is_some(),+ "tick should issue both a read and a write"+ );+ assert!(+ first_write < first_read,+ "writes must land before reads: the read result zeroes each synced \+ key's local_pending, so a read that predates this tick's writes \+ silently discards those counts until the next sync. calls={calls:?}"+ );+ }++ #[tokio::test]+ async fn test_pending_sync_cap_drops_new_keys() {+ // Keys clearing the sync floor faster than the per-tick drain must not+ // grow pending_sync without bound; at the cap, new sync requests drop+ // (the key re-queues on its next request) while known keys stay queued.+ let client = Arc::new(MockRedisClient::new());+ let config = GlobalRateLimiterConfig {+ max_pending_sync_entries: 2,+ ..config_with_floor(0)+ };+ let limiter = GlobalRateLimiterImpl::new(config, vec![client]).unwrap();++ for key in ["a", "b", "c", "d"] {+ limiter.check_limit(key, 1, None).await;+ }++ assert_eq!(+ limiter.pending_sync.len(),+ 2,+ "pending_sync must stop growing at max_pending_sync_entries"+ );+ }++ #[tokio::test]+ async fn test_write_batch_cap_drops_new_keys_but_merges_existing() {+ // At the cap, an update for a brand-new key is dropped (bounded memory+ // beats an unbounded map under unique-key floods), while an update for+ // a key already in the batch still merges -- merging costs no memory+ // and dropping it would silently undercount a key we are tracking.+ let mut batch: HashMap<(String, i64), u64> = HashMap::new();+ batch.insert(("k1".to_string(), 1), 5);+ batch.insert(("k2".to_string(), 1), 5);++ GlobalRateLimiterImpl::absorb_update(&mut batch, "k3".to_string(), 1, 7, 2, "test");+ assert_eq!(batch.len(), 2, "new key at cap must be dropped");+ assert!(!batch.contains_key(&("k3".to_string(), 1)));++ GlobalRateLimiterImpl::absorb_update(&mut batch, "k1".to_string(), 1, 7, 2, "test");+ assert_eq!(+ batch.get(&("k1".to_string(), 1)),+ Some(&12),+ "existing key at cap must still merge"+ );+ }++ #[tokio::test]+ async fn test_tick_purges_stale_epochs_instead_of_writing_them() {+ let mock = Arc::new(MockRedisClient::new());+ let client: Arc<dyn Client + Send + Sync> = mock.clone();+ let config = config_with_floor(0); // 60s window+ let cache: Cache<String, CacheEntry> = Cache::builder().max_capacity(100).build();+ let pending: Arc<DashSet<String>> = Arc::new(DashSet::new());++ let current_epoch = epoch_from_timestamp(Utc::now(), config.window_interval);+ let mut writes: HashMap<(String, i64), u64> = HashMap::new();+ writes.insert(("live".to_string(), current_epoch), 1);+ writes.insert(("stale".to_string(), current_epoch - 5), 1);++ GlobalRateLimiterImpl::tick(+ &config,+ std::slice::from_ref(&client),+ &cache,+ &pending,+ &mut writes,+ "test",+ 1,+ )+ .await;++ let write_calls: Vec<String> = mock+ .get_calls()+ .into_iter()+ .filter(|c| c.op == "batch_incr_by_expire")+ .map(|c| c.key)+ .collect();+ assert_eq!(+ write_calls,+ vec![format!("items=1;ttl={}", config.global_cache_ttl.as_secs())],+ "only the readable-epoch entry may be written; a stale epoch can never be read (reads consult current + previous only) and must not spend write commands"+ );+ assert!(+ writes.is_empty(),+ "stale entry must be purged, not deferred"+ );+ }++ #[tokio::test]+ async fn test_tick_bounds_write_drain_and_carries_remainder() {+ let client: Arc<dyn Client + Send + Sync> = Arc::new(MockRedisClient::new());+ let config = GlobalRateLimiterConfig {+ max_sync_keys_per_tick: 10,+ ..config_with_floor(0)+ };+ let cache: Cache<String, CacheEntry> = Cache::builder().max_capacity(100).build();+ let pending: Arc<DashSet<String>> = Arc::new(DashSet::new());+ let mut writes: HashMap<(String, i64), u64> = HashMap::new();+ let epoch = epoch_from_timestamp(Utc::now(), config.window_interval);+ for i in 0..25 {+ writes.insert((format!("w{i}"), epoch), 1);+ }++ GlobalRateLimiterImpl::tick(+ &config,+ std::slice::from_ref(&client),+ &cache,+ &pending,+ &mut writes,+ "test",+ 1,+ )+ .await;++ assert_eq!(+ writes.len(),+ 15,+ "tick must drain at most max_sync_keys_per_tick write entries and \+ leave the remainder batched -- deferring keeps counts (they merge by \+ key+epoch and land a tick late), dropping them would lose counts"+ );+ }++ #[tokio::test]+ async fn test_idle_tier_key_above_floor_still_syncs() {+ let client = Arc::new(MockRedisClient::new());+ let config = GlobalRateLimiterConfig {+ global_threshold: 1000,+ ..config_with_floor(10)+ };+ let limiter = GlobalRateLimiterImpl::new(config, vec![client]).unwrap();++ // Locally accumulated events don't decay, so this entry sits at level 50:+ // idle by pressure (0.05 < 0.1) but well above the absolute floor, and+ // last synced longer ago than the Low cadence (4 * 15s).+ limiter.cache.insert(+ "fleet_hot".to_string(),+ CacheEntry {+ estimated_count: 0.0,+ synced_at: Instant::now() - Duration::from_secs(120),+ local_pending: 50,+ pressure: 0.05,+ },+ );++ limiter.check_limit("fleet_hot", 1, None).await;++ assert!(+ limiter.pending_sync.contains("fleet_hot"),+ "an idle-tier key above the floor must still sync, else a key hot across \+ the fleet but cold on any single node is never discovered and never limited"+ );+ }++ #[tokio::test]+ async fn test_tick_bounds_drain_and_chunks_reads() {+ let mock = Arc::new(MockRedisClient::new());+ let client: Arc<dyn Client + Send + Sync> = mock.clone();+ let config = GlobalRateLimiterConfig {+ max_sync_keys_per_tick: 10,+ // 2 entities per read command (two epoch keys each).+ max_keys_per_command: 4,+ ..config_with_floor(0)+ };+ let cache: Cache<String, CacheEntry> = Cache::builder().max_capacity(1000).build();+ let pending: Arc<DashSet<String>> = Arc::new(DashSet::new());+ for i in 0..25 {+ pending.insert(format!("k{i}"));+ }+ let mut writes: HashMap<(String, i64), u64> = HashMap::new();++ GlobalRateLimiterImpl::tick(+ &config,+ std::slice::from_ref(&client),+ &cache,+ &pending,+ &mut writes,+ "test",+ 1,+ )+ .await;++ assert_eq!(+ pending.len(),+ 15,+ "tick must take at most max_sync_keys_per_tick and leave the remainder \+ queued -- deferring keeps the tick inside its interval, dropping them \+ would silently lose syncs"+ );++ let mget_calls = mock+ .get_calls()+ .into_iter()+ .filter(|c| c.op == "mget")+ .count();+ assert_eq!(+ mget_calls, 5,+ "10 drained keys at 2 entities per command must issue 5 bounded MGETs, \+ not one oversized command that cannot fit the per-command timeout"+ );+ }+#[tokio::test]async fn test_sync_dedup() {let client = Arc::new(MockRedisClient::new());diff --git a/rust/common/limiters/tests/global_rate_limiter_integration_tests.rs b/rust/common/limiters/tests/global_rate_limiter_integration_tests.rsindex 7149812a5069..38ba3047e3b7 100644--- a/rust/common/limiters/tests/global_rate_limiter_integration_tests.rs+++ b/rust/common/limiters/tests/global_rate_limiter_integration_tests.rs@@ -55,6 +55,14 @@ fn test_config(test_name: &str) -> GlobalRateLimiterConfig {global_read_timeout: Duration::from_millis(500),global_write_timeout: Duration::from_millis(500),metrics_scope: "integration_test".to_string(),+ // These tests assert exact Redis counter values against a threshold of+ // 1000, so every key must sync and every tick must drain fully.+ min_sync_floor: 0,+ max_sync_keys_per_tick: 10_000,+ max_keys_per_command: 2_000,+ max_concurrent_commands: 4,+ max_write_batch_entries: 200_000,+ max_pending_sync_entries: 200_000,}}diff --git a/rust/common/redis/Cargo.toml b/rust/common/redis/Cargo.tomlindex 1499ef6cd2fb..0312492ca7aa 100644--- a/rust/common/redis/Cargo.toml+++ b/rust/common/redis/Cargo.toml@@ -7,6 +7,8 @@ edition = "2021"workspace = true[dependencies]+arc-swap = { workspace = true }+tokio = { workspace = true }async-trait = { workspace = true }# `futures-timer` (not `tokio::time::sleep`) lets the mock module simulate# blocking pipeline calls without making `tokio` a runtime dependency of everydiff --git a/rust/common/redis/src/client.rs b/rust/common/redis/src/client.rsindex 7dbfcef3814b..6f7e4d5d74a5 100644--- a/rust/common/redis/src/client.rs+++ b/rust/common/redis/src/client.rs@@ -1,8 +1,11 @@+use std::sync::Arc;+use std::time::{Duration, Instant};++use arc_swap::ArcSwap;use async_trait::async_trait;use redis::aio::MultiplexedConnection;use redis::{AsyncCommands, RedisError};-use std::time::Duration;-use tracing::warn;+use tracing::{info, warn};use crate::pipeline::{PipelineCommand, PipelineResult};use crate::{Client, CompressionConfig, CustomRedisError, RedisValueFormat};@@ -14,11 +17,72 @@ const ERR_RAWBYTES_SET: &str =#[derive(Clone)]pub struct RedisClient {- connection: MultiplexedConnection,+ /// Shared across clones so a `heal()` on any handle repairs all of them.+ /// `MultiplexedConnection` does not reconnect after its TCP connection+ /// dies; `heal()` swaps in a rebuilt one.+ connection: Arc<ArcSwap<MultiplexedConnection>>,+ /// Connection info retained so `heal()` can rebuild.+ client: redis::Client,+ response_timeout: Option<Duration>,+ connection_timeout: Option<Duration>,+ /// Serializes heal attempts and carries the last-attempt time for the+ /// cooldown, so an error burst cannot stampede reconnects.+ heal_state: Arc<tokio::sync::Mutex<Instant>>,compression: CompressionConfig,format: RedisValueFormat,}+/// Minimum time between reconnect attempts (see `RedisClient::heal_connection`).+const HEAL_COOLDOWN: Duration = Duration::from_secs(5);++impl RedisClient {+ /// Current connection handle. Cheap: one atomic load plus a+ /// `MultiplexedConnection` clone (an mpsc sender clone).+ fn conn(&self) -> MultiplexedConnection {+ self.connection.load().as_ref().clone()+ }++ /// Rebuild the underlying connection after it has died.+ ///+ /// `MultiplexedConnection` never reconnects on its own: once its TCP+ /// connection drops (Redis failover, node replacement), every command+ /// errors forever. Callers that detect an unrecoverable error+ /// (`CustomRedisError::is_unrecoverable_error`) call this to swap in a+ /// fresh connection; all clones of this client share the swap. Attempts+ /// are serialized and rate-limited by `HEAL_COOLDOWN`, and a failed+ /// attempt just waits for the next caller -- the client keeps failing+ /// open in the meantime, exactly as it would without healing.+ pub async fn heal_connection(&self) {+ let mut last_attempt = self.heal_state.lock().await;+ if last_attempt.elapsed() < HEAL_COOLDOWN {+ return;+ }+ *last_attempt = Instant::now();++ let mut config = redis::AsyncConnectionConfig::new();+ if let Some(timeout) = self.response_timeout {+ config = config.set_response_timeout(timeout);+ }+ if let Some(timeout) = self.connection_timeout {+ config = config.set_connection_timeout(timeout);+ }++ match self+ .client+ .get_multiplexed_async_connection_with_config(&config)+ .await+ {+ Ok(connection) => {+ self.connection.store(Arc::new(connection));+ info!("Redis connection healed after unrecoverable error");+ }+ Err(e) => {+ warn!(error = %e, "Redis heal attempt failed; will retry after cooldown");+ }+ }+ }+}+impl RedisClient {/// Create a new RedisClient with default settings///@@ -147,7 +211,11 @@ impl RedisClient {.await?;Ok(RedisClient {- connection,+ connection: Arc::new(ArcSwap::from_pointee(connection)),+ client,+ response_timeout,+ connection_timeout,+ heal_state: Arc::new(tokio::sync::Mutex::new(Instant::now() - HEAL_COOLDOWN)),compression,format,})@@ -239,7 +307,7 @@ impl RedisClient {for arg in args {invocation.arg(arg);}- let mut conn = self.connection.clone();+ let mut conn = self.conn();let result: Vec<i64> = invocation.invoke_async(&mut conn).await?;Ok(result)}@@ -247,25 +315,29 @@ impl RedisClient {#[async_trait]impl Client for RedisClient {+ async fn heal(&self) {+ self.heal_connection().await;+ }+async fn zrangebyscore(&self,k: String,min: String,max: String,) -> Result<Vec<String>, CustomRedisError> {- let mut conn = self.connection.clone();+ let mut conn = self.conn();let results = conn.zrangebyscore(k, min, max).await?;Ok(results)}async fn zadd(&self, k: String, member: String, score: i64) -> Result<(), CustomRedisError> {- let mut conn = self.connection.clone();+ let mut conn = self.conn();conn.zadd::<_, _, _, ()>(k, member, score).await?;Ok(())}async fn hincrby(&self, k: String, v: String, count: i64) -> Result<(), CustomRedisError> {- let mut conn = self.connection.clone();+ let mut conn = self.conn();conn.hincr::<_, _, _, ()>(k, v, count).await?;Ok(())}@@ -279,7 +351,7 @@ impl Client for RedisClient {k: String,format: RedisValueFormat,) -> Result<String, CustomRedisError> {- let mut conn = self.connection.clone();+ let mut conn = self.conn();let raw_bytes: Vec<u8> = conn.get(k).await?;// return NotFound error when empty@@ -308,7 +380,7 @@ impl Client for RedisClient {}async fn get_raw_bytes(&self, k: String) -> Result<Vec<u8>, CustomRedisError> {- let mut conn = self.connection.clone();+ let mut conn = self.conn();let raw_bytes: Vec<u8> = conn.get(k).await?;// return NotFound error when empty@@ -327,7 +399,7 @@ impl Client for RedisClient {v: Vec<u8>,ttl_seconds: Option<u64>,) -> Result<(), CustomRedisError> {- let mut conn = self.connection.clone();+ let mut conn = self.conn();match ttl_seconds {Some(ttl) => conn.set_ex::<_, _, ()>(k, v, ttl).await?,None => conn.set::<_, _, ()>(k, v).await?,@@ -347,7 +419,7 @@ impl Client for RedisClient {) -> Result<(), CustomRedisError> {let final_bytes = self.serialize_and_compress(v, format)?;- let mut conn = self.connection.clone();+ let mut conn = self.conn();conn.set::<_, _, ()>(k, final_bytes).await?;Ok(())}@@ -365,7 +437,7 @@ impl Client for RedisClient {) -> Result<(), CustomRedisError> {let final_bytes = self.serialize_and_compress(v, format)?;- let mut conn = self.connection.clone();+ let mut conn = self.conn();conn.set_ex::<_, _, ()>(k, final_bytes, seconds).await?;Ok(())}@@ -388,7 +460,7 @@ impl Client for RedisClient {) -> Result<bool, CustomRedisError> {let final_bytes = self.serialize_and_compress(v, format)?;- let mut conn = self.connection.clone();+ let mut conn = self.conn();let seconds_usize = seconds as usize;// Use SET with both NX and EX options@@ -423,7 +495,7 @@ impl Client for RedisClient {.ignore();}- let mut conn = self.connection.clone();+ let mut conn = self.conn();pipe.query_async::<()>(&mut conn).await?;Ok(())}@@ -439,19 +511,19 @@ impl Client for RedisClient {pipe.cmd("EXPIRE").arg(&k).arg(ttl_seconds).ignore();}- let mut conn = self.connection.clone();+ let mut conn = self.conn();pipe.query_async::<()>(&mut conn).await?;Ok(())}async fn del(&self, k: String) -> Result<(), CustomRedisError> {- let mut conn = self.connection.clone();+ let mut conn = self.conn();conn.del::<_, ()>(k).await?;Ok(())}async fn hget(&self, k: String, field: String) -> Result<String, CustomRedisError> {- let mut conn = self.connection.clone();+ let mut conn = self.conn();let result: Option<String> = conn.hget(k, field).await?;match result {@@ -461,7 +533,7 @@ impl Client for RedisClient {}async fn scard(&self, k: String) -> Result<u64, CustomRedisError> {- let mut conn = self.connection.clone();+ let mut conn = self.conn();let result = conn.scard(k).await?;Ok(result)}@@ -470,7 +542,7 @@ impl Client for RedisClient {if keys.is_empty() {return Ok(vec![]);}- let mut conn = self.connection.clone();+ let mut conn = self.conn();let results: Vec<Option<Vec<u8>>> = conn.mget(&keys).await?;Ok(results)}@@ -483,7 +555,7 @@ impl Client for RedisClient {for k in &keys {pipe.scard(k);}- let mut conn = self.connection.clone();+ let mut conn = self.conn();let results: Vec<u64> = pipe.query_async(&mut conn).await?;Ok(results)}@@ -505,7 +577,7 @@ impl Client for RedisClient {.arg("NX").ignore();}- let mut conn = self.connection.clone();+ let mut conn = self.conn();pipe.query_async::<()>(&mut conn).await?;Ok(())}@@ -521,7 +593,7 @@ impl Client for RedisClient {for (k, v, ttl) in &items {pipe.cmd("SET").arg(k).arg(v).arg("NX").arg("EX").arg(ttl);}- let mut conn = self.connection.clone();+ let mut conn = self.conn();let results: Vec<Option<String>> = pipe.query_async(&mut conn).await?;Ok(results.into_iter().map(|r| r.is_some()).collect())}@@ -530,7 +602,7 @@ impl Client for RedisClient {if keys.is_empty() {return Ok(());}- let mut conn = self.connection.clone();+ let mut conn = self.conn();redis::cmd("DEL").arg(&keys).query_async::<()>(&mut conn)@@ -613,7 +685,7 @@ impl Client for RedisClient {}// Execute the pipeline- let mut conn = self.connection.clone();+ let mut conn = self.conn();let raw_results: Vec<redis::Value> = pipe.query_async(&mut conn).await?;// Process resultsdiff --git a/rust/common/redis/src/lib.rs b/rust/common/redis/src/lib.rsindex be2e60e17893..a1867aec9748 100644--- a/rust/common/redis/src/lib.rs+++ b/rust/common/redis/src/lib.rs@@ -290,6 +290,14 @@ pub trait Client: Send + Sync {&self,commands: Vec<PipelineCommand>,) -> Result<Vec<Result<PipelineResult, CustomRedisError>>, CustomRedisError>;++ /// Attempt to repair a dead underlying connection.+ ///+ /// Callers that see `CustomRedisError::is_unrecoverable_error()` may call+ /// this; implementations that self-heal (or have nothing to heal) keep the+ /// default no-op. Must be cheap to call repeatedly -- implementations own+ /// their own cooldown.+ async fn heal(&self) {}}/// Extension trait providing the `.pipeline()` builder method.diff --git a/rust/common/redis/src/read_write.rs b/rust/common/redis/src/read_write.rsindex 6c0c709a8c72..17db25225a6f 100644--- a/rust/common/redis/src/read_write.rs+++ b/rust/common/redis/src/read_write.rs@@ -253,6 +253,11 @@ impl ReadWriteClient {#[async_trait]impl Client for ReadWriteClient {+ async fn heal(&self) {+ self.reader.heal().await;+ self.writer.heal().await;+ }+async fn get(&self, k: String) -> Result<String, CustomRedisError> {match self.reader.get(k.clone()).await {Ok(value) => Ok(value),