Security python Intermediate

Rate Limiter Decorator for CLI Tools

Decorator that throttles function calls to N per second — useful for API clients.

python
import time, functools, threading

def rate_limit(calls: int, period: float = 1.0):
    lock = threading.Lock()
    times: list[float] = []

    def decorator(fn):
        @functools.wraps(fn)
        def wrapper(*args, **kwargs):
            with lock:
                now = time.time()
                times[:] = [t for t in times if now - t < period]
                if len(times) >= calls:
                    time.sleep(period - (now - times[0]))
                times.append(time.time())
            return fn(*args, **kwargs)
        return wrapper
    return decorator

@rate_limit(calls=5, period=1.0)
def call_api(endpoint: str): ...

Prerequisites

  • python >= 3.9

Pro Tips

  • → Use a token bucket for smoother bursting behaviour.

Was this module useful?

Share your experience — it helps the team improve.

Leave Feedback

Commercial Licensing

Acquire a production access token or template license for enterprise deployment.

Module Info

Language
python
Level
Intermediate
Read time
4 min
Published
Apr 2026
License
Commercial License

Newsletter

New modules every week, directly to your inbox.