The `token-bucket` package provides a very fast implementation of the token bucket algorithm, suitable for rate limiting in web applications. It manages bucket state internally without requiring a separate timer thread, allowing for controlled bursts while maintaining a consistent average rate. The current version is 0.3.0, and releases appear to be infrequent, focusing on stability and core algorithm improvements.
pip install token-bucketVerified import paths — ran on the pinned version, not inferred.
Initialize a `TokenBucket` with a `capacity` and `rate` (tokens per second). Use the `consume()` method to attempt to acquire tokens. It returns `True` if tokens are successfully acquired, `False` otherwise. The bucket automatically replenishes tokens based on the elapsed time since the last operation, up to its capacity.
Ensure your project runs on Python 3.5+; if not, upgrade Python or pin `token-bucket` to version 0.2.x.
For distributed systems, consider integrating with an external store like Redis or exploring libraries like `token-throttler` or `bucketflow` that offer distributed backend support.
Upgrade to version 0.3.0 or later to ensure accurate rate limiting when `rate` is less than 1.0 token per second.