Registry / http-networking / ratelimit

ratelimit

JSON →
library2.2.1pypypi✓ verified 27d ago

The `ratelimit` library provides a simple, yet powerful, API rate limiting decorator for Python functions. It allows developers to easily control the frequency at which a function can be called, preventing abuse or excessive resource consumption. Currently at version 2.2.1, it follows a stable release cadence, with updates primarily for bug fixes and compatibility.

pip install ratelimit
INSTALL
IMPORT
SIG · RATELIMIT
R
ratelimit
http-networkingpythonv2.2.1
Install
2.4s avg
Import
10ms
Disk
17MB
Pass rate
10/ 10
Env Coverage10 / 10
glibc
3.93.13
musl
3.93.13
Install & Compatibility
Where this runs
tested against v2.2.1 · pip install
no network on importno background threads
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
py 3.103.95 runs
installs and imports cleanly · install 0.0s · import 0.004s · 19.2MB
glibc
py 3.103.95 runs
installs and imports cleanly · install 2.4s · import 0.000s · 20MB
17MB installed
● package 17MB
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

limits
from ratelimit import limits
from ratelimit import ratelimit
The primary decorator was renamed from `ratelimit` to `limits` in version 2.0.
sleep_and_retry
from ratelimit import sleep_and_retry
RateLimitException
from ratelimit import RateLimitException

This example demonstrates how to apply a rate limit to a function using the `limits` decorator. The `sleep_and_retry` decorator automatically pauses execution until the rate limit period resets, preventing `RateLimitException` from being raised directly. If `sleep_and_retry` is omitted, you must manually catch `RateLimitException`.

import time from ratelimit import limits, sleep_and_retry, RateLimitException CALLS = 5 PERIOD = 10 # seconds @sleep_and_retry @limits(calls=CALLS, period=PERIOD) def call_mock_api(url): """Simulates an API call that is rate-limited.""" print(f"Calling API for {url} at {time.strftime('%X')}") # Simulate some work or actual API request return f"Response from {url}" if __name__ == "__main__": print(f"Limiting to {CALLS} calls per {PERIOD} seconds.\n") urls_to_fetch = [f"http://example.com/data/{i}" for i in range(10)] for url in urls_to_fetch: try: result = call_mock_api(url) # print(result) # Uncomment to see individual results except RateLimitException as e: print(f"Caught RateLimitException for {url}: {e}") # If sleep_and_retry wasn't used, this catch block would be essential. # With sleep_and_retry, this block might only be hit if something else fails. time.sleep(0.1) # Small delay to make output clearer print("\nFinished all simulated API calls.")
Debug
Known issues
breakingVersion 2.0 introduced significant breaking changes. The main decorator was renamed from `ratelimit` to `limits`, and its signature changed from positional arguments to keyword arguments (`calls`, `period`). The `enforce` argument was removed.
fix
Update decorator usage from `@ratelimit(N, S)` to `@limits(calls=N, period=S)`. Ensure `RateLimitException` is imported directly if catching.
affects: 1.x to 2.x
gotchaThe default in-memory storage for rate limits is not thread-safe or process-safe across multiple Python processes or distributed applications. If you run your application with multiple workers or on different machines, they will not share the same rate limit state.
fix
For distributed or multi-process environments, implement a custom storage backend (e.g., using Redis) by subclassing `ratelimit.BaseProxy` and passing an instance to the `limits` decorator's `rate_limiter` argument.
affects: All versions
gotchaWhile `ratelimit` works with `asyncio` applications, it is not inherently `async`/`await` native. The decorators are synchronous and will block the event loop if applied directly to `async def` functions, leading to reduced concurrency.
fix
For `async def` functions, wrap the rate-limited synchronous function call in `loop.run_in_executor()` or use an `async` native rate-limiting library. If the actual I/O within your `async` function is blocked by the synchronous decorator, consider refactoring.
affects: All versions
gotchaThe `sleep_and_retry` decorator handles `RateLimitException` for you. If you omit `@sleep_and_retry`, you *must* implement your own `try...except RateLimitException` block, otherwise, your application will crash when the limit is exceeded.
fix
Either always use `@sleep_and_retry` for automatic handling or explicitly wrap calls to rate-limited functions in `try...except RateLimitException` blocks to manage the error gracefully.
affects: All versions
Errors
Common errors & fixes
ModuleNotFoundError: No module named 'ratelimit'
The 'ratelimit' library has not been installed in your current Python environment.
fix
pip install ratelimit
TypeError: ratelimit() missing 2 required positional arguments: 'rate' and 'per'
The `@ratelimit` decorator was used without providing the mandatory `rate` (number of calls) and `per` (time period in seconds) arguments.
fix
from ratelimit import ratelimit

@ratelimit(rate=5, per=60) # Allow 5 calls per 60 seconds
def my_function():
    return "Hello"
NameError: name 'sleep_and_retry' is not defined
The `sleep_and_retry` decorator, which automatically retries a function call after hitting a rate limit, was not imported from its correct submodule.
fix
from ratelimit import ratelimit
from ratelimit.uses import sleep_and_retry

@sleep_and_retry
@ratelimit(rate=1, per=1) # Allow 1 call per second
def my_function_with_retry():
    return "Retrying hello"
ratelimit.exceptions.RateLimitException
A function decorated with `@ratelimit` was called more frequently than allowed by its configured rate limit, causing the exception to be raised.
fix
from ratelimit.exceptions import RateLimitException

try:
    # Call your rate-limited function here
    result = my_rate_limited_function()
except RateLimitException:
    print("Rate limit hit, please wait and retry after some time.")
Upgrade
Version history
2.2.1latest on PyPI · released Dec 17, 2018
Audit
Dependencies

No dependency data recorded yet.

Agent activity
18 hits · last 30 days
node
16
OpenAI (training)
1
Resources
ratelimit — pip install ratelimit · libregistry