113. Throttling API Requests
1. Using asyncio for Throttling API Requests
asyncio for Throttling API Requestsimport asyncio
import aiohttp
import time
# Define the maximum number of concurrent requests
CONCURRENT_REQUESTS = 5
async def fetch(session, url):
async with session.get(url) as response:
return await response.text()
async def throttled_fetch(sem, session, url):
async with sem: # Acquire a semaphore
print(f"Fetching {url}")
return await fetch(session, url)
async def main():
urls = [f"https://jsonplaceholder.typicode.com/posts/{i}" for i in range(1, 21)]
sem = asyncio.Semaphore(CONCURRENT_REQUESTS) # Throttle to 5 concurrent requests
async with aiohttp.ClientSession() as session:
tasks = [throttled_fetch(sem, session, url) for url in urls]
results = await asyncio.gather(*tasks)
print(f"Fetched {len(results)} responses")
start = time.time()
asyncio.run(main())
print(f"Completed in {time.time() - start:.2f} seconds")2. Using asyncio.sleep for Time-Based Throttling
asyncio.sleep for Time-Based Throttling3. Using threading for Throttling API Requests
threading for Throttling API Requests4. Using Token Bucket Algorithm with asyncio
asyncio5. Rate-Limiting with aiolimiter
aiolimiterSummary of Techniques:
Last updated