From 44e97e96f43b3882151119ed59f0af4c2fb4fbad Mon Sep 17 00:00:00 2001 From: Wes Date: Wed, 18 Nov 2026 14:28:20 -0700 Subject: [PATCH] fix(pubsub): round the rate-limit retry hint up from PTTL (#9552) ## Summary The Redis rate limiter built its `retry in Ns` hint from `TTL`, which truncates to whole seconds. With 400 ms left in the window, a denied request was told `retry in 0s`, and a client that sleeps for exactly the hint retried straight into another refusal. This reads `PTTL` and rounds the milliseconds up to whole seconds, so the hint is never 0 while the window is still open. The no-expiry repair path is unchanged. ## Testing - New `rate_limiter::tests::retry_hint_rounds_a_partial_second_up` (`#[ignore = "requires Redis"]`, like the other Redis tests in this crate) seeds an exhausted window with 400 ms left and asserts the denial reports 1 second. Against the old `TTL` code it fails with `left: 0, right: 1`; with this change it passes. - `cargo nextest run -p buzz-pubsub --lib`: 38 passed. Ignored Redis `rate_limiter` and `nip98_replay` tests: 5 passed against a local Redis. - `cargo nextest run -p buzz-relay --lib` with local Postgres and Redis: 1762 passed. The relay `rejection::`/`admission::` lane with `--run-ignored all`: 16 passed. - Pre-push hooks (including rust-tests) passed. CI note: the Redis-backed pubsub tests only run in CI when they are named in `.github/workflows/_ci-relay.yml`, so the new test isn't selected there yet. Adding `or test(/^rate_limiter::tests::/)` to the "Pubsub subscriber reconciliation regression" filter would cover it. I left that out here because this branch can't push workflow file changes. --------- Signed-off-by: Wes Co-authored-by: Groot Co-authored-by: Star Lord --- crates/buzz-pubsub/src/rate_limiter.rs | 45 +++++++++++++++++++++++--- 1 file changed, 40 insertions(+), 5 deletions(-) diff --git a/crates/buzz-pubsub/src/rate_limiter.rs b/crates/buzz-pubsub/src/rate_limiter.rs index 095e6591e1..570e2d8330 100644 --- a/crates/buzz-pubsub/src/rate_limiter.rs +++ b/crates/buzz-pubsub/src/rate_limiter.rs @@ -17,7 +17,9 @@ use buzz_core::TenantContext; use nostr::PublicKey; use redis::Script; -/// Atomically INCR the key, set EXPIRE on first call, and return (count, ttl). +/// Atomically INCR the key, set EXPIRE on first call, and return +/// (count, ttl_ms). The TTL is in milliseconds because `TTL` truncates to +/// whole seconds and would report 0 while part of a second remains. /// /// Using a Lua script ensures INCR and EXPIRE are executed atomically — /// a crash between them can no longer leave a key without a TTL. @@ -26,7 +28,7 @@ local count = redis.call('INCR', KEYS[1]) if count == 1 then redis.call('EXPIRE', KEYS[1], ARGV[1]) end -local ttl = redis.call('TTL', KEYS[1]) +local ttl = redis.call('PTTL', KEYS[1]) return {count, ttl} "#; @@ -45,7 +47,7 @@ async fn run_rate_limit( let mut conn = pool.clone(); let script = Script::new(RATE_LIMIT_SCRIPT); - let (count, ttl): (u64, i64) = script + let (count, ttl_ms): (u64, i64) = script .key(key) .arg(window_secs as i64) .invoke_async(&mut conn) @@ -54,7 +56,7 @@ async fn run_rate_limit( // ttl == -1 means the key exists but has no expiry — broken state from a // prior crash between INCR and EXPIRE. Repair it now. - let reset_in_secs = if ttl < 0 { + let reset_in_secs = if ttl_ms < 0 { tracing::warn!(key = %key, "rate limit key has no TTL — repairing"); let _: () = redis::cmd("EXPIRE") .arg(key) @@ -65,7 +67,8 @@ async fn run_rate_limit( // After repair, the window resets to the full duration. window_secs } else { - ttl.max(0) as u64 + // Round up so the retry hint is never 0 while the window is open. + (ttl_ms as u64).div_ceil(1000) }; if count <= limit { @@ -116,3 +119,35 @@ impl RateLimiter for RedisRateLimiter { run_rate_limit(&self.pool, &key, window_secs, limit).await } } + +#[cfg(test)] +mod tests { + use super::*; + + fn redis_pool() -> crate::RedisConnection { + let url = std::env::var("REDIS_URL").unwrap_or_else(|_| "redis://127.0.0.1:6379".into()); + crate::redis_connection(&url).expect("redis connection") + } + + #[tokio::test] + #[ignore = "requires Redis"] + async fn retry_hint_rounds_a_partial_second_up() { + let pool = redis_pool(); + let key = format!("buzz:test:ratelimit:{}", uuid::Uuid::new_v4()); + let _: () = redis::cmd("SET") + .arg(&key) + .arg(1) + .arg("PX") + .arg(1400) + .query_async(&mut pool.clone()) + .await + .expect("seed exhausted window"); + + let result = run_rate_limit(&pool, &key, 60, 1) + .await + .expect("rate limit"); + + assert!(!result.allowed); + assert_eq!(result.reset_in_secs, 2); + } +}