Skip to main content

taplimit

Lianes8 Certified

Small, typed, thread-safe in-process rate limiter: N calls per period, block or raise, sync or async, globally or per key.

You call an API that allows 15 requests a minute, a mail server that wants a pause between messages, or a scraper that must stay polite. taplimit keeps one process under that rate with one decorator, or a limiter object you share between functions, threads and coroutines. It has no dependencies, its clock and sleep are injectable so tests never wait, and a small command-line tool throttles lines in a shell pipeline.

Install

pip install taplimit

Quick start

Cap a function at N calls per period. By default a call over the limit waits until a slot frees:

from taplimit import rate_limit


@rate_limit(calls=15, period=60)
def call_api() -> str:
    return "ok"

Prefer to fail fast, or to wait only so long? Ask it to raise, or give a timeout:

from taplimit import RateLimitExceeded, rate_limit


@rate_limit(calls=15, period=60, on_limit="raise")
def call_api() -> str:
    return "ok"


@rate_limit(calls=15, period=60, timeout=5)  # waits up to 5 s, then raises
def call_other_api() -> str:
    return "ok"


try:
    call_api()
except RateLimitExceeded as exc:
    print(f"slow down, retry in {exc.retry_after:.1f}s")

async def functions work the same way, waiting with await instead of blocking:

@rate_limit(calls=10, period=1)
async def fetch(url: str) -> str:
    return url

Limit each user, host or token separately with key, which receives the call's arguments:

@rate_limit(calls=5, period=60, on_limit="raise", key=lambda user, message: user)
def send(user: str, message: str) -> None:
    print(f"to {user}: {message}")

The limiter object

Share one budget across several functions, threads and coroutines, or control slots by hand. A RateLimiter is a decorator, a context manager (sync and async), and exposes acquire, acquire_async and try_acquire:

from taplimit import RateLimiter

limiter = RateLimiter(calls=100, period=60)


@limiter
def read() -> None: ...


@limiter
def write() -> None: ...  # read and write draw on the same 100-per-minute budget


def do_work() -> None: ...


with limiter:  # guard a block of code
    do_work()

if limiter.try_acquire():  # never blocks; returns False when full
    do_work()

limiter.acquire(cost=10, timeout=2.5)  # take ten slots, wait at most 2.5 s
print(limiter.available(), limiter.retry_after())  # 88 0.0

KeyedRateLimiter gives every key its own window and forgets idle keys on its own:

from taplimit import KeyedRateLimiter

per_host: KeyedRateLimiter[str] = KeyedRateLimiter(calls=2, period=1)
per_host.acquire("example.com")

parse_rate turns a human string into arguments: RateLimiter(*parse_rate("100/min")).

Testing without real time

clock (returns seconds), sleep (waits seconds) and async_sleep (awaits seconds) are injectable, so a limiter runs instantly under a fake clock:

now = [0.0]


def fake_sleep(seconds: float) -> None:
    now[0] += seconds


limiter = RateLimiter(calls=1, period=10, clock=lambda: now[0], sleep=fake_sleep)
limiter.acquire()
limiter.acquire()  # "waits" ten seconds without sleeping
assert now[0] == 10.0

Command line

taplimit 5/s access.log                  # replay a log at five lines per second
tail -f app.log | taplimit 2/s           # follow a busy log without flooding
taplimit 30/min urls.txt | xargs -n1 curl -sO
journalctl -f | taplimit --drop 10/s     # keep ten lines per second, drop the rest

Lines pass through byte for byte. taplimit --help lists every option.

How it limits

taplimit keeps a sliding-window log: at every instant t, at most calls slots have a grant time in (t - period, t]. A slot frees exactly period seconds after the call that took it, so a burst of up to calls is allowed at once and the sustained rate is calls / period; nothing carries over a fixed boundary the way a reset-every-minute counter does. Waiting callers reserve their slot and are served first come, first served. All state is guarded by a lock, so one limiter is safe to share across threads and coroutines. The decisions are checked against the moving-window limiter of limits and the in-memory bucket of pyrate-limiter, which differ only at the boundary instant (the guide explains). The guide states every guarantee in detail.

Why

The simple niche of "let this function run at most N times per period, in one process" is oddly unserved:

  • ratelimit popularised the @limits(calls, period) shape and still had over 14 million downloads in the month to 16 October 2026, but its last release, 2.2.1, dates from December 2018. It counts calls in a fixed window that restarts once period has passed, so up to twice the limit can pass around a restart, and it has no asyncio support.
  • limits and pyrate-limiter are maintained and implement the same sliding-window log (and more), but they are built around pluggable storage backends such as Redis, Memcached or SQL databases, and using them means choosing a storage, a strategy and a rate object first.
  • limiter is a token-bucket library with a different rate / capacity API, not the plain calls-per-period shape.

taplimit is the small, typed take: one decorator, a sliding window, thread-safe and asyncio-aware, no dependencies, and a clock you can fake in tests. Reach for it when a single process needs to stay under a rate and a full rate-limiting backend would be too much.

Documentation

  • Guide: the algorithm, every guarantee, errors, threads and coroutines, keyed limits, testing and the command line.
  • Changelog, including what changed since 0.1.0.

License

MIT. See LICENSE.

Metadata

Release files for taplimit 1.0.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for taplimit 1.0.0
File Size Uploaded Provenance Actions
taplimit-1.0.0.tar.gz 74.8 kB Without provenance Details for taplimit-1.0.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for taplimit 1.0.0
File Interpreter ABI Platform Actions
taplimit-1.0.0-py3-none-any.whl Python 3 none any Details for taplimit-1.0.0-py3-none-any.whl

Total release size: 95.5 kB

Release files / taplimit-1.0.0.tar.gz

Download URL taplimit-1.0.0.tar.gz
Size 74.8 kB
Tags Source
SHA-256 checksum
How to use checksums
f474643a12954fc50d10b056b354637c6e47da952f4390ea518fc2d01dfa38d8
BLAKE2b-256 checksum
How to use checksums
11347372e005a294640d3cfeb235105f6671bda32b6abeb811ca83ce525f8115
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.13.2

Release files / taplimit-1.0.0-py3-none-any.whl

Download URL taplimit-1.0.0-py3-none-any.whl
Size 20.7 kB
Tags Python 3
SHA-256 checksum
How to use checksums
4fe5aaf0bc5c69a3ef7e0fb12b4ea922c349fda3f44b747ccdcb0e8b6c6088b4
BLAKE2b-256 checksum
How to use checksums
6bf5e9096cf83e1370be5671831302831c19cf82d0b66fe80798da74ee949a8b
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.13.2

Security for taplimit 1.0.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

1.0.0 This release

2 release files No provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page