In Rust, which std collection fits a sliding-window rate counter that appends new timestamps and expires old ones, and which methods do the work?
answer
- queue, not a stack
- both ends, one allocation
- peek before you remove
- front, pop_front, push_back
basics
~10 sUse std::collections::VecDeque: push_back each new timestamp, then pop_front while front() is older than the window. Both ends are amortised O(1), unlike Vec::remove(0), which shifts every remaining element.
solid answer
~40 sA rate counter is a FIFO queue: hits join at one end and expire at the other. `VecDeque<T>` is std's growable ring buffer, so `push_back` and `pop_front` are amortised O(1) and never shift elements. `front()` returns `Option<&T>` so you can compare the oldest timestamp before removing it, and `pop_front()` returns `Option<T>`, `None` when empty. The expire step is `while let Some(&t) = q.front() { if now - t < window { break } q.pop_front(); }`, or since Rust 1.93 `while q.pop_front_if(|t| now - *t >= window).is_some() {}`. A `Vec` would need `remove(0)`, which shifts every remaining element. `VecDeque` also indexes in O(1) and iterates oldest to newest.
code
rust · 33 linesuse std::collections::VecDeque;
/// Sliding-window rate counter: at most `limit` hits per `window_ms`.
struct RateCounter {
window_ms: u64,
limit: usize,
hits: VecDeque<u64>, // timestamps in ms, oldest at the front
}
impl RateCounter {
fn allow(&mut self, now_ms: u64) -> bool {
// Expire timestamps that fell out of the window.
while let Some(&oldest) = self.hits.front() {
if now_ms - oldest < self.window_ms {
break;
}
self.hits.pop_front();
}
if self.hits.len() < self.limit {
self.hits.push_back(now_ms);
true
} else {
false
}
}
}
fn main() {
let mut rc = RateCounter { window_ms: 1000, limit: 3, hits: VecDeque::new() };
for t in [0, 100, 200, 300, 1050, 1150] {
println!("t={t:>4} allowed={}", rc.allow(t));
}
}go deeper
Name VecDeque and the queue pair push_back and pop_front, and say pop_front returns an Option rather than panicking on an empty deque.
Explain the ring buffer: a head index that advances on pop_front, wrap-around at the end of the allocation, and amortised O(1) growth. Contrast with Vec::remove(0) shifting every element.
Mention the underflow trap on u64 timestamps, rejecting before pushing to bound memory per client, and pop_front_if from Rust 1.93 as the cleaner expire loop.
Treat the per-key deque as a memory budget: a limit of N hits costs N timestamps per active key, so the window and limit set the counter's footprint across all clients.
## The shape of the problem A **sliding-window rate counter** answers one question per request: how many hits arrived in the last `window` milliseconds? The usual design stores one timestamp per accepted hit. Every new hit is appended at the **newest** end; before deciding, the counter throws away every timestamp that has fallen out of the window, and those always sit at the **oldest** end. That is a **FIFO queue**: items enter at the back and leave at the front, in the order they arrived. In Rust the std type built for this is `std::collections::VecDeque<T>`, a **double-ended queue implemented with a growable ring buffer**. Its own documentation names the default queue usage: `push_back` to add and `pop_front` to remove. ## What a ring buffer buys you A `VecDeque` owns one heap allocation, like a `Vec`, plus a `head` index and a length. The logical first element lives at `buf[head]`, and the sequence may **wrap around** the end of the allocation and continue at slot 0. Consequences: - Removing from the front just advances `head`; nothing is shifted. - Adding at either end writes into a free slot next to the current run. - When the buffer is full, it grows by reallocating, so pushes are **amortised O(1)**, not O(1) on every call. - Indexing with `q[i]` or `q.get(i)` is O(1), because the index is translated through `head`. ## The methods that do the work | Method | Returns | Cost or note | |---|---|---| | `push_back(t)` | `()` | amortised O(1) | | `front()` | `Option<&T>` | O(1) | | `pop_front()` | `Option<T>`, `None` if empty | amortised O(1) | | `pop_front_if(pred)` | `Option<T>` | stable since Rust 1.93 | | `len()` | `usize` | O(1) | `front()` peeks at the oldest timestamp without removing it, which is exactly what the expire step needs: look, compare, and only then remove. ## Writing the expire loop The classic loop, valid on every Rust release: ```rust while let Some(&oldest) = hits.front() { if now_ms - oldest < window_ms { break; } hits.pop_front(); } ``` Since **Rust 1.93**, `VecDeque::pop_front_if` takes a predicate (`FnOnce(&mut T) -> bool`), removes and returns the front element only when the predicate says yes, and returns `None` when it says no or the deque is empty. The loop collapses to one line: ```rust while hits.pop_front_if(|t| now_ms - *t >= window_ms).is_some() {} ``` A full `allow` call then runs in three steps: 1. Expire every front timestamp older than the window. 2. Compare `hits.len()` with the limit. 3. If under the limit, `push_back(now_ms)` and accept; otherwise reject. ## Why not a Vec, or a LinkedList - **`Vec::remove(0)`** shifts every remaining element one slot left, so each expiry costs O(n). With thousands of timestamps per key and a hot path, that is real CPU. - **Reversing a Vec** so the oldest sits at the end makes expiry cheap but moves the cost to inserting at the front. - **`LinkedList`** also has O(1) operations at both ends, but pays one heap allocation per timestamp and walks scattered memory; std itself notes that `Vec` or `VecDeque` is almost always the better choice. ## Edge cases worth naming - `now_ms - oldest` on `u64` panics on underflow in a debug build and wraps in a release build if a timestamp ever runs ahead of `now_ms`; `saturating_sub` makes the arithmetic total. - For a strict cap on memory, check the limit before `push_back`, as above, so the deque never holds more than `limit` entries. - Iterating a `VecDeque` goes front to back, so `hits.iter()` lists timestamps oldest first — handy for debugging. ## Choosing the element type The deque does not care what it stores, so the timestamp type is a separate decision: - **`u64` milliseconds** from a clock you pass in keeps the counter pure and trivially testable, as in the example. - **`std::time::Instant`** reads the monotonic clock directly and is immune to wall-clock jumps; compare with `now.duration_since(oldest) < window`. - **One counter per key** usually lives in a `HashMap<Key, VecDeque<u64>>`; the deque is the per-key part, the map is a separate subject. Whichever you pick, the queue discipline stays the same: oldest at the front, newest at the back, and the expire step only ever looks at `front()`.
- Why compare with front() before calling pop_front(), instead of popping and pushing back?Popping first removes the timestamp even when it is still inside the window, and putting it back with `push_front` is extra work and easy to get wrong. `front()` returns `Option<&T>`, a borrow you can inspect for free, so the loop only removes what has really expired. Since Rust 1.93, `pop_front_if` packages the same look-then-remove step in one call.
- How would you cap the counter's memory so one noisy client cannot grow its deque without bound?Check `len()` against the limit before `push_back` and reject instead of storing, so the deque never holds more than `limit` timestamps. `VecDeque::with_capacity(limit)` preallocates that much space up front. If you keep the newest N samples instead of rejecting, `truncate` keeps the front N, while `retain_back(n)`, stable since Rust 1.99, keeps the last N.
- Use a Vec and call remove(0) to expire the oldest timestamp.
- pop_front panics when the deque is empty.
- VecDeque is a linked list, so indexing it is O(n).
- push_back is O(1) on every single call, with no reallocation ever.
- A BinaryHeap is needed because timestamps must be sorted.
Assumes Rust 1.99; VecDeque::pop_front_if and pop_back_if are stable since Rust 1.93, the front()/pop_front() loop works on every release.