Async URL Batch Fetcher with Concurrency Limits
Data Structure DesignModel answerLast updated
Build an async function that fetches a list of URLs with bounded parallelism, deduplicates identical URLs, preserves input order, and isolates per-URL errors.
Background
Networked applications often need to load data from many endpoints at once. Firing all requests simultaneously can overwhelm the remote server or exhaust local file descriptors, but processing them one at a time is unnecessarily slow. A well-designed fetcher lets you dial in a concurrency cap, skip redundant network calls for repeated URLs, and surface per-request failures without aborting the whole batch.
Task
Implement the async function fetch_urls below.
from typing import Any, Awaitable, Callable, Dict, List
async def fetch_urls(
urls: List[str],
fetch_fn: Callable[[str], Awaitable[str]],
max_concurrency: int = 3
) -> List[Dict[str, Any]]:
"""
Download content for every URL in `urls`, subject to the rules below.
Each element of the returned list corresponds to the URL at the same
index in the input and has the shape:
{
"url": str,
"status": "success" | "error",
"data": str | None,
"error": str | None
}
"""
pass
Rules
- Bounded concurrency. No more than
max_concurrencycalls tofetch_fnmay be running at the same time. Whenmax_concurrency == 1the calls run one after another. - Single fetch per unique URL. If the same URL appears more than once,
fetch_fnis called for it exactly once. Every occurrence in the output reflects the same result. - Input order in output. The returned list has the same length as
urlsand each position matches the corresponding input URL. - Per-request error containment. When
fetch_fnraises an exception for a URL, record the error in that URL's result object and continue processing the remaining URLs normally.
Constraints
0 <= len(urls) <= 10,0001 <= max_concurrency <= 100fetch_fnaccepts a URL string and either returns a string payload or raises anException.- Memory use should grow with the number of unique URLs and results, not with the raw length of the input.
Example
urls = [
"https://api.example.com/1",
"https://api.example.com/2",
"https://api.example.com/1", # duplicate
]
max_concurrency = 2
# fetch_fn("https://api.example.com/1") → "data 1"
# fetch_fn("https://api.example.com/2") → raises ConnectionError("Timeout")
# Expected output:
[
{"url": "https://api.example.com/1", "status": "success", "data": "data 1", "error": None},
{"url": "https://api.example.com/2", "status": "error", "data": None, "error": "Timeout"},
{"url": "https://api.example.com/1", "status": "success", "data": "data 1", "error": None},
]
# fetch_fn was called exactly twice.
What to address in your answer
- The overall approach and how each requirement maps to a concrete mechanism.
- Time and space complexity.
- Edge cases: empty input, all-identical URLs,
max_concurrencylarger than the unique URL count, all successes, all failures. - At least one meaningful follow-up extension and how you would approach it.
Hints
Hint 1
Separate the problem into three independent concerns before writing any code: deduplication, concurrency control, and order restoration. Solve each one individually, then compose them.
Hint 2
For concurrency control, consider spawning exactly min(max_concurrency, unique_url_count) worker coroutines that all pull from a shared iterator. Because asyncio is single-threaded and a plain iterator yields synchronously, no two workers can receive the same URL.
Hint 3
Catch Exception rather than BaseException inside each worker. In Python 3.8+, asyncio.CancelledError is a BaseException, so catching only Exception lets cancellation propagate correctly while still recording every ordinary request failure.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Three requirements — deduplication, concurrency control, and order preservation — map cleanly to three separate mechanisms. Keep them decoupled so each can be reasoned about independently.
1. Deduplication
unique_urls = list(dict.fromkeys(urls))
dict.fromkeys runs in O(n) and preserves first-occurrence order, so the relative ordering among unique URLs stays stable. Every URL in unique_urls will be fetched exactly once; duplicates in the original input never touch the network.
2. Concurrency control via a worker pool
Spawn k = min(max_concurrency, len(unique_urls)) worker coroutines. All of them pull from one shared iterator over unique_urls. Because asyncio is single-threaded and Python's iterator protocol is synchronous, two workers can never receive the same URL. Each worker awaits one fetch, records the result, then immediately asks the iterator for the next URL.
This is preferable to the semaphore-per-task pattern (asyncio.gather with Semaphore), which would create up to 10,000 coroutines all sitting in memory waiting for a semaphore slot. With the worker pool, only k ≤ max_concurrency coroutines ever exist.
3. Error isolation
The try/except lives inside the worker's loop, not outside it. A failure only affects that URL's record; the worker continues to the next URL and asyncio.gather never sees the exception.
Catch Exception, not BaseException. Since Python 3.8, asyncio.CancelledError inherits from BaseException, so catching Exception lets a cancellation signal propagate to the caller instead of being silently swallowed as a failed URL.
4. Order restoration
Store results in a url → result dict as workers complete. Once all workers finish, walk the original urls list to build the output. Completion order is irrelevant; the final pass restores exact input order, including all duplicates.
Return a shallow copy of each result dict (dict(results[url])) so that callers mutating one copy don't corrupt the others.
Complete implementation
import asyncio
from typing import Any, Awaitable, Callable, Dict, List
async def fetch_urls(
urls: List[str],
fetch_fn: Callable[[str], Awaitable[str]],
max_concurrency: int = 3,
) -> List[Dict[str, Any]]:
if not urls:
return []
if max_concurrency < 1:
raise ValueError("max_concurrency must be >= 1")
# Step 1: unique URLs in first-occurrence order
unique_urls = list(dict.fromkeys(urls))
results: Dict[str, Dict[str, Any]] = {}
# Step 2: shared iterator — synchronous next(), safe without a lock
url_iter = iter(unique_urls)
async def worker() -> None:
for url in url_iter:
try:
data = await fetch_fn(url)
results[url] = {
"url": url,
"status": "success",
"data": data,
"error": None,
}
except Exception as exc:
# CancelledError (BaseException) is intentionally not caught here
results[url] = {
"url": url,
"status": "error",
"data": None,
"error": str(exc) or type(exc).__name__,
}
num_workers = min(max_concurrency, len(unique_urls))
await asyncio.gather(*(worker() for _ in range(num_workers)))
# Step 3: restore original order; copy each dict to avoid shared mutation
return [dict(results[url]) for url in urls]
Walkthrough of the example
unique_urls = [url1, url2], so two workers start. Worker A pulls url1, awaits fetch_fn, records status: "success", data: "data 1". Worker B pulls url2, fetch_fn raises ConnectionError("Timeout"), records status: "error", error: "Timeout". The iterator is now exhausted and both workers exit. The output pass maps [url1, url2, url1] to [success, error, success]. fetch_fn was called exactly twice.
Complexity
Let n = len(urls), u = unique URLs, c = max_concurrency.
- Time: O(n) for deduplication and output assembly, plus
ucalls tofetch_fn. Wall-clock time is roughly⌈u / c⌉ × Lwhere L is average fetch latency. - Space: O(u) for the unique list and results map, O(n) for the output list, O(min(c, u)) coroutine frames. This satisfies the "proportional to unique URLs" constraint.
Edge cases
| Case | Behavior |
|---|---|
Empty urls | Returns [] immediately; no workers created. |
| All identical URLs | u = 1, one worker makes one call; every output entry is a copy of that result. |
max_concurrency > u | Workers capped at u; no idle coroutines created. |
| All failures | Each worker records an error and moves on; gather returns normally. |
| Exception with empty message | str(exc) or type(exc).__name__ ensures the error field is never an empty string. |
Common mistakes
asyncio.gatherover all raw URLs without deduplication or a semaphore. This fires up to 10,000 concurrent requests, deduplicates nothing, and a single failure aborts the whole batch unlessreturn_exceptions=Trueis set.- Deduplicating with
set(urls). Set iteration order is not guaranteed, which scrambles the result-to-index mapping. - Catching
BaseExceptionor a bareexcept:. This silently interceptsCancelledError, making the function impossible to cancel from outside. - Building output by appending inside the worker. Workers finish in arbitrary order, so position in the list would be random.
Follow-up: retries with exponential backoff
Wrap the await fetch_fn(url) call in an attempt loop inside the worker. Retry only on transient errors (e.g., a status code in the 429/503 range). Between attempts, sleep for base * 2**attempt + random_jitter seconds, and respect a Retry-After header when present. Cap both the attempt count and the maximum sleep duration.
One subtle decision: should the worker hold its concurrency slot while sleeping? Holding it is gentler on a server that is rate-limiting you; releasing it (by briefly exiting the worker and re-entering after sleep) improves throughput toward other URLs in the batch. Which is correct depends on whether the backoff is protecting a single origin or the whole batch.