perf(push-gateway): evict the oldest signed-call window without scanning (#9799)

The push gateway's signed-call limiter keeps one counter per attested
key, capped at 100,000 keys. Once the map was full, every call from a
key not already in it scanned the whole map (once to drop expired
windows, again to find the oldest), all while holding the limiter's
lock. Under heavy load from many new keys, that serialized each signed
call behind a 100,000-entry scan.

The limiter now keeps a queue of window starts, oldest first, and evicts
from its front. A key whose window restarts leaves a stale entry behind,
which eviction skips; the queue is compacted once stale entries make up
half of it, so a call stays O(1) amortized. Rate-limit behavior is
unchanged, except that a full map now drops one oldest window per new
key instead of every expired window at once. The map and the queue share
one copy of each key; the queue can reach about twice the map's entries
before compaction, so memory stays bounded.

Follow-up from #9562.

### Validation

| 1,000 new keys on a full map (release build) | Time |
| --- | --- |
| Before | 277 ms (about 0.28 ms per call, under the lock) |
| After | 0.11 ms |

-
[`a_full_map_drops_the_key_with_the_oldest_window`](https://github.com/block/buzz/blob/push-gateway-limiter-eviction/crates/buzz-push-gateway/src/signed_call_limiter.rs)
checks that eviction picks the oldest window.
-
[`eviction_skips_a_restarted_window`](https://github.com/block/buzz/blob/push-gateway-limiter-eviction/crates/buzz-push-gateway/src/signed_call_limiter.rs)
checks that eviction skips a stale entry and keeps a key whose window
just restarted.
-
[`restarted_windows_do_not_grow_the_queue`](https://github.com/block/buzz/blob/push-gateway-limiter-eviction/crates/buzz-push-gateway/src/signed_call_limiter.rs)
checks that compaction bounds the queue when one key keeps restarting
its window.

---------

Signed-off-by: Tom Brow <tomb@block.xyz>
Co-authored-by: studio <dc2fc481343672df31a689840c09299972e704dac592e0da6f18486646a7ee3e@buzz.block.builderlab.xyz>
This commit is contained in:
Tom Brow
2026-11-20 09:02:20 -08:00
committed by GitHub
parent d647c9fd98
commit 47c9a672d7

View File

@@ -9,7 +9,10 @@
//! with several replicas allows each key up to that many times the configured
//! calls.
use std::{collections::HashMap, sync::Mutex};
use std::{
collections::{HashMap, VecDeque},
sync::{Arc, Mutex},
};
/// Most keys tracked at once. Past it, the key with the oldest window is
/// dropped, so memory stays bounded however many keys call.
@@ -19,7 +22,18 @@ const MAX_TRACKED_KEYS: usize = 100_000;
pub struct SignedCallLimiter {
window_seconds: i64,
max_calls: i64,
windows: Mutex<HashMap<Vec<u8>, Window>>,
state: Mutex<State>,
}
#[derive(Default)]
struct State {
/// Keys are shared with `starts`, so each key is stored once.
windows: HashMap<Arc<[u8]>, Window>,
/// Every window start, oldest first. A key whose window restarted leaves
/// a stale entry behind (its start no longer matches the map), which is
/// skipped on eviction and dropped by compaction. Evicting from the front
/// keeps a call on a full map O(1) amortized instead of a scan of it.
starts: VecDeque<(i64, Arc<[u8]>)>,
}
#[derive(Clone, Copy)]
@@ -28,51 +42,95 @@ struct Window {
calls: i64,
}
impl State {
fn is_current(&self, started_at: i64, key: &[u8]) -> bool {
self.windows
.get(key)
.is_some_and(|w| w.started_at == started_at)
}
/// Drop the key with the oldest window. Wall-clock steps backwards can
/// leave the queue slightly out of order, which only makes the choice
/// approximate.
fn evict_oldest(&mut self) {
while let Some((started_at, key)) = self.starts.pop_front() {
if self.is_current(started_at, &key) {
self.windows.remove(&key);
return;
}
}
}
fn start_window(&mut self, key: Arc<[u8]>, now: i64, calls: i64) {
self.windows.insert(
Arc::clone(&key),
Window {
started_at: now,
calls,
},
);
self.starts.push_back((now, key));
// Restarted windows leave stale entries; drop them once they make up
// half the queue, so compaction stays amortized O(1) per call.
if self.starts.len() > 2 * self.windows.len().max(1) {
let State { windows, starts } = self;
starts.retain(|(started_at, key)| {
windows
.get(&**key)
.is_some_and(|w| w.started_at == *started_at)
});
}
}
}
impl SignedCallLimiter {
/// At most `max_calls` calls per key in each `window_seconds` window.
pub fn new(window_seconds: i64, max_calls: i64) -> Self {
// A window that never ends would restart on every call and grow the
// start queue without bound; config already requires it positive.
assert!(window_seconds > 0, "signed-call window must be positive");
Self {
window_seconds,
max_calls,
windows: Mutex::new(HashMap::new()),
state: Mutex::new(State::default()),
}
}
/// Count one call by `key` at `now`; false when the key is over its limit.
pub fn admit(&self, key: &[u8], now: i64) -> bool {
// The map holds only counters, so a poisoned lock is still consistent.
let mut windows = self
.windows
// The map and the queue must agree, but a panic between their updates
// would at worst leave a live key without a queue entry, which
// eviction skips, so a poisoned lock is still usable.
let mut state = self
.state
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner());
if !windows.contains_key(key) && windows.len() >= MAX_TRACKED_KEYS {
let window_seconds = self.window_seconds;
windows.retain(|_, w| now.saturating_sub(w.started_at) < window_seconds);
if windows.len() >= MAX_TRACKED_KEYS {
let oldest = windows
.iter()
.min_by_key(|(_, w)| w.started_at)
.map(|(key, _)| key.clone());
if let Some(oldest) = oldest {
windows.remove(&oldest);
let restarting = match state.windows.get_mut(key) {
Some(window) if now.saturating_sub(window.started_at) < self.window_seconds => {
if window.calls >= self.max_calls {
return false;
}
window.calls += 1;
return true;
}
}
let window = windows.entry(key.to_vec()).or_insert(Window {
started_at: now,
calls: 0,
});
if now.saturating_sub(window.started_at) >= self.window_seconds {
*window = Window {
started_at: now,
calls: 0,
};
}
if window.calls >= self.max_calls {
return false;
}
window.calls += 1;
true
Some(_) => true,
None => false,
};
let shared_key = if restarting {
state
.windows
.get_key_value(key)
.map(|(shared, _)| Arc::clone(shared))
.expect("a restarting key is in the map")
} else {
if state.windows.len() >= MAX_TRACKED_KEYS {
state.evict_oldest();
}
Arc::from(key)
};
let admitted = self.max_calls > 0;
state.start_window(shared_key, now, i64::from(admitted));
admitted
}
}
@@ -91,7 +149,49 @@ mod tests {
for index in 0..(MAX_TRACKED_KEYS + 10) {
limiter.admit(&index.to_be_bytes(), 1_000);
}
let tracked = limiter.windows.lock().unwrap().len();
let tracked = limiter.state.lock().unwrap().windows.len();
assert!(tracked <= MAX_TRACKED_KEYS, "tracked {tracked} keys");
}
#[test]
fn a_full_map_drops_the_key_with_the_oldest_window() {
let limiter = SignedCallLimiter::new(60, 1);
assert!(limiter.admit(b"oldest", 100));
assert!(limiter.admit(b"newer", 101));
for index in 0..(MAX_TRACKED_KEYS - 2) {
limiter.admit(&index.to_be_bytes(), 102);
}
assert!(limiter.admit(b"new", 103));
let state = limiter.state.lock().unwrap();
assert_eq!(state.windows.len(), MAX_TRACKED_KEYS);
assert!(!state.windows.contains_key(b"oldest".as_slice()));
assert!(state.windows.contains_key(b"newer".as_slice()));
}
#[test]
fn restarted_windows_do_not_grow_the_queue() {
let limiter = SignedCallLimiter::new(1, 1);
for now in 0..10_000 {
assert!(limiter.admit(b"a", now));
}
let state = limiter.state.lock().unwrap();
assert_eq!(state.windows.len(), 1);
assert!(state.starts.len() <= 2, "queue has {}", state.starts.len());
}
#[test]
fn eviction_skips_a_restarted_window() {
let limiter = SignedCallLimiter::new(60, 1);
assert!(limiter.admit(b"restarted", 0));
assert!(limiter.admit(b"oldest", 10));
// Leaves (0, "restarted") stale at the front of the queue.
assert!(limiter.admit(b"restarted", 70));
for index in 0..(MAX_TRACKED_KEYS - 2) {
limiter.admit(&index.to_be_bytes(), 71);
}
assert!(limiter.admit(b"new", 72));
let state = limiter.state.lock().unwrap();
assert!(state.windows.contains_key(b"restarted".as_slice()));
assert!(!state.windows.contains_key(b"oldest".as_slice()));
}
}