~learn.
0:00 / 1:09
LLD · Rate limiter

Your rate limiter test waits a whole minute. It shouldn't.

transcript

Your rate limiter test just waited a whole minute. It should take microseconds.

Every algorithm here depends on time. So where does time come from? Read the system clock inside, and proving a refill means sleeping. Proving a 60 second reset means waiting a minute. So pass the clock in. A fake one in tests. Advance it, assert.

Free search gets 5 tokens, refilled 5 a second. A burst of 7. 5 allowed. Calls 6 and 7? Denied. Advance the fake clock half a second. 2 point 5 tokens come back. Next 3 calls: allowed, allowed, denied. No sleeping. Instant.

But here's the sneaky one. After a clock correction, wall time can jump backwards. Negative elapsed time. A bucket hands out tokens it doesn't have. So production uses a monotonic clock. It never goes back.

Monotonic in production. Fake in tests. Same output, every run. Time is a dependency. Inject it, like any other.

Full breakdown in the lecture.