← All Exercises

Asyncio Rate Limiting with Semaphore

advancedpython~30min

Background

Semaphores bound in-flight work without creating a thread per request; asyncio.gather returns results in the order of the awaitables, not completion order.

Problem

Implement run_jobs(durations, limit) that runs one coroutine per duration, allows at most limit jobs inside the semaphore at once, returns result values index*10 in input order, and reports the peak observed concurrency. Validate that limit is positive.

Input

A list of simulated job durations in seconds and a positive concurrency limit.

Output

A tuple of result values in input order and the peak number of jobs that ran concurrently.

Sample tests

Sample 1

Input: durations = [0.01, 0.01, 0.01, 0.01], limit = 2
Expected: ([0, 10, 20, 30], 2)

Sample 2

Input: durations = [0.01, 0.01], limit = 1
Expected: ([0, 10], 1)

Your solution

Learning objective

Apply semaphores for async backpressure and measure actual concurrency safely.