KatInterview

Async URL Batch Fetcher with Concurrency Limits

Data Structure DesignModel answer
MediumModel answerData Structure Designasyncconcurrencypython

Last 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

  1. Bounded concurrency. No more than max_concurrency calls to fetch_fn may be running at the same time. When max_concurrency == 1 the calls run one after another.
  2. Single fetch per unique URL. If the same URL appears more than once, fetch_fn is called for it exactly once. Every occurrence in the output reflects the same result.
  3. Input order in output. The returned list has the same length as urls and each position matches the corresponding input URL.
  4. Per-request error containment. When fetch_fn raises 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,000
  • 1 <= max_concurrency <= 100
  • fetch_fn accepts a URL string and either returns a string payload or raises an Exception.
  • 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_concurrency larger 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.