Token throttler is an extendable rate-limiting library for Python, somewhat based on the token bucket algorithm. It supports both blocking (sync) and non-blocking (async) operations, global and instance-specific configurations, and various storage backends including in-memory and Redis. The current version is 1.5.1, actively maintained with regular updates.
pip install token-throttlerVerified import paths — ran on the pinned version, not inferred.
This quickstart demonstrates initializing `TokenThrottler` with `RuntimeStorage` and adding a basic `TokenBucket`. It then simulates several API calls, showing how to consume tokens and handle rate limits. It also includes an example of consuming tokens with a custom cost.
Configure global settings using `default_config.set()` *before* initializing any `TokenThrottler` instances. For instance-specific overrides, pass a `ThrottlerConfig` object to the `TokenThrottler` constructor instead.
Set `ENABLE_THREAD_LOCK=True` in your `ThrottlerConfig` (globally or per instance) to enable a thread lock for the `consume` method, preventing race conditions. Be aware this incurs a slight performance cost.
Ensure all identifiers used in `consume` have a corresponding `TokenBucket` added via `throttler.add_bucket()`. Alternatively, set `IDENTIFIER_FAIL_SAFE=True` in `ThrottlerConfig` to make unknown identifiers act as limitless buckets, preventing `KeyError`.
Before calling `throttler.consume('my_id')`, ensure you've called `throttler.add_bucket('my_id', TokenBucket(max_tokens=X, replenish_time=Y))` or set `IDENTIFIER_FAIL_SAFE=True` in the throttler's `ThrottlerConfig`.Perform all modifications to `default_config` at the very start of your application, before any `TokenThrottler` instances are initialized. For dynamic configuration, use instance-specific `ThrottlerConfig` objects when creating `TokenThrottler` instances.
Review your `TokenBucket` configurations. `max_tokens` determines burst capacity, `replenish_time` determines the rate at which tokens are refilled. Also, check the `cost` parameter in `consume()` calls. For multi-threaded scenarios, consider enabling `ENABLE_THREAD_LOCK=True` in your `ThrottlerConfig` to prevent token overconsumption due to race conditions.