Skip to main content

Testable Rate Limiter

Challenge on lesson: Checkpoint: Testing

Design a rate limiter around a Clock seam in Solution: - interface Clock { long nowMillis(); } - static class RateLimiter with constructor (Clock clock, int maxPerWindow) and boolean allow(String key): - counts calls per key within a 1000ms rolling window (from the clock) - returns true if under the limit, false otherwise - calls OLDER than 1000ms (strictly) no longer count - static Clock manualClock(long startMillis) returns a mutable-ish clock advanced by calling ((Solution.AdvanceableClock) c).advance(ms) — define static interface AdvanceableClock extends Clock with void advance(long ms). The tests drive time explicitly — no sleeps.

Difficulty: intermediate

Back to lesson: Checkpoint: Testing