Stop 14 · Advanced PythonProjects · 1/1

Concurrent File Downloader

Part of the Python Roadmap

In short

This project turns all the concurrency theory into something you can measure. You'll build one tool three ways and show, with your own timings, when each approach wins.

A command-line tool that downloads a list of files at the same time, shows progress, retries failures and compares sequential, threaded and asyncio versions. It turns concurrency theory into measured results.

The jaadu stands at a courier hub waving off four delivery riders on scooters, each carrying a parcel, while a returned parcel sits ready on a shelf for another try.

Think of it like this

A fleet of delivery bikes

A courier hub with one rider delivers parcels one after another. Add four riders and deliveries overlap, but you still cap the fleet so the roads don't jam. When a parcel bounces back, a rider tries again a little later. Your downloader is that hub: a limited number of parallel downloads, retries and a clear delivery report.

Watch it happen

Sequential vs concurrent downloads

Sequential

  • One file at a time
  • Total time is the sum of every download
  • Simplest code, easy to debug

Concurrent (threads or asyncio)

  • Several files at once, capped by a limit
  • Total time is close to the slowest few downloads
  • Needs limits, retries and careful error handling

Downloads are I/O-bound, so threads and asyncio both give large speedups. Measure all three and put the table in your README.

The big ideas

What you need to know

Limit concurrency

An asyncio.Semaphore or max_workers caps parallel downloads so you don't overload the server or your connection.

Retry with backoff

Network errors happen. Retry a few times, waiting longer each time (2, 4, 8 seconds), then report a clear failure.

A real CLI

Use argparse for the URL file, output folder and limit. Add a progress bar with a library like tqdm or rich.

Benchmark honestly

Run each version on the same list of files several times and report the timings in a table.

How it works

Build plan

  1. 1

    Sequential version

    Read URLs from urls.txt and download them in a loop with requests.

  2. 2

    Threaded version

    Wrap the download in ThreadPoolExecutor with a max_workers option.

  3. 3

    Async version

    Use httpx.AsyncClient, a Semaphore and asyncio.as_completed.

  4. 4

    Robustness

    Add timeouts, retries with backoff and safe file names.

  5. 5

    Measure and document

    Benchmark all three and explain the results in the README.

See it in code

Walk through the code

python
1import asyncio2from pathlib import Path3 4import httpx5 6OUT = Path("downloads")7MAX_PARALLEL = 48 9async def download(client: httpx.AsyncClient, sem: asyncio.Semaphore, url: str, retries: int = 3) -> str:10    name = url.rstrip("/").rsplit("/", 1)[-1] or "index.html"11    for attempt in range(1, retries + 1):12        try:13            async with sem:14                response = await client.get(url, follow_redirects=True)15                response.raise_for_status()16            (OUT / name).write_bytes(response.content)17            return f"ok    {name} ({len(response.content):,} bytes)"18        except httpx.HTTPError as exc:19            if attempt == retries:20                return f"fail  {name}: {exc}"21            await asyncio.sleep(2 ** attempt)22    return f"fail  {name}"23 24async def main() -> None:25    urls = Path("urls.txt").read_text().split()26    OUT.mkdir(exist_ok=True)27    sem = asyncio.Semaphore(MAX_PARALLEL)28    async with httpx.AsyncClient(timeout=20) as client:29        tasks = [download(client, sem, url) for url in urls]30        for finished in asyncio.as_completed(tasks):31            print(await finished)32 33asyncio.run(main())

1/5Output folder and the maximum number of downloads running at the same time.

The asyncio version of the downloader. Put one URL per line in urls.txt and run pip install httpx first.

Save yourself the pain

Common mistakes

Oops

Firing hundreds of downloads at once with no limit.

Do this instead

Servers may block you and your connection gets saturated. Cap it with a Semaphore or max_workers.

Oops

Creating a new httpx.AsyncClient for every file.

Do this instead

Use one client for all downloads so connections are reused, and close it with async with.

Oops

Claiming "async is 10x faster" without data.

Do this instead

Show your own benchmark table, with the number of files, their sizes and the timings for each version.

Your mission

Ship the downloader

~180 min

Quick check

What does asyncio.Semaphore(4) do in the downloader?

Go deeper

  1. 1Read the list of URLs from a text file passed with argparse.
  2. 2Build threaded and asyncio versions and time both against a sequential one.
  3. 3Add retries with a short wait and log any downloads that still fail.

Stuck on this topic? Ask an Insider

Get 1:1 guidance from people who've walked this exact path — on the InsideEdge app.

Download
InsideEdge