peek: Check current rate limit state for a key (returns RateLimitState).
2) Example
from throttled import RateLimiterType, Throttled, utils
throttle = Throttled(
# 📈 Use Token Bucket algorithm
using=RateLimiterType.TOKEN_BUCKET.value,
# 🪣 Set quota: 1,000 tokens per second (limit), bucket size 1,000 (burst)
quota="1000/s burst 1000",
# 📁 By default, global MemoryStore is used as the storage backend.
)
def call_api() -> bool:
# 💧 Deduct 1 token for key="/ping"
result = throttle.limit("/ping", cost=1)
return result.limited
if __name__ == "__main__":
# 💻 Python 3.12.10, Linux 5.4.119-1-tlinux4-0009.1, Arch: x86_64, Specs: 2C4G.
# ✅ Total: 100000, 🕒 Latency: 0.0068 ms/op, 🚀 Throughput: 122513 req/s (--)
# ❌ Denied: 98000 requests
benchmark: utils.Benchmark = utils.Benchmark()
denied_num: int = sum(benchmark.serial(call_api, 100_000))
print(f"❌ Denied: {denied_num} requests")
3) Asynchronous
The core API is the same for synchronous and asynchronous code. Just replace from throttled import ... with from throttled.asyncio import ... in your code.
You can use the context manager to limit the code block. When access is allowed, return RateLimitResult.
If the limit is exceeded or the retry timeout is exceeded, it will raise LimitedError.
from throttled import Throttled, exceptions
def call_api():
print("doing something...")
throttle: Throttled = Throttled(key="/api/v1/users/", quota="1/m")
with throttle as rate_limit_result:
print(f"limited: {rate_limit_result.limited}")
call_api()
try:
with throttle:
call_api()
except exceptions.LimitedError as exc:
print(exc) # Rate limit exceeded: remaining=0, reset_after=60, retry_after=60
Wait & Retry
By default, rate limiting returns RateLimitResult immediately.
You can specify a timeout to enable wait-and-retry behavior. The rate limiter will wait according to the retry_after value in RateLimitState and retry automatically.
Returns the final RateLimitResult when the request is allowed or timeout reached.
from throttled import RateLimiterType, Throttled, utils
throttle = Throttled(
using=RateLimiterType.GCRA.value,
quota="100/s burst 100",
# ⏳ Set timeout=1 to enable wait-and-retry (max wait 1 second)
timeout=1,
)
def call_api() -> bool:
# ⬆️⏳ Function-level timeout overrides global timeout
result = throttle.limit("/ping", cost=1, timeout=1)
return result.limited
if __name__ == "__main__":
# 👇 The actual QPS is close to the preset quota (100 req/s):
# ✅ Total: 1000, 🕒 Latency: 35.8103 ms/op, 🚀 Throughput: 111 req/s (--)
# ❌ Denied: 8 requests
benchmark: utils.Benchmark = utils.Benchmark()
denied_num: int = sum(benchmark.concurrent(call_api, 1_000, workers=4))
print(f"❌ Denied: {denied_num} requests")
2) Storage Backends
Redis
You only need very simple configuration, and it supports connecting to Redis standalone, sentinel, and cluster modes.
The following example uses Redis as the storage backend, options supports all Redis configuration items, see RedisStore Options.
By default, a global MemoryStore instance with a maximum capacity of 1024 is used as the storage backend when no storage backend is specified. Therefore, it is usually not necessary to manually create a MemoryStore instance.
Different instances mean different storage spaces, if you want to throttle the same Key at different locations in your program, make sure that Throttled receives the same MemoryStore and uses a consistent Quota.
The following example uses memory as the storage backend and throttles the same Key on ping and pong:
Storage keys are namespaced under throttled by default - a key k limited by
the GCRA algorithm is stored as throttled:v1:gcra:k, where v1 versions the
stored state format.
Pass key_prefix to replace the throttled namespace with your own. It
must be a non-blank string and must not start or end with :. The schema
version and rate limiter type are still appended after the namespace, so a
stored-state format change or an algorithm switch never misreads existing keys:
ConnectionFactory is used to create and maintain ConnectionPool.
Automatically select via the server scheme by default. Standalone: "throttled.store.ConnectionFactory" Sentinel:"throttled.store.SentinelConnectionFactory" Cluster: "throttled.store.ClusterConnectionFactory"
Automatically select via the server scheme and sync/async mode by default. Sync(Standalone): "redis.connection.ConnectionPool" Async(Standalone): "redis.asyncio.connection.ConnectionPool" Sync(Sentinel): "redis.sentinel.SentinelConnectionPool" Async(Sentinel): "redis.asyncio.sentinel.SentinelConnectionPool" Cluster: "Disabled"
SENTINEL_CLASS
Sentinel import path.
Automatically select sync/async mode by default. Sync: "redis.Sentinel" Async: "redis.asyncio.Sentinel"
MemoryStore Options
MemoryStore is essentially a LRU Cache based on memory with expiration time.
Parameter
Description
Default
MAX_SIZE
Maximum capacity. When the number of stored key-value pairs exceeds MAX_SIZE, they will be eliminated according to the LRU policy.
1024
6) Exception
All exceptions inherit from throttled.exceptions.BaseThrottledError.
LimitedError
When a request is throttled, an exception is thrown, such as: Rate limit exceeded: remaining=0, reset_after=60, retry_after=60..
Field
Type
Description
rate_limit_result
RateLimitResult
The result after executing the RateLimiter for the given key.
DataError
Thrown when the parameter is invalid, such as: Invalid key: None, must be a non-empty key..
📊 Benchmarks
1) Test Environment
Python Version: 3.13.1 (CPython implementation)
Operating System: macOS Darwin 23.6.0 (ARM64 architecture)