Search RU
Tasks / Concurrency / Thread-safe token bucket
Statement easy

Thread-safe token bucket

Implement a thread-safe `TokenBucket(rate, capacity, clock=None)`.

`rate` is how many tokens are added per second, `capacity` is the maximum number
of tokens in the bucket. `clock` is a zero-argument function returning time in
seconds; it defaults to `time.monotonic`. Tests replace the clock, so no `sleep`
is needed.

Rules:

- the bucket starts full: `capacity` tokens;
- `rate` is a finite number greater than zero, otherwise `ValueError`;
- `capacity` is an integer `>= 1`, otherwise `ValueError`; `bool` is not a
number;
- `allow(cost=1)` returns `True` when enough tokens are available and consumes
them;
- otherwise it returns `False` and consumes nothing;
- `cost` is an integer `>= 1`, otherwise `ValueError`;
- refill is continuous: over `dt` seconds `rate * dt` tokens are added, capped at
`capacity`;
- the boundary is inclusive: exactly `cost` tokens is a success;
- if the clock goes backwards, nothing is refilled;
- `allow` is called from multiple threads: no extra tokens are granted and no
consumption is lost.

Example: `TokenBucket(rate=2, capacity=2)`; two `allow()` calls in a row return
`True`, a third one without moving the clock returns `False`; after `0.5`
seconds it returns `True` again.

Python
concurrencyrate-limittoken-bucketthreadsclock
solution.py Python 3.14
AI mentor

The AI mentor is available after you log in: it sees your attempt history and does not spend resources on anonymous requests.

Log in and ask
Hints 1 of 3 unlocked · attempts: 0
Hint 1

Which part must be atomic: the refill, the balance check, or the consumption? And
why do the tests not need `sleep`?

Hint 2 — unlocks after 1 attempt
Hint 3 — unlocks after 3 attempts