2

I writing an app based on the asyncio framework. This app interacts with an API that has a rate limit(maximum 2 calls per sec). So I moved methods which interact with an API to the celery for using it as rate limiter. But it is looks like as an overhead.

There are any ways to create a new asyncio event loop(or something else) that guarantees execution of a coroutins not more then n per second?

2 Answers 2

9

The accepted answer is accurate. Note however that, usually, one would want to get as close to 2QPS as possible. This method doesn't offer any parallelisation, which could be a problem if make_io_call() takes longer than a second to execute. A better solution would be to pass a semaphore to make_io_call, that it can use to know whether it can start executing or not.

Here is such an implementation: RateLimitingSemaphore will only release its context once the rate limit drops below the requirement.

import asyncio
from collections import deque
from datetime import datetime

class RateLimitingSemaphore:
    def __init__(self, qps_limit, loop=None):
        self.loop = loop or asyncio.get_event_loop()
        self.qps_limit = qps_limit

        # The number of calls that are queued up, waiting for their turn.
        self.queued_calls = 0

        # The times of the last N executions, where N=qps_limit - this should allow us to calculate the QPS within the
        # last ~ second. Note that this also allows us to schedule the first N executions immediately.
        self.call_times = deque()

    async def __aenter__(self):
        self.queued_calls += 1
        while True:
            cur_rate = 0
            if len(self.call_times) == self.qps_limit:
                cur_rate = len(self.call_times) / (self.loop.time() - self.call_times[0])
            if cur_rate < self.qps_limit:
                break
            interval = 1. / self.qps_limit
            elapsed_time = self.loop.time() - self.call_times[-1]
            await asyncio.sleep(self.queued_calls * interval - elapsed_time)
        self.queued_calls -= 1

        if len(self.call_times) == self.qps_limit:
            self.call_times.popleft()
        self.call_times.append(self.loop.time())

    async def __aexit__(self, exc_type, exc, tb):
        pass


async def test(qps):
    executions = 0
    async def io_operation(semaphore):
        async with semaphore:
            nonlocal executions
            executions += 1

    semaphore = RateLimitingSemaphore(qps)
    start = datetime.now()
    await asyncio.wait([io_operation(semaphore) for i in range(5*qps)])
    dt = (datetime.now() - start).total_seconds()
    print('Desired QPS:', qps, 'Achieved QPS:', executions / dt)

if __name__ == "__main__":
    asyncio.get_event_loop().run_until_complete(test(100))
    asyncio.get_event_loop().close()

Will print Desired QPS: 100 Achieved QPS: 99.82723898022084

5
  • Note that this impl can raise ZeroDivisionError when qps is set to 1. Caused by the following line: cur_rate = len(self.call_times) / (self.loop.time() - self.call_times[0]) where similar return values from self.loop.time() and self.call_times[0] cause division by zero. @Chris, what's the intended behavior in this case? Apr 4, 2018 at 18:31
  • @JaanusVarus that is a bit strange. For self.loop.time() to be equal to the last call time, it would mean that the semaphore was entered twice in the same microsecond - which is impossible. Replacing 100 for 1 in the example above give me Desired QPS: 1 Achieved QPS: 0.9989469101673017. Could you confirm whether you get ZeroDivisionError when replacing 100 for 1 in the example above>
    – Chris
    Apr 5, 2018 at 22:53
  • I found it weird as well. When I run the following script: pastebin.com/2Tsrah9N, I will get the following output: pastebin.com/ABVZLzus. Note that I am using Python 3.6.5 (64-bit) on Windows Apr 6, 2018 at 8:52
  • I think this is a windows specific issue - from the documentation: The resolution of the monotonic clock on Windows is usually around 15.6 msec. The best resolution is 0.5 msec. The resolution depends on the hardware (availability of HPET) and on the Windows configuration. See asyncio delayed calls.
    – Chris
    Apr 8, 2018 at 8:46
  • To get around this, you could consider adding a small value to the denominator, or special casing self.loop.time() == self.call_times[0] to calculate interval in a different way.
    – Chris
    Apr 8, 2018 at 8:49
4

I believe you are able to write a cycle like this:

while True:
    t0 = loop.time()
    await make_io_call()
    dt = loop.time() - t0
    if dt < 0.5:
        await asyncio.sleep(0.5 - dt, loop=loop)
3
  • Thanks! I made a decorator using this way while a waiting an answer. It seems as this is a single proper approach do this. This is true? Jul 31, 2016 at 15:09
  • What do you mean by "single proper approach"? For me it's the simplest and the most obvious way to solve the issue but I can invite a dozen of overcomplicated solutions. Jul 31, 2016 at 19:29
  • It's exactly what I want to hear :) Thanks Jul 31, 2016 at 20:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.