Implement a per-user token bucket rate limiter
Role: Software Engineer
Category: Software Engineering Fundamentals
Difficulty: medium
Interview Round: Other
Design a rate-limiting system that follows the *token-bucket* algorithm.
You are given a class `TokenBucket` with the following behavior:
- `capacity` is the maximum number of tokens that can be stored in the bucket.
- `refill_rate` is the (possibly fractional) number of tokens added to the bucket every second.
- Each user has an independent bucket identified by their `user_id`. A user seen for the first time starts with a full bucket.
A request consumes a specified number of tokens. A request is allowed if, after refilling up to the current time, the user's bucket still contains at least that many tokens.
Implement the following methods:
- `TokenBucket(capacity = 5, refill_rate = 1)`: initialize the data structure. Both arguments are optional; the defaults are shown.
- `canRequest(user_id: string, required_tokens = 1) -> boolean`: return `true` and deduct `required_tokens` if the user currently has enough tokens; otherwise return `false` and remove no tokens.
- `availableTokens(user_id: string) -> int`: return the integer number of full tokens the user has at this moment.
Example with the default settings, where all calls happen within a few milliseconds of each other:
```text
Input:
["TokenBucket", "canRequest", "availableTokens", "canRequest", "availableTokens"]
[[], ["123"], ["123"], ["123", 5], ["123"]]
Output:
[null, true, 4, false, 4]
Explanation:
tb = TokenBucket() # capacity = 5, refill_rate = 1
tb.canRequest("123") # true: a new user starts at 5, the request takes 1, leaving 4
tb.availableTokens("123") # 4: a few milliseconds of refill add only a fraction, which is truncated
tb.canRequest("123", 5) # false: only 4 full tokens are available
tb.availableTokens("123") # 4: the denied request removed nothing
```
```hint Where refill happens
You do not need a timer that adds tokens in the background. Think about what you can work out from the time a user's bucket was last updated.
```
```hint Fractional tokens
With a fractional refill rate the balance is rarely a whole number. Make sure canRequest and availableTokens agree when the balance sits right at an integer.
```
### Constraints & Assumptions
- `1 <= capacity <= 10^3`
- `0 < refill_rate <= 10^3`
- Up to `10^5` total calls to `canRequest` and `availableTokens`.
- `user_id` is a non-empty ASCII string of at most 64 characters.
- Methods are called in real time. Two successive calls can happen at the same instant, and time never goes backward between them.
### Clarifying Questions to Ask
- Can `required_tokens` exceed `capacity`, and should such a request simply be denied?
- Is `required_tokens` always a positive integer, or can it be zero or fractional?
- Will several threads call the limiter at once?
- Should state for users who stop sending requests be dropped at some point, or can it live for the life of the process?
### What a Strong Answer Covers
- How the balance is brought up to date from elapsed time on each call, and how the capacity cap is applied.
- Per-user state, including what a first-time user starts with.
- Check-then-deduct behavior: a denied request leaves the balance untouched, and both methods treat fractional balances the same way.
- The clock source, and thread safety when calls arrive concurrently.
- Time and space cost per call, and how memory grows with the number of users.
### Follow-up Questions
- How would you unit test this class without calling `sleep`?
- With many threads, one global lock becomes a bottleneck. How would you reduce contention?
- How would you evict idle users without changing any user's observable behavior?
- How would the design change if the buckets lived in Redis and were shared by many application servers?
Overview: Implement a per-user token bucket rate limiter with a fixed capacity and a possibly fractional refill rate, exposing a check-and-deduct request method and a count of whole tokens left. It tests lazy refill from elapsed time, the capacity cap, floating-point edge cases and thread safety.