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): pin rate limiter epoch keys to an absolute expiry (#104891)

Eli Reisman0a43f6069110
diff --git a/rust/common/limiters/GLOBAL_RATE_LIMITER.md b/rust/common/limiters/GLOBAL_RATE_LIMITER.md
index 709009f7f7bd..0db0844334b6 100644
--- a/rust/common/limiters/GLOBAL_RATE_LIMITER.md
+++ b/rust/common/limiters/GLOBAL_RATE_LIMITER.md
@@ -39,7 +39,7 @@ and **pressure-tiered adaptive sync** to minimize read volume for low-utilizatio
│ │ 2. Drain pending_sync set → sync_keys Vec │ │
│ │ │ │
│ │ 3. Build single Redis pipeline: │ │
-│ │ WRITES: INCRBY + EXPIRE for each (key, epoch) │ │
+│ │ WRITES: INCRBY + EXPIREAT for each (key, epoch) │ │
│ │ READS: MGET [curr_epoch, prev_epoch] per entity │ │
│ │ │ │
│ │ 4. Execute pipeline │ │
@@ -62,7 +62,7 @@ and **pressure-tiered adaptive sync** to minimize read volume for low-utilizatio
│ {prefix}:{key}:{e} │
│ │
│ e = epoch number │
- │ TTL = 2 × window │
+ │ dies 1 epoch later │
└─────────────────────┘
```
@@ -177,7 +177,7 @@ The background task uses `tokio::select!` over two sources:
The pipeline per tick consists of:
-- **Writes**: `INCRBY key delta` + `EXPIRE key ttl` for each `(entity, epoch)` with pending counts
+- **Writes**: `INCRBY key delta` + `EXPIREAT key deadline` for each `(entity, epoch)` with pending counts
- **Reads**: `MGET [current_epoch_key, prev_epoch_key]` for each entity in `pending_sync`
All operations go in a single Redis round-trip.
@@ -241,7 +241,7 @@ but are written to Redis on the next tick — the under-count is negligible (<0.
```text
Key: {prefix}:{entity_key}:{epoch_number}
Value: integer counter (INCRBY)
-TTL: 2 × window_interval (120s for 60s window)
+Dies: (epoch + 2) × window_interval, an absolute instant fixed by the epoch
```
Only 2 keys per entity exist at any time (current + previous epoch).
@@ -281,7 +281,7 @@ only if you're also changing the window/sync intervals.
| Parameter | Default | Description |
|---|---|---|
-| `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_cache_ttl` | 2 × `window_interval` | Sets the deadline on Redis epoch keys, applied as `EXPIREAT` rather than a relative TTL so a key's life follows its epoch instead of its last write. Any value above the two-window minimum becomes clock-skew grace. |
| `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`) |
diff --git a/rust/common/limiters/src/global_rate_limiter.rs b/rust/common/limiters/src/global_rate_limiter.rs
index 17dcac6f0b88..58e2867f46b5 100644
--- a/rust/common/limiters/src/global_rate_limiter.rs
+++ b/rust/common/limiters/src/global_rate_limiter.rs
@@ -357,6 +357,16 @@ pub fn epoch_key(prefix: &str, key: &str, epoch: i64) -> String {
format!("{prefix}:{key}:{epoch}")
}
+/// The absolute unix second at which an epoch key stops being readable, since
+/// a read consults only the current and previous epoch.
+///
+/// TTL configured above the two-window minimum becomes clock-skew grace.
+pub fn epoch_expire_at(epoch: i64, window_interval: Duration, global_cache_ttl: Duration) -> i64 {
+ let window_secs = window_interval.as_secs() as i64;
+ let grace_secs = (global_cache_ttl.as_secs() as i64 - 2 * window_secs).max(0);
+ (epoch + 2) * window_secs + grace_secs
+}
+
/// Build the current and previous epoch Redis keys for a given entity
pub fn epoch_keys(
prefix: &str,
@@ -1115,7 +1125,6 @@ impl GlobalRateLimiterImpl {
) {
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 first, then reads. A read result zeroes each synced key's
// `local_pending`, so the read must already include this tick's write
@@ -1126,8 +1135,7 @@ impl GlobalRateLimiterImpl {
// 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 writes_issued = Self::run_writes(config, redis, &redis_idx_str, writes, scope).await;
let reads_issued =
Self::run_reads(config, redis, &redis_idx_str, cache, sync_keys, now, scope).await;
@@ -1149,22 +1157,23 @@ impl GlobalRateLimiterImpl {
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
+ let write_items: Vec<(String, i64, i64)> = writes
.iter()
.map(|((key, epoch), count)| {
let redis_key = epoch_key(&config.redis_key_prefix, key, *epoch);
- (redis_key, *count as i64)
+ let expire_at =
+ epoch_expire_at(*epoch, config.window_interval, config.global_cache_ttl);
+ (redis_key, *count as i64, expire_at)
})
.collect();
- let chunks: Vec<Vec<(String, i64)>> = write_items
+ let chunks: Vec<Vec<(String, i64, i64)>> = write_items
.chunks(config.max_keys_per_command.max(1))
.map(|chunk| chunk.to_vec())
.collect();
@@ -1182,7 +1191,7 @@ impl GlobalRateLimiterImpl {
let started = Instant::now();
match tokio::time::timeout(
config.global_write_timeout,
- redis.batch_incr_by_expire(chunk.clone(), ttl),
+ redis.batch_incr_by_expire_at(chunk.clone()),
)
.await
{
@@ -1583,6 +1592,43 @@ mod tests {
assert_eq!(prev, "p:k:1");
}
+ #[test]
+ fn test_epoch_expire_at_covers_exactly_the_readable_window() {
+ let window = Duration::from_secs(120);
+ // The minimum cache TTL is two windows, which leaves no grace.
+ let ttl = Duration::from_secs(240);
+
+ // A key written anywhere in epoch 10 is read while the clock sits in
+ // epoch 10 or epoch 11, so it must live to the end of epoch 11 and no
+ // longer. Epoch 11 ends at (10 + 2) * 120.
+ assert_eq!(epoch_expire_at(10, window, ttl), 1440);
+
+ let last_readable_instant = 12 * 120 - 1;
+ assert!(epoch_expire_at(10, window, ttl) > last_readable_instant);
+
+ // The deadline follows the epoch, so consecutive epochs stay one
+ // window apart rather than drifting with write time.
+ assert_eq!(
+ epoch_expire_at(11, window, ttl) - epoch_expire_at(10, window, ttl),
+ 120
+ );
+ }
+
+ #[test]
+ fn test_epoch_expire_at_carries_configured_slack_as_grace() {
+ let window = Duration::from_secs(120);
+
+ // TTL above the two-window minimum becomes clock-skew grace.
+ assert_eq!(
+ epoch_expire_at(10, window, Duration::from_secs(250)),
+ 1440 + 10
+ );
+
+ // A TTL below the minimum cannot pull the deadline inside the readable
+ // window, which would expire a key that reads still consult.
+ assert_eq!(epoch_expire_at(10, window, Duration::from_secs(60)), 1440);
+ }
+
// --- Weighted count estimation tests (parameterized) ---
#[test]
@@ -1911,7 +1957,7 @@ mod tests {
let calls = client.get_calls();
let batch_calls: Vec<_> = calls
.iter()
- .filter(|c| c.op == "batch_incr_by_expire")
+ .filter(|c| c.op == "batch_incr_by_expire_at")
.collect();
assert!(
!batch_calls.is_empty(),
@@ -2397,12 +2443,18 @@ mod tests {
let write_calls: Vec<String> = mock
.get_calls()
.into_iter()
- .filter(|c| c.op == "batch_incr_by_expire")
+ .filter(|c| c.op == "batch_incr_by_expire_at")
.map(|c| c.key)
.collect();
+ let live_key = epoch_key(&config.redis_key_prefix, "live", current_epoch);
+ let live_expire_at = epoch_expire_at(
+ current_epoch,
+ config.window_interval,
+ config.global_cache_ttl,
+ );
assert_eq!(
write_calls,
- vec![format!("items=1;ttl={}", config.global_cache_ttl.as_secs())],
+ vec![format!("{live_key}=1@{live_expire_at}")],
"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!(
diff --git a/rust/common/redis/src/client.rs b/rust/common/redis/src/client.rs
index acbb2510ce90..35d690263cea 100644
--- a/rust/common/redis/src/client.rs
+++ b/rust/common/redis/src/client.rs
@@ -570,6 +570,21 @@ impl Client for RedisClient {
Ok(())
}
+ async fn batch_incr_by_expire_at(
+ &self,
+ items: Vec<(String, i64, i64)>,
+ ) -> Result<(), CustomRedisError> {
+ let mut pipe = redis::pipe();
+ for (k, by, expire_at) in items {
+ pipe.cmd("INCRBY").arg(&k).arg(by).ignore();
+ pipe.cmd("EXPIREAT").arg(&k).arg(expire_at).ignore();
+ }
+
+ let mut conn = self.conn();
+ pipe.query_async::<()>(&mut conn).await?;
+ Ok(())
+ }
+
async fn del(&self, k: String) -> Result<(), CustomRedisError> {
let mut conn = self.conn();
conn.del::<_, ()>(k).await?;
diff --git a/rust/common/redis/src/lib.rs b/rust/common/redis/src/lib.rs
index 77658aeb3908..640b6ceab786 100644
--- a/rust/common/redis/src/lib.rs
+++ b/rust/common/redis/src/lib.rs
@@ -270,6 +270,16 @@ pub trait Client: Send + Sync {
ttl_seconds: usize,
) -> Result<(), CustomRedisError>;
+ /// Increment each key and set its expiry to an absolute unix second, as
+ /// `(key, increment, expire_at)`.
+ ///
+ /// Prefer this over `batch_incr_by_expire` when the key fixes its own
+ /// deadline; do not add `NX`, which needs Redis 7 and buys nothing here.
+ async fn batch_incr_by_expire_at(
+ &self,
+ items: Vec<(String, i64, i64)>,
+ ) -> Result<(), CustomRedisError>;
+
async fn del(&self, k: String) -> Result<(), CustomRedisError>;
async fn hget(&self, k: String, field: String) -> Result<String, CustomRedisError>;
async fn scard(&self, k: String) -> Result<u64, CustomRedisError>;
diff --git a/rust/common/redis/src/mock.rs b/rust/common/redis/src/mock.rs
index 24c5a7018517..2a695cd0791c 100644
--- a/rust/common/redis/src/mock.rs
+++ b/rust/common/redis/src/mock.rs
@@ -17,6 +17,7 @@ pub struct MockRedisClient {
set_nx_ex_ret: HashMap<String, Result<bool, CustomRedisError>>,
batch_incr_by_expire_nx_ret: Option<Result<(), CustomRedisError>>,
batch_incr_by_expire_ret: Option<Result<(), CustomRedisError>>,
+ batch_incr_by_expire_at_ret: Option<Result<(), CustomRedisError>>,
del_ret: HashMap<String, Result<(), CustomRedisError>>,
hget_ret: HashMap<String, Result<String, CustomRedisError>>,
scard_ret: HashMap<String, Result<u64, CustomRedisError>>,
@@ -43,6 +44,7 @@ impl Default for MockRedisClient {
set_nx_ex_ret: HashMap::new(),
batch_incr_by_expire_nx_ret: None,
batch_incr_by_expire_ret: None,
+ batch_incr_by_expire_at_ret: None,
del_ret: HashMap::new(),
hget_ret: HashMap::new(),
scard_ret: HashMap::new(),
@@ -169,6 +171,11 @@ impl MockRedisClient {
self.clone()
}
+ pub fn batch_incr_by_expire_at_ret(&mut self, ret: Result<(), CustomRedisError>) -> Self {
+ self.batch_incr_by_expire_at_ret = Some(ret);
+ self.clone()
+ }
+
pub fn mget_ret(&mut self, key: &str, ret: Option<Vec<u8>>) -> Self {
self.mget_ret.insert(key.to_owned(), ret);
self.clone()
@@ -508,6 +515,28 @@ impl Client for MockRedisClient {
}
}
+ async fn batch_incr_by_expire_at(
+ &self,
+ items: Vec<(String, i64, i64)>,
+ ) -> Result<(), CustomRedisError> {
+ // Record each key's deadline so a test can assert the epoch math.
+ let recorded = items
+ .iter()
+ .map(|(k, by, expire_at)| format!("{k}={by}@{expire_at}"))
+ .collect::<Vec<_>>()
+ .join(",");
+ self.lock_calls().push(MockRedisCall {
+ op: "batch_incr_by_expire_at".to_string(),
+ key: recorded,
+ value: MockRedisValue::None,
+ });
+
+ match &self.batch_incr_by_expire_at_ret {
+ Some(ret) => ret.clone(),
+ None => Ok(()),
+ }
+ }
+
async fn del(&self, key: String) -> Result<(), CustomRedisError> {
let mut calls = self.lock_calls();
calls.push(MockRedisCall {
diff --git a/rust/common/redis/src/read_write.rs b/rust/common/redis/src/read_write.rs
index 703705e8d1a0..4f037bc86df8 100644
--- a/rust/common/redis/src/read_write.rs
+++ b/rust/common/redis/src/read_write.rs
@@ -461,6 +461,13 @@ impl Client for ReadWriteClient {
self.writer.batch_incr_by_expire(items, ttl_seconds).await
}
+ async fn batch_incr_by_expire_at(
+ &self,
+ items: Vec<(String, i64, i64)>,
+ ) -> Result<(), CustomRedisError> {
+ self.writer.batch_incr_by_expire_at(items).await
+ }
+
async fn del(&self, k: String) -> Result<(), CustomRedisError> {
self.writer.del(k).await
}