aiolimiter: Asyncio Rate Limiter

1.2.1 · active · verified Thu Apr 09

aiolimiter is an asyncio-compatible rate limiter library for Python, implementing a leaky bucket algorithm. It allows controlling the rate at which concurrent operations can acquire permits, preventing resource exhaustion or API overuse. The current version is 1.2.1, and it maintains a steady release cadence for bug fixes and minor enhancements.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to initialize `AsyncLimiter` and use it to control the rate of operations. It shows both the `async with` context manager for single-permit acquisition and the explicit `await limiter.acquire(count)` method for multiple permits.

import asyncio
from aiolimiter import AsyncLimiter

async def main():
    # Initialize a limiter for 5 permits per second
    limiter = AsyncLimiter(5, 1) 

    print("Attempting to acquire 3 permits...")
    async with limiter:
        await limiter.acquire(2) # Acquire 2 permits within the context manager
        print("Acquired 3 permits (1 from 'async with', 2 from 'acquire')!")

    print("Attempting to acquire 1 permit without context manager...")
    await limiter.acquire(1)
    print("Acquired 1 permit!")

    # Demonstrate waiting if limit is reached
    print("Acquiring 5 permits, might wait...")
    for _ in range(5):
        await limiter.acquire(1)
        print(f"Permit {_+1} acquired.")

asyncio.run(main())

view raw JSON →