Skip to main content

Practice ยท 1 of 1

RateLimitedClient

Implement class RateLimitedClient: 1. __init__(self, max_concurrent=2) โ€” create an asyncio.Saphore-guarded limit (use asyncio.Semaphore) and an in_flight counter of requests currently inside the critical section. 2. async def request(self, name, delay, fail=False) โ€” acquires the semaphore, increments in_flight, sleeps delay, raises RuntimeError(f'{name} failed') when fail=True, returns f'{name}:ok', and ALWAYS decrements in_flight (success, failure, or cancellation). 3. async def run_all(self, specs, per_request_timeout=None) โ€” runs all (name, delay, fail) specs concurrently in one TaskGroup; with per_request_timeout set, each request is bounded and its slot receives f'timeout:{per_request_timeout}' instead of raising. Determinism checks: in_flight never exceeds max_concurrent (sampled via a wrapped sleep), and all results come back positionally.

Difficulty: advanced

Back to lesson: Practice: Project: High-Concurrency Async Service