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.

fix(capture): clamp the rate limiter Redis TTL to two windows (#89726)

Eli Reisman274efc01b835
diff --git a/rust/common/limiters/GLOBAL_RATE_LIMITER.md b/rust/common/limiters/GLOBAL_RATE_LIMITER.md
index 11247f8fb7dc..d1cf81662975 100644
--- a/rust/common/limiters/GLOBAL_RATE_LIMITER.md
+++ b/rust/common/limiters/GLOBAL_RATE_LIMITER.md
@@ -260,7 +260,7 @@ only if you're also changing the window/sync intervals.
| Parameter | Default | Description |
|---|---|---|
-| `global_cache_ttl` | 120s (2 × window) | `EXPIRE` TTL on Redis epoch keys. Must be ≥ 2 × `window_interval` so both epoch keys survive for reads |
+| `global_cache_ttl` | 2 × `window_interval` | `EXPIRE` TTL on Redis epoch keys. Clamped up to 2 × `window_interval` at construction so both epoch keys survive for reads. The default is derived from the *default* window, so a caller that changes `window_interval` and leaves this alone is corrected rather than silently under-enforcing |
| `global_read_timeout` | 100ms | Timeout for batched MGET reads |
| `global_write_timeout` | 100ms | Timeout for batched INCRBY writes |
| `redis_key_prefix` | `@posthog/global_rate_limiter` | Prefix for all Redis keys (capture derives from `capture_mode`) |
@@ -278,8 +278,9 @@ only if you're also changing the window/sync intervals.
│◄── window_interval (60s) ──►│
│ │
- │ global_cache_ttl (120s = 2×window) │
- │ Redis epoch keys expire after this, ensuring old counters clean up │
+ │ global_cache_ttl (2×window, clamped at construction) │
+ │ Redis epoch keys expire after this. Below 2×window the previous │
+ │ epoch key dies while reads still need it, and the estimate drops. │
│◄─────────────────────────────────────────────────────────────────────►│
│ │
│ local_cache_idle_timeout (300s) │
@@ -300,8 +301,22 @@ 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 Redis hygiene — it only needs to be ≥ 2 × `window_interval`.
- Making it much larger wastes Redis memory on dead keys.
+- `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.
+
+**All three TTLs are clamped at construction**, because each one expiring inside
+the window it serves causes silent under-enforcement:
+
+| Parameter | Clamped to at least | What an undersized value breaks |
+|---|---|---|
+| `local_cache_idle_timeout` | `window_interval` | Entries expire mid-window and the next request takes the always-allowed miss path |
+| `local_cache_ttl` | `window_interval` | Same, on the absolute expiry path |
+| `global_cache_ttl` | 2 × `window_interval` | The previous epoch key dies while reads still need it, so `prev_count` reads as 0 |
## Request Flow
diff --git a/rust/common/limiters/src/global_rate_limiter.rs b/rust/common/limiters/src/global_rate_limiter.rs
index f00f8b5f1a04..af12e946c3fa 100644
--- a/rust/common/limiters/src/global_rate_limiter.rs
+++ b/rust/common/limiters/src/global_rate_limiter.rs
@@ -543,6 +543,25 @@ 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.
+ let min_global_cache_ttl = config.window_interval * 2;
+ if config.global_cache_ttl < min_global_cache_ttl {
+ warn!(
+ scope,
+ global_cache_ttl = ?config.global_cache_ttl,
+ window_interval = ?config.window_interval,
+ "global_cache_ttl below 2x window_interval expires the previous \
+ epoch key while reads still need it; clamping to 2x window_interval"
+ );
+ config.global_cache_ttl = min_global_cache_ttl;
+ }
let config = config;
let cache = Cache::builder()
@@ -2113,6 +2132,35 @@ mod tests {
}
}
+ #[tokio::test]
+ async fn test_global_cache_ttl_clamped_up_to_two_windows() {
+ // (configured_ttl_secs, expected_secs) against test_config()'s 60s window
+ let cases = vec![
+ (30, 120), // below one window
+ (60, 120), // one window: still expires the previous epoch early
+ (119, 120), // just below the bound
+ (120, 120), // exactly at the bound: untouched
+ (600, 600), // above: untouched
+ ];
+
+ for (ttl_secs, expected_secs) in cases {
+ let client = Arc::new(MockRedisClient::new());
+ let config = GlobalRateLimiterConfig {
+ global_cache_ttl: Duration::from_secs(ttl_secs),
+ ..test_config()
+ };
+ let limiter = GlobalRateLimiterImpl::new(config, vec![client]).unwrap();
+
+ assert_eq!(
+ limiter.config.global_cache_ttl,
+ Duration::from_secs(expected_secs),
+ "global_cache_ttl={ttl_secs}s against a 60s window should resolve to {expected_secs}s -- \
+ a TTL under 2x the window expires the previous epoch key while reads still \
+ need it, so weighted_count takes prev_count as 0 and under-enforces"
+ );
+ }
+ }
+
#[tokio::test]
async fn test_sync_floor_capped_at_one_percent_of_threshold() {
// (configured_floor, threshold, count, expect_queued)
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 38ba3047e3b7..3068ed3792b0 100644
--- a/rust/common/limiters/tests/global_rate_limiter_integration_tests.rs
+++ b/rust/common/limiters/tests/global_rate_limiter_integration_tests.rs
@@ -105,13 +105,22 @@ async fn test_epoch_key_ttl_expiry() {
};
let mut config = test_config("ttl_expiry");
- config.global_cache_ttl = Duration::from_secs(2);
+ // `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.
+ 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();
- let _ = limiter.check_limit("ttl_key", 10, None).await;
-
+ // 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.
let now = Utc::now();
+ let _ = limiter.check_limit("ttl_key", 10, Some(now)).await;
+
let epoch = epoch_from_timestamp(now, config.window_interval);
let redis_key = epoch_key(&config.redis_key_prefix, "ttl_key", epoch);
@@ -120,7 +129,7 @@ async fn test_epoch_key_ttl_expiry() {
results[0].is_some()
});
- tokio::time::sleep(Duration::from_secs(3)).await;
+ tokio::time::sleep(Duration::from_secs(5)).await;
let results = redis.mget(vec![redis_key]).await.unwrap();
assert!(results[0].is_none(), "Key should have expired after TTL");