I've created code to call the Page Speed Insights API.
The build_cwv_data is an async coroutine that calls the api and retrieves and processes json data for a particular URL.
According to the documentation the API has a limit of 400 requests per 100 seconds. And interestingly it is at around the 100 second mark that the API starts returning a 409 error status code (quota exceeded)
My code is doing approximately 775 calls in 100 seconds.
I don't understand how it is making so many calls in that time period as I have added sleep delays to try to slow it down.
Firstly, why is it still so fast? What can I do to slow it down?
async def retrieve_cwv_data(urls_list):
site_id = 10234
tasks = []
rate_limit = 2 # maximum number of API calls per second
interval = 1 / rate_limit # interval between API calls in seconds
count = 0
start_time = time.monotonic() # initial start time
for url in urls_list:
task1 = asyncio.ensure_future(build_cwv_data(site_id, url, 'mobile', psi_key))
task2 = asyncio.ensure_future(build_cwv_data(site_id, url, 'desktop', psi_key))
tasks.append(task1)
tasks.append(task2)
count += 2
if count >= rate_limit * 2:
elapsed_time = time.monotonic() - start_time
if elapsed_time < interval:
# introduce delay to stay within the rate limit
await asyncio.sleep(interval - elapsed_time)
# reset count and start time for the next second
count = 0
start_time = time.monotonic()
results = await asyncio.gather(*tasks)
tmp_list = []
for result in results:
tmp_list.append(result)
return tmp_list```