: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): stop the rate limiter dropping counts on a busy pod (#116680)
Eli Reismanb17390ae66cb
diff --git a/rust/common/limiters/GLOBAL_RATE_LIMITER.md b/rust/common/limiters/GLOBAL_RATE_LIMITER.mdindex 3d36e9b47523..0ca35860883a 100644--- a/rust/common/limiters/GLOBAL_RATE_LIMITER.md+++ b/rust/common/limiters/GLOBAL_RATE_LIMITER.md@@ -208,6 +208,9 @@ The background task uses `tokio::select!` over two sources:```The channel is not read while a tick runs, so updates wait in it until the tick ends.+The loop takes updates in batches of up to `UPDATE_DRAIN_BATCH` (256) per receive. Tokio's cooperative budget allows a task 128 budgeted operations per poll, and each receive is one, so one update per receive lets a CPU-starved pod drain slower than events arrive.+Each tick first takes every update already queued. A tick that runs longer than `tick_interval` leaves the next tick ready at once, and without this drain the random `select!` could pick the tick again before the channel.+A full channel drops the update and increments `global_rate_limiter_error_total` with `cause=channel_full`. It writes no log line.Each tick, per Redis instance:@@ -334,7 +337,7 @@ Where the two read different env vars, both are listed.| `max_concurrent_commands` | 4 | `GLOBAL_RATE_LIMIT_MAX_CONCURRENT_COMMANDS` | Commands in flight at once per instance || `max_write_batch_entries` | 200,000 | `GLOBAL_RATE_LIMIT_MAX_WRITE_BATCH_ENTRIES` | Buffered `(key, epoch)` entries. At the cap, updates for new keys drop and are counted || `max_pending_sync_entries` | 200,000 | `GLOBAL_RATE_LIMIT_MAX_PENDING_SYNC_ENTRIES` | Queued syncs. At the cap, new sync requests drop and re-queue on the key's next request |-| `channel_capacity` | 1,000,000 | — | mpsc channel buffer for async update requests |+| `channel_capacity` | 1,000,000 | — | mpsc channel buffer for async update requests. A full channel drops the update |#### Local cache (Moka)@@ -368,7 +371,7 @@ Without `GLOBAL_RATE_LIMIT_REDIS_URL`, both limiters share capture's main Redis- An entry idles out only when no request touches it for `local_cache_idle_timeout`, so a key's sync cadence never evicts an active key.- Under high key cardinality with cold-skewed traffic, a shorter idle timeout reclaims slots faster.-- **`min_sync_floor` gates reads only.** It never drops a count; it only suppresses the `MGET` for keys too far under their threshold to be limited. Counts can still be lost to a full channel, the write-batch cap, or a failed write.+- **`min_sync_floor` gates reads only.** It never drops a count; it only suppresses the `MGET` for keys too far under their threshold to be limited. Counts can still be lost to a full channel, the write-batch cap, a failed write, or the stale-epoch purge.- Writes are bounded separately. `absorb_update` merges updates by `(key, epoch)` between ticks, so write volume scales with distinct active keys, not event rate.## Request Flow@@ -483,6 +486,7 @@ hashes. Two things to know before that changes.| `global_rate_limiter_pending_sync_size` | Gauge | Keys read this tick, capped at `max_sync_keys_per_tick`. For the backlog, use `sync_deferred_size` || `global_rate_limiter_sync_deferred_size` | Gauge | Keys still queued for sync after a tick took its slice || `global_rate_limiter_write_deferred_size` | Gauge | `(key, epoch)` entries still batched after a tick took its slice |+| `global_rate_limiter_update_channel_depth` | Gauge | Updates waiting in the channel when a tick starts. Near zero while the loop keeps up || `global_rate_limiter_sync_skipped_total` | Counter | Syncs not queued because the key is below the floor || `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 changes, counted when a read lands |diff --git a/rust/common/limiters/src/global_rate_limiter.rs b/rust/common/limiters/src/global_rate_limiter.rsindex 896f8c2f96cf..b35c2023960b 100644--- a/rust/common/limiters/src/global_rate_limiter.rs+++ b/rust/common/limiters/src/global_rate_limiter.rs@@ -49,6 +49,8 @@ const GLOBAL_RATE_LIMITER_EVICTION_COUNTER: &str = "global_rate_limiter_evictionconst 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";+/// Updates waiting in the channel when a tick starts.+const GLOBAL_RATE_LIMITER_CHANNEL_DEPTH_GAUGE: &str = "global_rate_limiter_update_channel_depth";/// 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.@@ -70,6 +72,8 @@ const CUSTOM_THRESHOLDS_LAST_REFRESH_GAUGE: &str =/// distribution moves slowly and prod metrics dedup to 60s, so a periodic scan/// keeps these gauges fresh enough without scanning the cache every tick.const TIER_SCAN_INTERVAL_TICKS: u64 = 30;+/// Batch receives so Tokio's 128-receive poll budget cannot throttle the drain on a starved pod.+const UPDATE_DRAIN_BATCH: usize = 256;/// Tier label order, indexed by `PressureTier::index()`.const TIER_LABELS: [&str; 4] = ["idle", "low", "normal", "hot"];@@ -905,7 +909,7 @@ impl GlobalRateLimiterImpl {timestamp,};- if let Some(Err(e)) = self.update_tx.as_ref().map(|tx| tx.try_send(update)) {+ if let Some(Err(_)) = self.update_tx.as_ref().map(|tx| tx.try_send(update)) {metrics::counter!(GLOBAL_RATE_LIMITER_ERROR_COUNTER,"scope" => self.scope,@@ -914,11 +918,6 @@ impl GlobalRateLimiterImpl {"cause" => "channel_full",).increment(1);- error!(- key = key,- error = %e,- "Failed to queue rate limit update, channel may be full"- );}}@@ -1017,35 +1016,38 @@ impl GlobalRateLimiterImpl {// Pre-aggregate writes by (key, epoch)let mut write_batch: HashMap<(String, i64), u64> = HashMap::new();let mut tick_n: u64 = 0;+ let mut update_buf: Vec<UpdateRequest> = Vec::with_capacity(UPDATE_DRAIN_BATCH);loop {tokio::select! {- result = update_rx.recv() => {- match result {- Some(req) => {- let epoch = epoch_from_timestamp(req.timestamp, config.window_interval);- Self::absorb_update(- &mut write_batch,- req.key,- epoch,- req.count,- config.max_write_batch_entries,- scope,- );- }- None => {- // Channel closed: run one last bounded tick and exit- if !write_batch.is_empty() {- Self::tick(- &config, &redis_instances, &cache,- &pending_sync, &mut write_batch, &read_health, scope, tick_n,- ).await;- }- break;+ drained = update_rx.recv_many(&mut update_buf, UPDATE_DRAIN_BATCH) => {+ if drained == 0 {+ // Channel closed: run one last bounded tick and exit+ if !write_batch.is_empty() {+ Self::tick(+ &config, &redis_instances, &cache,+ &pending_sync, &mut write_batch, &read_health, scope, tick_n,+ ).await;}+ break;}+ Self::absorb_requests(&config, &mut write_batch, &mut update_buf, scope);}_ = tick.tick() => {+ // Drain the queue first, or back-to-back overrun ticks can starve the channel.+ let mut queued = update_rx.len();+ metrics::gauge!(GLOBAL_RATE_LIMITER_CHANNEL_DEPTH_GAUGE, "scope" => scope)+ .set(queued as f64);+ while queued > 0 {+ let taken = update_rx+ .recv_many(&mut update_buf, UPDATE_DRAIN_BATCH.min(queued))+ .await;+ if taken == 0 {+ break;+ }+ queued -= taken;+ Self::absorb_requests(&config, &mut write_batch, &mut update_buf, scope);+ }tick_n = tick_n.wrapping_add(1);Self::tick(&config, &redis_instances, &cache,@@ -1057,6 +1059,25 @@ impl GlobalRateLimiterImpl {});}+ fn absorb_requests(+ config: &GlobalRateLimiterConfig,+ write_batch: &mut HashMap<(String, i64), u64>,+ update_buf: &mut Vec<UpdateRequest>,+ scope: &'static str,+ ) {+ for req in update_buf.drain(..) {+ let epoch = epoch_from_timestamp(req.timestamp, config.window_interval);+ Self::absorb_update(+ write_batch,+ req.key,+ epoch,+ req.count,+ config.max_write_batch_entries,+ scope,+ );+ }+ }+/// 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@@ -2758,6 +2779,74 @@ mod tests {matches!(result, EvalResult::Limited(_))}+ fn written_total(mock: &MockRedisClient) -> u64 {+ mock.get_calls()+ .iter()+ .filter(|c| c.op == "batch_incr_by_expire_at")+ .flat_map(|c| c.key.split(','))+ .filter_map(|item| {+ item.split_once('=')?+ .1+ .split('@')+ .next()?+ .parse::<u64>()+ .ok()+ })+ .sum()+ }++ #[tokio::test(flavor = "current_thread")]+ async fn test_ticks_longer_than_the_interval_do_not_starve_the_channel() {+ let mock = Arc::new(+ MockRedisClient::new().batch_incr_by_expire_at_block(Duration::from_millis(50)),+ );+ let config = GlobalRateLimiterConfig {+ channel_capacity: 2_000,+ tick_interval: Duration::from_millis(10),+ global_write_timeout: Duration::from_secs(1),+ ..config_with_floor(0)+ };+ let limiter = GlobalRateLimiterImpl::new(config, vec![mock.clone()]).unwrap();++ // Writes outlast the tick interval, so every tick overruns.+ for round in 0..60 {+ for i in 0..200 {+ limiter.check_limit(&format!("r{round}k{i}"), 1, None).await;+ }+ tokio::time::sleep(Duration::from_millis(10)).await;+ }++ wait_until!(+ "ticks that overran their interval starved the channel and lost updates",+ written_total(&mock) == 12_000+ );+ }++ #[tokio::test(flavor = "current_thread")]+ async fn test_burst_larger_than_one_poll_budget_is_not_dropped() {+ let mock = Arc::new(MockRedisClient::new());+ let config = GlobalRateLimiterConfig {+ channel_capacity: 400,+ tick_interval: Duration::from_millis(10),+ ..config_with_floor(0)+ };+ let limiter = GlobalRateLimiterImpl::new(config, vec![mock.clone()]).unwrap();++ for i in 0..400 {+ limiter.check_limit(&format!("first{i}"), 1, None).await;+ }+ // One poll of the background task; a single `recv` would take only 128 updates.+ tokio::task::yield_now().await;+ for i in 0..300 {+ limiter.check_limit(&format!("second{i}"), 1, None).await;+ }++ wait_until!(+ "a burst larger than one poll overflowed the channel and lost updates",+ written_total(&mock) == 700+ );+ }+fn failing_reads() -> Arc<dyn Client + Send + Sync> {Arc::new(MockRedisClient::new().mget_error(CustomRedisError::Timeout))}diff --git a/rust/common/redis/src/mock.rs b/rust/common/redis/src/mock.rsindex 9e205f0a15af..2520f7c2e032 100644--- a/rust/common/redis/src/mock.rs+++ b/rust/common/redis/src/mock.rs@@ -27,6 +27,7 @@ pub struct MockRedisClient {mget_error: Option<CustomRedisError>,pipeline_error: Option<CustomRedisError>,pipeline_block: Option<Duration>,+ batch_incr_by_expire_at_block: Option<Duration>,pipeline_errors_by_call: HashMap<usize, CustomRedisError>,/// Shared via `Arc` so clones of the mock agree on call sequencing.pipeline_call_counter: Arc<AtomicUsize>,@@ -57,6 +58,7 @@ impl Default for MockRedisClient {mget_error: None,pipeline_error: None,pipeline_block: None,+ batch_incr_by_expire_at_block: None,pipeline_errors_by_call: HashMap::new(),pipeline_call_counter: Arc::new(AtomicUsize::new(0)),mget_errors_by_call: HashMap::new(),@@ -206,6 +208,12 @@ impl MockRedisClient {self.clone()}+ /// Block every `batch_incr_by_expire_at` call for `duration` after recording it.+ pub fn batch_incr_by_expire_at_block(&mut self, duration: Duration) -> Self {+ self.batch_incr_by_expire_at_block = Some(duration);+ self.clone()+ }+/// Fail the Nth `execute_pipeline` call (0-indexed across the lifetime of/// this mock) with the given error. Other calls proceed normally. Takes/// precedence over `pipeline_error`. Use to exercise partial-failure@@ -560,6 +568,9 @@ impl Client for MockRedisClient {key: recorded,value: MockRedisValue::None,});+ if let Some(duration) = self.batch_incr_by_expire_at_block {+ futures_timer::Delay::new(duration).await;+ }match &self.batch_incr_by_expire_at_ret {Some(ret) => ret.clone(),