Skip to content

Variable rate metric, or limit by request payload size instead of number of requests #181

Answered by mjpieters
Rassibassi asked this question in Q&A
Discussion options

You must be logged in to vote

You can rate limit any amount per minute, just acquire a different amount by awaiting on limiter.acquire(<amount>)

async def task(id: int, limiter: AsyncLimiter, payload_size: float):
    """Simulate a task that requires rate limiting with variable payload."""
    await limiter.acquire(payload_size)
    print(f"Task {id} with payload {payload_size} is running.")
    await asyncio.sleep(1)  # Simulate an I/O-bound task.

The async with limiter: syntax is just syntactic sugar for await limiter.aquire(1) here.

If you really must have a context manager for your use-case, just create a simple utility context manager; it doesn't have to be a method on the class at all:

import typing as t
from co…

Replies: 2 comments 2 replies

Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
2 replies
@Rassibassi
Comment options

@mjpieters
Comment options

Answer selected by Rassibassi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants
Converted from issue

This discussion was converted from issue #169 on November 04, 2023 18:20.