Thread-Safe Blocking Sliding-Window Rate Limiter in Python
Company: DRW
Role: Software Engineer
Category: Software Engineering Fundamentals
Difficulty: hard
Interview Round: Technical Screen
Implement a rate limiter for outgoing sends: at most `limit` sends may happen within any `window` seconds. When a send would exceed the limit, the caller is not rejected; it waits until sending is allowed and then sends. Once the single-threaded version works, several clients share one limiter from different threads.
```python
class RateLimiter:
def __init__(self, limit: int, window: float): ...
def acquire(self) -> None:
"""Block until one more send is allowed, record it, and return; the caller then sends."""
```
For example, with `limit = 2` and `window = 1.0`, calls made at times 0.0, 0.25 and 0.5 return at 0.0, 0.25 and 1.0: the third call has to wait until the send at time 0.0 has left the window.
### Clarifying Questions
- Does a send made exactly `window` seconds ago still count against the limit?
- Which clock should measure time, and how should the code be tested without really sleeping?
- With several clients, is the limit shared by all of them or applied to each client separately?
- Must waiting callers be served in arrival order, or is any order acceptable?
- Should `acquire` support a timeout or cancellation?
### Part 1 — Single-threaded limiter
Implement `RateLimiter` for one caller: `acquire` returns immediately while the limit allows it; otherwise it sleeps exactly as long as needed and then records the send.
```hint What to remember
Decide what the limiter must remember about past sends to answer "may I send now?", and at what moment each record stops mattering.
```
```hint Compute, do not poll
When the limit is reached, the earliest moment the next send becomes legal is already determined by the state you keep.
```
#### What This Part Should Cover
- The state kept per send and when old entries are discarded
- The exact wait time, and the boundary rule for a send exactly one window old
- The choice of clock, the amortized cost per call, and memory in terms of `limit`
### Part 2 — Many clients, one limiter
Several client threads now call `acquire` on the same limiter at the same time, and together they must never exceed the limit.
```hint Where the waiting happens
Consider what every other thread can do while one thread is waiting for its turn, and what may have changed by the time it wakes up.
```
#### What This Part Should Cover
- The critical section: discarding, checking and recording as one atomic step
- How a thread waits without stalling the others, and what it must do after waking
- Fairness between waiting threads, and how to guarantee arrival order if required
### What a Strong Answer Covers
- Correct sliding-window semantics, with never more than `limit` sends in any window
- Waiting time computed from the stored state rather than by busy polling
- A race-free multi-threaded version with a short critical section
- Testability through an injectable clock and sleep function
- Edge cases: invalid parameters, a burst after an idle period, clock adjustments
### Follow-up Questions
- Storing one timestamp per send costs memory proportional to `limit`. What would you use for a limit of a million sends per hour, and what accuracy would you give up?
- How would you support a separate limit for each of thousands of clients, including cleanup of idle ones?
- How would you enforce one limit across several processes or machines?
- How would the design change for an `asyncio` client instead of threads?
Overview: Implement a rate limiter that allows at most a given number of sends in any sliding time window and makes callers wait rather than fail when the limit is reached. Then make it safe for many client threads sharing one limiter, covering race conditions, how and where callers wait, fairness and testability.
Read the full DRW Software Engineer interview experience this question came from