Python Asyncio Web Scraping & API Automation: How to Process 10,000 Requests in 60 Seconds Safely

Neon dark illustration of a Python asyncio scraping pipeline: a code editor showing Semaphore rate limiting next to the headline 10,000 requests in 60 seconds, zero bans

Ten thousand requests in sixty seconds is 167 requests per second, and that number is not a benchmark, it is a budget line: it is the exact throughput at which a fan-out stops being a script and becomes an incident. The failure is rarely mysterious. On a two-vCPU box with the default file-descriptor limit of 1,024, an uncapped asyncio.gather over 2,000 URLs against a server in its own process answered 1,018 of them and then died: the other 982 failed with Errno 24: Too many open files, the client’s own descriptor table peaked at exactly 1,024, and the run was over in 0.60 seconds. The same client, wrapped in one semaphore of 20, finished all 2,000 in 12.32 seconds with a peak of 26 descriptors — 2.5% of the budget it had just spent.

Both runs are printed in this article, along with the rest of a matrix that now runs to twenty-six experiment scripts on Python 3.12.16, aiohttp 3.14.5, lxml 6.1.3, glibc 2.41, two vCPUs and 1,998 MB of RAM. Every figure below comes from one of those scripts, run against a loopback server; nothing is estimated from a blog post, and where a claim comes from documentation instead of a measurement, the sentence says so. Nothing in this article sends traffic anywhere except 127.0.0.1, which is the only way to measure a client’s behaviour without making somebody else’s server pay for the experiment.

TL;DR — concurrency is a politeness setting, not a speed setting. Size it with Little’s law (throughput x latency), then bound three different things, because they are three different limits: requests in flight, sockets, and request starts per second.

  • Unbounded is not fast, it is short. 2,000 URLs through an uncapped gather answered 1,018, hit the 1,024-descriptor limit and stopped in 0.60 seconds. One semaphore of 20 finished all 2,000 in 12.32 seconds at 26 descriptors.
  • A semaphore is not a rate limit. 20 slots at 120 ms latency sustained 161.5 req/s; at zero latency the same 20 slots allowed 3,490.5 req/s. The connector is a third ceiling: a limit of 10 under a semaphore of 50 turned a 1.28-second job into 6.12 seconds and pushed p50 from 125.4 ms to 609.9 ms.
  • A token bucket is. A bucket of 20 per second produced exactly 20.0 req/s. A bucket whose capacity equals its rate produced 30.0 against the same quota, because the first second held two windows’ worth.
  • Retry outside the slot, and obey the header. Sleep where no slot is held. Honour Retry-After exactly and never come back early. When the server asks for more than 60 seconds, stop and leave the URL to a later run — and hold the whole host while you do, because the header was an answer to the client, not to that one URL: 200 URLs with a per-host limit of 8 cost 8 requests and 192 deferrals instead of 200 requests. Adding up to 10% on top breaks the lockstep, not the burst: 200 retries spread over 99.2 ms and 50 of them still arrived inside 20 ms.
  • Jitter is a spread, not a rate. Full jitter over your own backoff is worth having — 200 synchronised retries landed inside 19.0 ms, and full jitter spread them across 494.1 ms with the busiest 20 ms window falling from 200 to 16 — but no jitter sets a throughput. With a 20/s token bucket in front of the same 200 retries, they arrived at 20 per second and never more than one in any 20 ms window; without it, the 10% nudge left 50 in one window.
  • Count a 404, but never as a failure. One breaker per host, counting 5xx and timeouts: 240 requests and 3.80 seconds became 60 requests and 0.27 seconds while the healthy hosts kept answering.
  • Against a real quota, politeness wins. A naive fan-out completed 5 of 300 URLs before being banned; the bounded client completed 300 of 300.

The cover image for this article makes the same claim in one line: a code editor showing a semaphore next to the headline 10,000 requests in 60 seconds, zero bans. The zero belongs to the bounded client, not to asyncio. The naive version of the same job was banned after completing 5 of 300 URLs (section 14), and the difference between those two clients is the subject of everything below.

1. The arithmetic you do before the first request

Little’s law says that for a stable system, the number of items inside it equals the arrival rate multiplied by the time each item spends inside. Written for a scraper, that is the only sizing formula you need: concurrency = requests per second x latency in seconds. If the target answers in 120 ms and you want 167 requests per second, you need twenty requests in flight, not ten thousand.

concurrency = throughput x latency
167 req/s x 0.12 s = 20.04
10,000 requests / 167 req/s = 59.9 s

The formula is trivially checkable, which is the point: you can throw away a design that violates it before you write the design. The table below is the formula against a real loopback server with a 120 ms think time, seven concurrency settings, each run sized to last about three seconds after warm-up. The server counted its own in-flight requests, so the “peak in flight” column does not depend on the client telling the truth about itself.

ConcurrencyRequestsWall timeMeasured req/sPredicted (c / 0.12 s)p50 latencyp95 latencyEfficiency
112014.51 s8.38.3120.9 ms121.0 ms100%
51202.92 s41.141.7121.3 ms122.1 ms98.6%
102002.45 s81.883.3121.6 ms122.2 ms98.2%
204002.48 s161.5166.7122.8 ms124.2 ms96.9%
501,0002.56 s390.9416.7125.0 ms126.5 ms93.8%
1002,0002.58 s774.5833.3125.0 ms139.0 ms92.9%
2004,0003.03 s1,321.11,666.7125.8 ms141.0 ms79.3%
Table 1. Little’s law on a loopback server with a 120 ms think time. Efficiency is measured divided by predicted; the last row is the client and server sharing two vCPUs, which is the ceiling of this machine rather than of the pattern.

Two things in that table are worth more than the others. The first is that the model holds closely enough to plan with: at concurrency 20 the 400-request run took 2.48 seconds against a floor of 2.40, which is 3.3% of overhead, and at concurrency 50 the 1,000-request run took 2.56 seconds against the same 2.40, which is 6.7%. The second is the last row. At concurrency 200 the measured rate is 79.3% of the prediction, and the p95 latency jumps from 126.5 ms at concurrency 50 to 141.0 ms, because the client and the server are competing for the same two vCPUs. That is not a property of asyncio; it is a property of the machine, and it is the first hint that “how many in flight” is bounded on both ends of the wire.

Now apply the same arithmetic to the headline claim. Ten thousand requests at 120 ms of latency needs 10,000 x 0.12 seconds of total service time, which is 1,200 seconds of work to be divided across however many slots you are willing to hold. Twenty slots make that 60 seconds. Fifty slots make it 24. Both were run to completion, and both completed every URL.

Two caveats belong in front of that table, because both columns are easy to read wrongly. The server in these runs lived in the same process as the client — an aiohttp.web application on 127.0.0.1 — so every descriptor count in Table 2 is both ends of each connection: 48 descriptors at 20 slots is 20 client sockets, 20 server sockets, and 8 descriptors the process already had open (stdio, the loop’s epoll and its wakeup pipe, the listening socket). Counted from outside, with the server in its own process, the client’s table is sockets plus six to eight: 26 for the 20-slot run of Table 3, which is 20 sockets and six descriptors, and 28 and 58 for the 10,000-URL runs at 20 and 50 slots, in 62.06 and 24.43 seconds. Every descriptor figure in this article is one of those two accountings, and the whole difference between them is the server’s end of each socket plus whatever the process happened to have open when it started. And the RSS column is not a comparison between the rows at all; it is the price of being the first 10,000-request run in a process, which the paragraph after the table measures directly.

ConcurrencyWall timeMeasured req/sFloor (10,000 x 0.12 / c)CompletedPeak open descriptorsRSS growth
2061.92 s161.560.0 s10,000 / 10,0004815.8 MB
5024.92 s401.324.0 s10,000 / 10,0001081.0 MB
Table 2. The title claim, measured end to end: 10,000 requests, zero failures, 3.2% and 3.8% above the arithmetic floor respectively. Descriptor counts include the server’s end of every socket, because it ran in the same process.

The 3.2% is the cost of being a client rather than a formula: coroutine scheduling, connection setup for the first flight, and the loop’s bookkeeping. It is the number to put in front of anyone who asks why the run takes 62 seconds instead of 60, and it is small enough that the arithmetic stays useful for planning. What it does not tell you is whether the target will still be answering at request 10,000, which is the subject of the rest of this article.

The RSS column needs its own sentence, because 15.8 MB against 1.0 MB reads like “fifty slots are cheaper than twenty” and it is not. The same two runs were repeated in a fresh process in the opposite order — 50 first, then 20 — and the numbers followed the order rather than the concurrency: 15.8 MB for the run at 50 slots and 1.0 MB for the run at 20. What 15.8 MB buys is being the first 10,000-request run in a process: allocator arenas, the session and connector being built, and ten thousand coroutine and task objects created for the first time. The second run reuses all of it, whichever concurrency it uses. A memory figure taken from one run in a fresh process therefore measures warm-up as much as it measures the design, which is why the memory claims in section 11 are per unit rather than per run.

2. The four ways a fan-out fails, reproduced

An uncapped gather does not fail in one way. It fails in four, and the first one you see depends on the order in which the operating system, the remote server and the event loop give up. Here is the code that produces all four, written the way it appears in most tutorials: one session, a timeout, and every URL scheduled at once.

import asyncio

import aiohttp

URLS = [f"https://api.example.com/items/{i}" for i in range(10_000)]


async def fetch(session: aiohttp.ClientSession, url: str) -> dict:
    async with session.get(url, timeout=aiohttp.ClientTimeout(total=1)) as resp:
        resp.raise_for_status()
        return await resp.json()


async def main() -> None:
    connector = aiohttp.TCPConnector(limit=0)          # no socket ceiling either
    async with aiohttp.ClientSession(connector=connector) as session:
        results = await asyncio.gather(
            *(fetch(session, url) for url in URLS),
            return_exceptions=True,
        )
    failures = sum(1 for r in results if isinstance(r, BaseException))
    print(f"{failures:,} of {len(results):,} failed")


if __name__ == "__main__":
    asyncio.run(main())

Every line in that block is defensible in isolation. return_exceptions=True means one bad URL cannot cancel the other 9,999. The timeout means a dead host cannot hang the run. The connector with no limit is honest about what the code intends: go as fast as the loop allows. Run it against the 120 ms loopback server with 2,000 URLs and a one-second timeout, and the result is not partial success: it is 1,018 answers and then a wall.

StrategyRequestsSucceededFailure breakdownPeak descriptorsWall time
Unbounded gather, 1 s timeout2,0001,018982 ClientConnectorError (Errno 24)1,0240.60 s
Same URLs, Semaphore(20)2,0002,000none2612.32 s
Unbounded gather, no return_exceptions, one 5002010raised ClientResponseError: 500 after 0.16 s, 117 of its requests still in flightn/a0.16 s
Table 3. Three runs of the same client. In the first two the server was a separate process and the descriptor count was sampled by the parent from /proc/<client pid>/fd, so every descriptor in those rows belongs to the client; the third ran in one process, because its subject is a task tree rather than a socket table. The failure column is the server’s own status log plus the client’s exception types.

Read the second row again. The bounded client took 12.32 seconds where the unbounded one took 0.60, and answered 2,000 requests where the unbounded one answered 1,018. The unbounded client did not lose most of the work; it lost the rest of it, because the client reached exactly 1,024 open descriptors, the next socket was refused with Errno 24, and from that point every new connection failed instantly. Nothing was slow. The run simply ended, and it ended eleven seconds before the polite version that finished the job.

Two things about how that was measured matter for reading every descriptor number in this article. One is who is counting. When this run lived in one process with its test server, the sockets belonged to both of them at once and the sampler that was supposed to record the peak died where the client did: OSError: [Errno 24] Too many open files: '/proc/self/fd'. That is a fair summary of a process that has spent its descriptor budget on concurrency it cannot use, and a useless measurement. With the server in its own process, and its own descriptor limit raised so that it cannot be the one that fails, the parent samples the client’s table every two milliseconds. Peak: exactly 1,024. A repeat run split the batch 1,017/983 rather than 1,018/982, because that process started with one more descriptor already open; the wall is at 1,024 either way, and the split moves by a few requests depending on what else the process owns.

The four failure modes, then, in the order a production run meets them:

  • Descriptor exhaustion. Every in-flight connection is a file descriptor. On this machine RLIMIT_NOFILE is 1,024, and the unbounded client reached it and kept asking. Raising the limit with ulimit -n moves the wall and does not remove it: the remote end has limits too, and none of them are yours to raise.
  • Timeout amplification. A total timeout is a deadline for the whole request, and the time a request spends waiting for a free socket in the connector counts against it, so a request that never leaves the client can still expire. Four runs of the same 100 URLs against a server that takes 500 ms. Five sockets and a one-second deadline: 95 timed out, 90 of them without sending a byte, and the median request lasted 1,000.7 ms, which is the deadline to the millisecond; the server counted 10 requests and finished 5, so five of the timeouts had been sent and were killed on the deadline. Twenty sockets: 20 completed, 80 timed out, 60 never sent, median 1,001.8 ms. No pool limit at all: 100 completed in 0.54 s, median 520.3 ms. And five sockets with the deadline at 30 seconds: 100 completed in 10.05 s, with the median request waiting 5,523.9 ms for its turn while the pool never held more than five. The amplification lives in the client’s own pool, which is why it survives a healthy network and a healthy server. The 1,017 TimeoutErrors in the earlier in-process run of this same 2,000-URL batch are a different mechanism with the same name — a server sharing the client’s event loop starves it — and they vanish when the server moves to its own process, which is the test that tells the two apart.
  • Silent loss. Without return_exceptions=True, the first 500 propagates out of gather, the handler returns, and the requests still in flight keep running with nothing awaiting them. In the third row of Table 3 the 500 arrived 0.16 seconds in, 117 of the 201 requests were still in flight, and every one of their answers was dropped on the floor: no result, no count, no log line. The other 84 had already finished, and their results died with the exception.
  • The self-inflicted 429. None of the first three matter if the server bans you first. In section 14 a 300-URL naive run put 521 requests into a single second against a target that allows 20 per second, and finished with 5 successes and 824 rejections.

None of these are exotic. They are what “just gather everything” means once the list is longer than the descriptor limit, and the reason the fix is three limiters rather than one is that each of them bounds a different quantity.

3. The semaphore, and the two things it does not do

asyncio.Semaphore is a counter with a queue behind it. You set it to the number of requests you are willing to have in flight; every task acquires before it starts a request and releases when the response is read. Two habits turn it from decoration into a control. The first is taking the global slot before the per-host slot, so a task never sits on a scarce per-host slot while it waits for the global one. The second is holding the slot only while I/O is in flight, and never while sleeping.

import asyncio
from contextlib import asynccontextmanager
from typing import AsyncIterator

import aiohttp


class HostLimiter:
    """A global ceiling and a per-host ceiling, taken global-first."""

    def __init__(self, global_limit: int, per_host: int) -> None:
        if global_limit < 1 or per_host < 1:
            raise ValueError("limits must be >= 1")
        self.global_limit = global_limit
        self.per_host_limit = per_host
        self._global = asyncio.Semaphore(global_limit)
        self._hosts: dict[str, asyncio.Semaphore] = {}

    @asynccontextmanager
    async def slot(self, host: str) -> AsyncIterator[None]:
        sem = self._hosts.get(host)
        if sem is None:
            sem = asyncio.Semaphore(self.per_host_limit)
            self._hosts[host] = sem
        async with self._global:          # cheap slot first: nobody parks here
            async with sem:               # then the scarce one
                yield


async def fetch(session: aiohttp.ClientSession, limiter: HostLimiter, url: str) -> bytes:
    host = url.split("/")[2]
    async with limiter.slot(host):
        async with session.get(url) as resp:
            resp.raise_for_status()
            return await resp.read()

That is the whole mechanism, and it is worth being explicit about what it buys. In the sweep in section 1, one session with a semaphore of 20 and a shared connection pool sustained 161.5 req/s at 120 ms of latency, and the server’s own counter never saw more than 20 requests at once. Against a zero-latency loopback server, the same semaphore of 20 allowed 60 requests to complete in 0.02 seconds, which is 3,490.5 req/s. That last figure is a 20-millisecond sample of sixty requests rather than a sustained rate: it exists to show that the semaphore never said no, not to claim a client can do 3,490 req/s all afternoon. The semaphore was never violated in either run. It simply does not answer the question “how often may I start a request”, and at zero latency that question is the only one that matters.

ControlWhat it boundsMeasured hereWhat it does not bound
asyncio.Semaphore(20)Requests in flight at once161.5 req/s at 120 ms latency, server peak 20Request starts: 3,490.5 req/s at zero latency
TCPConnector(limit=10)Sockets per session81.6 req/s at concurrency 50, p50 609.9 msAnything the moment the limit sits below your semaphore
Token bucket, 20 per secondRequest starts per second20.0 req/s, at most 20 arrivals in any one-second windowConcurrency: the bucket does not cap what is in flight
CircuitBreaker(threshold=5)Requests sent to a failing host240 requests became 60 plus 60 fail-fast responsesAnything while the host is healthy, by design
Table 4. Four controls, four different quantities. None of them substitutes for another, and a production client holds all four at once.

There is a fifth, quieter effect that the table cannot show: a slot held during a sleep is a slot spent on nothing. If the retry loop in section 6 kept the semaphore while backing off, a batch where 10% of URLs return 429 would have a tenth of its capacity sitting in asyncio.sleep, and the queue behind them would grow until the total timeout started firing. The fix is a single line of indentation, and it is the difference between a client that slows down under pressure and one that stalls.

4. The connector is a second ceiling, and a silent one

aiohttp’s connector is the object that owns the sockets. limit is the total for the session, limit_per_host is the share one origin may hold, and the default for limit is 100. Nothing in the API prevents you from setting a semaphore of 50 on top of a connector limit of 10; the client will simply queue 40 tasks inside the connector while the server sees ten requests at a time, and every latency number you collect will describe that queue rather than the network.

import aiohttp

CONCURRENCY = 20

connector = aiohttp.TCPConnector(
    limit=CONCURRENCY,             # total sockets this session may hold
    limit_per_host=8,              # no more than eight to any one origin
    ttl_dns_cache=300,             # reuse DNS answers for five minutes
    keepalive_timeout=30,          # keep idle sockets for reuse, not forever
)
timeout = aiohttp.ClientTimeout(total=15, connect=5, sock_read=10)
headers = {"User-Agent": "TechBobbyBot/1.1 (+https://techbobby.com/about)"}

The measured cost of getting this wrong is not a crash. It is a job that takes five times as long while reporting 100% success, which is the hardest kind of failure to notice in a dashboard that only counts errors.

Connector limitSemaphoreRequestsWall timereq/sp50p95Server peak in flight
10505006.12 s81.6609.9 ms1,101.7 ms10
50505001.28 s389.4125.4 ms132.8 ms50
0 (unlimited)505001.29 s386.9125.5 ms131.0 ms50
Table 5. Same server, same 120 ms latency, same semaphore. The only variable is the connector, and the latency column moves by a factor of 4.9 while the success count never changes.

Per host, the same effect applies one level down, and it is what keeps a crawler from putting all of its capacity into one origin. Two servers were started on 127.0.0.1 and 127.0.0.2, each counting its own in-flight requests, and 600 URLs were split across them with a global connector limit of 50. Both origins answered in 120 ms, and the URLs alternated, so this table is about how a ceiling splits capacity — the head-of-line question gets its own run in the paragraph after it.

limit_per_hostRequestsWall timereq/sPeak in flight, origin APeak in flight, origin B
56007.71 s77.855
506001.55 s386.92525
Table 6. A per-host ceiling splits capacity evenly instead of letting the first origin in the queue take it all. The 5-request ceiling is 5.0 times slower for this workload, and it is the correct setting for two small APIs you do not own.

Note the shape of the trade in Table 6: with limit_per_host=5 each origin received exactly five concurrent requests, which is politeness by construction, and the run took 7.71 seconds instead of 1.55. A crawler that respects a small API’s capacity is supposed to take longer. The mistake is not choosing the slow setting; it is choosing a fast setting by accident, because the connector default of 100 let it happen.

That run has one weakness, and it is the kind worth fixing rather than explaining: the 600 URLs were sent interleaved, so origin B’s share followed from the task order. A per-host ceiling is supposed to protect B when the queue is full of A, and that needs A to arrive first. So the question was asked again, plainly: two origins, A answering in 500 ms and B in 20, a global connector limit of 50, 200 requests queued to A and 100 milliseconds later 100 requests queued to B. With limit_per_host=50, A takes every socket in the limit and B waits in the connector: its first answer arrived after 439.4 ms, its p50 was 939.0 ms, and its 100 requests took 1.17 seconds. With limit_per_host=10, A can hold only a fifth of the pool: B’s first answer arrived after 26.1 ms, its p50 was 130.9 ms, and its 100 requests took 0.22 seconds while A was still working through its queue. A’s own 200 requests finished in 2.28 seconds at 50 and 10.06 seconds at 10, with a p50 of 1,521.7 ms against 5,529.9 ms — so the 7.8 seconds that protecting B costs is the trade stated plainly: a per-host ceiling does not create capacity, it moves capacity from the origin with more work to the origin with less. Same client, same server, same 50 sockets — the only change is how many of them one origin may hold.

5. A rate limit is not a concurrency limit

Everything above bounds how much is in flight. A published quota is stated in a different unit: requests per second, per minute, or per day. Twenty requests in flight against a server that answers in 5 ms is 4,000 requests per second, which is why a client that looks perfectly polite in a concurrency graph can be over quota by two orders of magnitude. The token bucket is the standard answer, and it is thirty lines.

import asyncio
import time
from typing import Awaitable, Callable


class TokenBucket:
    """Capacity tokens to burst with, refilled at `rate` tokens per second."""

    def __init__(
        self,
        rate: float,
        capacity: float = 1.0,
        clock: Callable[[], float] = time.monotonic,
        sleep: Callable[[float], Awaitable[None]] = asyncio.sleep,
    ) -> None:
        if rate <= 0:
            raise ValueError("rate must be positive")
        self.rate = rate
        self.capacity = max(capacity, 1.0)
        self.tokens = self.capacity
        self.updated = clock()
        self._clock = clock
        self._sleep = sleep

    async def acquire(self) -> None:
        while True:
            now = self._clock()
            self.tokens = min(self.capacity, self.tokens + (now - self.updated) * self.rate)
            self.updated = now
            if self.tokens >= 1.0:
                self.tokens -= 1.0
                return
            await self._sleep((1.0 - self.tokens) / self.rate)

The parameter that decides whether the bucket works is capacity, and the mistake that makes it useless is setting it to the same number as the rate. A bucket of 20 per second with a capacity of 1 admits exactly one request every 50 ms. The same rate with a capacity of 20 admits twenty at once and then twenty more over the following second, which is 40 requests inside a one-second window against a quota of 20.

PolicyTargetMeasured req/sMax arrivals in any 1 sSmallest gapGap variation (CV)
Bucket, capacity 15/s5.35200.2 ms0.001
Bucket, capacity 55/s7.590.0 ms0.632
Bucket, capacity 120/s20.02050.1 ms0.004
Bucket, capacity 2020/s30.0400.0 ms0.689
Bucket, capacity 150/s48.04920.4 ms0.012
Bucket, capacity 5050/s74.91000.0 ms0.703
Fixed sleep, staggered start20/s20.32147.7 ms0.014
Semaphore only, no bucketnone3,490.5600.0 ms0.981
Table 7. Arrival times were recorded by the server, not by the client, so the rate column is the rate the target experienced. Capacity equal to rate doubles the instantaneous burst; capacity 1 keeps every window inside the quota.

A second detail in that table is the 48.0 req/s at a 50 per second target, which is 4% under. A token bucket implemented with a loop and a real clock pays the scheduler’s wake-up latency on every grant, and the error accumulates with the number of requests rather than the time (150 requests, 3.12 seconds instead of 3.00). For a hard daily quota the shortfall is in your favour; for a test that asserts an exact rate it is a flaky assertion, which is why the module in section 13 injects both the clock and the sleep function.

The fixed-sleep row is the pattern most tutorials show: stagger the start times with asyncio.sleep(i / rate). It produced 20.3 req/s and 21 arrivals in the busiest second, so it is accurate — for a list whose tasks all start at once and whose duration is known. As soon as a task retries, the schedule it computed is stale, and as soon as the list is longer than the run, it is unmaintainable. A bucket is stateless with respect to the list, which is why it survives contact with retries.

6. Retries: the sleep is the design

The classic retry bug is not the exponent. It is the two places a sleep can sit. Inside the slot, a sleeping task holds a concurrency permit it is not using, so the queue drains at the speed of the backoff rather than the speed of the network. Outside the slot, the permit goes back to the pool and other work proceeds while the failed URL waits. The difference is one level of indentation and it decides whether a 10% failure rate costs 10% of throughput or half of it.

The second bug is ignoring Retry-After. That header is the one place where a server tells you exactly what it wants, in seconds or as an HTTP date, and it is usually issued by a rate limiter that is already watching you. To measure what ignoring it costs, the test server issues a single 429 with Retry-After: 0.4 and then treats any request that arrives inside that window as a permanent 403.

Client behaviourStatuses the server sentFinal statusWall timeOutcome
Ignores the header, retries after 50 ms1 x 429, 1 x 4034030.05 sPermanently blocked
Sleeps exactly the 0.4 s the server asked for1 x 429, 1 x 2002000.40 sCompleted
Sleeps 0.4 s plus up to 10% of jitter1 x 429, 1 x 2002000.42 sCompleted
200 tasks told Retry-After: 1, honoured exactly200 x 429, 200 x 200200 of 2002.10 s185 of the 200 retries arrived inside one 20 ms window, all of them inside 38.4 ms
Same 200, plus up to 10% of jitter200 x 429, 200 x 200200 of 2002.15 sRetries spread over 99.2 ms; 50 in the busiest 20 ms
Same 200, with a 20/s token bucket in front200 x 429, 200 x 200200 of 20021.08 s20 in the busiest second, 1 in any 20 ms
Same 200, bucket plus 10% jitter200 x 429, 200 x 200200 of 20021.23 s19 in the busiest second, 1 in any 20 ms
Told Retry-After: 3600, defers instead of waiting1 x 4294290.001 sOne request; the URL is marked deferred for a later run
Table 8. Eight runs of one rule. Rows 1-3 are a single request against a server that treats an early retry as a permanent ban. Rows 4-5 are 200 requests released from a barrier at the same instant — the situation the header exists to defuse — and the arrivals are counted at the server. Rows 6-7 put the section-5 token bucket at 20 per second in front of the same 200, where the bucket decides the rate and the jitter only decides the order. Row 8 is a one-hour ban, where the only compliant answers are an hour of waiting and another run.

Row 4 of the table looks wrong at first reading, because 2.10 seconds against a one-second wait looks like the client slept twice. It did not: the second is one of three segments. The 200 first attempts are held on a barrier until every one of them has connected, which on this box takes 993.7 ms — client connect time, not a sleep. The barrier releases them together, each is told Retry-After: 1, and the first retry arrives 1,007.8 ms after the release: the second the server asked for, plus 7.8 ms of scheduler. The retries themselves land inside 38.4 ms. Those three segments make 2.04 seconds, and the 2.10 in the table is that plus loop overhead. A reader who expects 1.0 s is timing the sleep; the row times the run, connections included.

import time
from email.utils import parsedate_to_datetime

MAX_RETRY_AFTER = 60.0  # longer than this: stop, and come back in a later run


def parse_retry_after(value: str | None, now: float | None = None) -> float | None:
    """Parse Retry-After as delta-seconds or as an HTTP-date. None if unusable."""
    if not value or not value.strip():
        return None
    try:
        return max(0.0, float(value))
    except ValueError:
        pass
    try:
        when = parsedate_to_datetime(value)
    except (TypeError, ValueError):
        return None
    if when is None:
        return None
    current = time.time() if now is None else now
    return max(0.0, when.timestamp() - current)


def backoff(attempt: int, retry_after: float | None, rng) -> float | None:
    """Seconds to wait before the next attempt. None means: stop, do not retry.

    Call it outside the semaphore - a sleeping task must not hold a slot - and
    treat None as "this URL belongs to a later run", not as an error to retry.
    """
    if retry_after is None:
        return rng.uniform(0, min(10.0, 0.25 * 2 ** (attempt - 1)))
    if retry_after > MAX_RETRY_AFTER:
        return None                                  # an hour is a later run, not a wait
    return retry_after + rng.uniform(0, retry_after * 0.10)  # never earlier than asked

Those two functions are the ones the module in section 13 exposes: parse_retry_after turns a header into seconds, and backoff turns seconds into a delay or into None. Three numbers in them are worth arguing about. The 10-second cap belongs to your own schedule: it is what stops an exponent from turning one URL into a ten-minute wait. The 60-second limit is not a cap on waiting, because there is no such thing as waiting for 60 of the 3,600 seconds the server asked for and calling it compliance — a retry that lands 3,540 seconds early is exactly the request the header exists to prevent. Above 60 seconds the function returns None, the caller keeps the result and marks it deferred, and the URL belongs to a later run that starts from the checkpoint. Row 8 of Table 8 measures that path: one request, no sleep, done in a millisecond.

Deferring the URL is half of that decision, because the header was an answer to the client and not to the URL. Two hundred URLs are queued for one host with a per-host limit of 8, and the server bans everything with Retry-After: 3600. Eight requests are already in flight when the first 429 is read, so eight is the floor; the question is what the other 192 do. Without a host-level gate they take their turn and each one pays a request to be told the same thing: 200 requests, 32 ms. With a gate that the first long answer closes, the 192 never open a socket — 8 requests, 192 rows marked host_cooldown, 9 ms for the whole run. The gate cannot recall a request already in flight, which is why the count is 8 and not 1, and why the per-host limit is also the size of the overshoot.

import time
from typing import Callable


class HostCooldown:
    """A per-host gate set when a Retry-After outlasts what the client will wait."""

    def __init__(self, clock: Callable[[], float] = time.monotonic) -> None:
        self._clock = clock
        self._until: dict[str, float] = {}
        self._header_s: dict[str, float] = {}

    def hold(self, host: str, seconds: float) -> None:
        """Keep every request for `host` from starting for `seconds`."""
        until = self._clock() + max(0.0, float(seconds))
        if until >= self._until.get(host, 0.0):      # a second ban never shortens
            self._until[host] = until
            self._header_s[host] = seconds

    def remaining(self, host: str) -> float | None:
        """Seconds left on the host's hold, or None if the host is open."""
        until = self._until.get(host)
        if until is None:
            return None
        left = until - self._clock()
        if left <= 0.0:
            self.release(host)
            return None
        return left

    def release(self, host: str) -> None:
        self._until.pop(host, None)
        self._header_s.pop(host, None)

The gate is checked twice per attempt, and the two checks answer different questions. In front of the token bucket it keeps a held URL from queuing for a token it will not spend, which is what makes the 192 deferrals cost nothing rather than cost a second each. Inside the slot it keeps a URL that was already queued when the gate closed from opening a socket when its turn comes; that check is the one that makes the request count for a held host equal the number that had already started. A URL that is deferred this way goes to the checkpoint as unfinished, which section 12 makes sure the next run retries.

The jitter is the third number, and it is positive only. A wait shorter than the server asked for is not compliance, and a wait that is exactly what it asked for is a synchronised wave when two hundred tasks were told the same number. That much is measured: 200 tasks were released from a barrier together, every one of them was told Retry-After: 1, and the server counted their return. Obeyed exactly, 185 of the 200 came back inside a single 20 millisecond window. With up to 10% added on top, the returns spread over 99.2 milliseconds and the busiest window held 50.

It would be easy to write that as if the problem were solved, and it is not. A tenth of a second is not a rate: 50 requests still arrived inside 20 ms and all 200 inside 99.2 ms, which is a burst with softer edges. The 10% nudge does the one thing it can — it stops a batch from returning in lockstep, so the same number sent to a thousand clients does not produce a thousand arrivals in the same millisecond — and the rest is the token bucket’s job. Rows 6 and 7 of Table 8 measure the difference: the same 200 retries, the same one-second header, a bucket of 20 per second in front, and the busiest second holds 20 arrivals (19 with the jitter) while the busiest 20 ms window holds exactly one. The retries in those rows are spread across 18,736.1 ms and 19,398.4 ms rather than 99.2 ms, for a reason worth being explicit about: the bucket is pacing the first attempts as well, so a retry can only start when its own token is available. The jitter’s whole contribution there is moving one request to a different part of the same second. Order the controls by what they do: the bucket sets the rate, Retry-After sets the earliest legal moment, and the jitter only breaks the ties.

Jitter is also the third rule for the delay you compute yourself, and there it is about arithmetic rather than etiquette. Exponential backoff without jitter is synchronised: every task that failed at the same moment computes the same delay and retries at the same moment, so the load arrives in a wave. The same is true of the delay you compute yourself, after a 503 or a timeout, where the number is your guess rather than the server’s instruction. Two hundred tasks were failed once by the server and then allowed to retry, and the spread of the second attempt was measured at the server.

JitterRetries spread over90th percentile of the spreadPeak retries in any 20 msTotal requests
None19.0 ms18.5 ms200400
Full (uniform 0 to nominal)494.1 ms450.4 ms16400
Equal (half nominal plus uniform)253.5 ms226.9 ms23400
Table 9. Two hundred tasks, one failure each, one retry. Without jitter every retry landed inside 19.0 ms and the busiest 20 ms window carried all 200 of them; full jitter cut that peak to 16.

The wave is not hypothetical damage; it is a second spike aimed at a server that has just told you it is overloaded. Full jitter removes it at the cost of a wider spread, which is exactly the trade you want: the same 400 requests, spread over 494.1 ms instead of 19.0 ms, and a peak that is 12.5 times lower.

What remains is the schedule itself, and the cap. With a base of 0.25 seconds, doubling and capped at 10, the seventh attempt is the first one that the cap touches.

AttemptNominal delayNo jitterEqual jitter rangeFull jitter range
10.25 s0.25 s0.125 to 0.25 s0 to 0.25 s
20.50 s0.50 s0.25 to 0.50 s0 to 0.50 s
31.00 s1.00 s0.50 to 1.00 s0 to 1.00 s
42.00 s2.00 s1.00 to 2.00 s0 to 2.00 s
54.00 s4.00 s2.00 to 4.00 s0 to 4.00 s
68.00 s8.00 s4.00 to 8.00 s0 to 8.00 s
710.00 s (capped)10.00 s5.00 to 10.00 s0 to 10.00 s
Table 10. The schedule a policy with base 0.25 seconds and cap 10 seconds produces. The cap decides how long a run can take to give up on one URL: a seven-attempt policy waits at most 15.75 seconds in total with full jitter, and the seventh attempt is the last request it makes.

The worst case for seven attempts with full jitter is the sum of the six waits between them, 0.25 + 0.50 + 1.00 + 2.00 + 4.00 + 8.00 = 15.75 seconds, which is the number that belongs next to your total timeout. A total timeout shorter than that will kill the later retries, and a run whose per-request budget is 10 seconds will spend its last attempts waiting for a deadline rather than for the server.

7. The circuit breaker: stop paying for 503s

Retries handle a blip. They are the wrong tool for an outage, because every retry is a request to a server that is already failing, and the backoff schedule means a task that has given up on one host spends its next fifteen seconds proving it. A breaker is a shared decision to stop asking: after N consecutive failures, every task fails fast without touching the network, and one probe is allowed through after a recovery window to find out whether the host came back.

import time
from typing import Callable


class CircuitBreaker:
    """Consecutive-failure breaker over one host, with a single half-open probe."""

    def __init__(
        self,
        threshold: int = 5,
        recovery_timeout: float = 10.0,
        clock: Callable[[], float] = time.monotonic,
    ) -> None:
        self.threshold = threshold
        self.recovery_timeout = recovery_timeout
        self._clock = clock
        self.state = "closed"
        self.failures = 0
        self.opened_at = 0.0
        self._probe_in_flight = False
        self.trips = 0

    def allow(self) -> bool:
        if self.state == "closed":
            return True
        if self.state == "open":
            if self._clock() - self.opened_at >= self.recovery_timeout:
                self.state = "half_open"
                self._probe_in_flight = True
                return True
            return False
        if self._probe_in_flight:
            return False
        self._probe_in_flight = True
        return True

    def record_success(self) -> None:
        self.failures = 0
        self._probe_in_flight = False
        self.state = "closed"

    def record_failure(self) -> None:
        self.failures += 1
        if self.state == "half_open":
            self._probe_in_flight = False
            self.opened_at = self._clock()
            self.state = "open"
            self.trips += 1
        elif self.failures >= self.threshold and self.state == "closed":
            self.opened_at = self._clock()
            self.state = "open"
            self.trips += 1


class BreakerRegistry:
    """One breaker per host, created on first use."""

    def __init__(self, threshold: int = 5, recovery_timeout: float = 10.0) -> None:
        self.threshold = threshold
        self.recovery_timeout = recovery_timeout
        self._breakers: dict[str, CircuitBreaker] = {}

    def for_host(self, host: str) -> CircuitBreaker:
        breaker = self._breakers.get(host)
        if breaker is None:
            breaker = CircuitBreaker(self.threshold, self.recovery_timeout)
            self._breakers[host] = breaker
        return breaker

    def open_hosts(self) -> list[str]:
        return sorted(h for h, b in self._breakers.items() if b.state == "open")

Two decisions in that code are the difference between a breaker and a self-inflicted outage. The first is what counts as a failure. A 5xx, a timeout, a refused connection and a 429 whose retries are spent are failures; a 404, a 403 or any other 4xx is not, because the host answered and only the URL was missing. A crawler walking a sitemap full of dead links would otherwise open the breaker against a perfectly healthy origin and refuse every page behind it. In the module the 4xx case calls record_success(), which resets the streak: reachability is the only thing being measured, and a 404 is proof of reachability. A 429 is the opposite kind of message — patience, not a fault — so it is counted once, and only if the retries run out.

The second decision is scope, and a single breaker is a global kill switch: one dead origin opens it and every other host in the run is refused as well. Two origins were put in front of the same client, one answering 503 to everything and one answering 200. With one shared breaker, the dead origin took two requests, the breaker opened, and all six requests to the healthy origin were refused without a socket: zero completed. With a breaker per host, the dead origin took its two requests, its own breaker opened, and the healthy origin completed all six. The outage cost its own requests and nothing else.

Against a target that returns 503 for everything, sixty tasks with four attempts each behave very differently depending on whether that class is in front of them.

ClientTasksRequests sentFail-fast skipsWall timeTrips
Retries only6024003.80 s0
Retries behind a breaker6060600.27 s1
Table 11. The dead host received 240 requests from the first client and 60 from the second; the second also finished 3.53 seconds earlier and told every remaining task the truth immediately.

The recovery side matters as much as the trip. A second run started with the breaker closed against a failing host, healed the target 1.5 seconds in, and used a recovery window of 0.5 seconds. The breaker moved open, half-open, open, half-open, open, half-open, closed — three probes at half-second intervals — and its last probe landed 1.53 seconds after the run started, 26 ms after the heal. The first successful request completed at 1.53 seconds, and the target saw 82 requests in total.

Those 26 ms are luck plus a short window. With a recovery timeout of 10 seconds, the worst case is that the run notices a healed host up to 10 seconds late, which for a batch job is usually the right trade and for a health check is not. The rule is that the recovery window should be shorter than the tolerance for stale data and longer than the time the host needs to recover; the breaker cannot tell the difference between those two.

8. Timeouts: one hung host takes ten slots with it

A concurrency limit is only a limit if the requests inside it finish. A response that never arrives holds its slot for as long as the client is willing to wait, so the practical size of your pool is the number of slots divided by the fraction that are stuck. Five hanging URLs out of a hundred, at concurrency 10, means half the pool is parked on a server that will never answer.

The experiment sends 100 URLs to a loopback server, five of which never respond, and varies only the total timeout. The ninety-five healthy requests take 20 ms each.

Total timeoutWall timeCompletedTimed outSlowest requestServer handlers cancelled
30 s30.21 s100030,011.7 ms0
5 s5.71 s9555,512.0 ms5
2 s2.20 s9552,003.3 ms5
0.5 s0.70 s955501.7 ms5
Table 12. A 100-URL job with five dead endpoints: 0.70 seconds at a 0.5-second timeout and 30.21 seconds at 30 seconds. The last row’s extra 5 results cost 29.5 seconds.

The first row is the one people ship. With a 30-second total timeout the run “succeeds” with 100 completions, because the hanging endpoints eventually answer, and it takes thirty seconds to do what it could have done in 0.7. The last row is the one to argue for: 0.5 seconds is short, yet it still completed 95 of 95 healthy requests, because a healthy request on this target takes 20 ms. A timeout is not a statement about how slow the world is allowed to be; it is a statement about how long a slot may be held.

import aiohttp

# total: the whole request, counted from the call - so time spent waiting for a
#        free connection in the connector pool is inside it, as are retries and
#        redirects
# connect: time to establish the TCP (and TLS) connection
# sock_read: time between two reads once the response has started
timeout = aiohttp.ClientTimeout(total=10, connect=3, sock_read=5)

# A per-attempt override for endpoints you know are slow:
slow_timeout = aiohttp.ClientTimeout(total=60, connect=3, sock_read=45)

Separate connect and read budgets are what make a short total timeout safe. A server that accepts the connection and then thinks for four seconds is doing legitimate work; a server that will not complete a TCP handshake in three seconds is usually down, and the connect budget is what stops one dead endpoint from consuming the whole total timeout. The other reason to keep the total budget explicit is that it covers the queue as well: in a saturated pool a request can spend most of its deadline waiting for a descriptor to free up, which is the pool-wait amplification measured in section 2 — 90 of 100 requests timing out without sending a byte — and a total that ignored queue time would hide it. In the run above, the five hanging endpoints were cancelled on the server side too — 5 cancelled handlers at every timeout setting — which is how you can tell the client closed the socket rather than merely losing interest in it.

9. Parsing: where the CPU goes, and why it is not where you think

Once the network is bounded, the next limit is the parser, and it is the component whose cost is most often guessed wrong. Five extractors were run over the same 109.1 KB product page with 200 product cards, each extracting the same 200 titles, each returning exactly 200 records. Timing and memory come from two separate passes, for a reason Table 13 carries its own column to show.

ExtractorMean per documentDocuments per secondSame loop, tracemalloc attachedTraced peak (Python heap)RSS growthRecords found
lxml.etree.HTML + XPath2.216 ms451.22.449 ms28.5 KB+0.0 MB200 / 200
lxml.html + XPath2.475 ms404.13.051 ms42.4 KB+0.1 MB200 / 200
stdlib html.parser subclass14.687 ms68.1111.859 ms40.7 KB+0.0 MB200 / 200
BeautifulSoup(lxml)42.424 ms23.6192.226 ms22,454.3 KB+10.5 MB200 / 200
BeautifulSoup(html.parser)60.049 ms16.7271.425 ms18,801.4 KB+35.4 MB200 / 200
Table 13. Five parsers, one document, 100 timed iterations each after warm-up. The fastest was 27.1 times faster than the slowest, and the two slowest were the two that allocate a Python object per node. The fourth column is the same loop with the tracer attached, and the gap between it and the third is the tracer’s own bill: 1.1x for lxml, 4.5x for BeautifulSoup, 7.6x for the stdlib parser — which is why the two columns come from different passes rather than one instrument doing both jobs.

The spread is 27.1 times between lxml.etree and BeautifulSoup on the stdlib parser, and the traced peak differs by a factor of 660: 28.5 KB against 18,801.4 KB. At 451 documents per second the lxml path digests 48 MB of HTML per second; at 16.7 documents per second the BeautifulSoup path is the bottleneck of the whole pipeline, and the network tuning in the previous six sections is irrelevant to it. The 4.5x and 7.6x in the fourth column are the reason those two rows used to read 271.8 ms and 110.6 ms: with tracemalloc attached, a parser that allocates a Python object per node pays for the tracer, and the number stops describing the parser.

Those memory figures need one warning before they are quoted anywhere, and the warning cuts both ways. tracemalloc traces allocations made by the Python allocator, so it sees BeautifulSoup’s objects and it cannot see lxml‘s: libxml2 builds its nodes in C, with malloc, outside the trace. That is why lxml shows 28.5 KB traced and +0.0 MB of RSS — not because it is free, but because each tree is freed before the next document and neither instrument catches the peak in between. The RSS column is the second opinion, and here it is not simply the larger one: BeautifulSoup on html.parser shows 18,801.4 KB traced against 35.4 MB of resident growth, while BeautifulSoup on lxml shows 22,454.3 KB traced against only 10.5 MB. Traced memory is a peak inside the window; RSS is a difference between two page counts, and an allocator that serves the peak out of arenas the process already owned reports less growth than it handed out. Neither column is a physical truth about the parser, so budget the larger of the two per parser and do not expect them to agree in direction.

The other cost of a parser does not show up in either column: while it runs, it owns the thread it runs on. A BeautifulSoup on the stdlib parser takes 60.049 ms per document for this 109.1 KB page, and those 60 milliseconds inside an async function are 60 milliseconds in which nothing else on the loop runs: no socket read, no timeout, no keep-alive, no other task. Forty of them in a row blocked this loop for 2,506.2 ms — which is how one slow parser turns a 20-request-per-second client into a stall. Handing each parse to a thread with await asyncio.to_thread(parse, html) keeps the loop free at the price of one thread hop per document: the same forty parses took 2.71 seconds and the worst gap fell from 2,506.2 ms to 165.5 ms. Bounding the workers to four at a time cut the gap to 126.0 ms without losing throughput. And a pure-Python parser holds the GIL while it parses, so threads free the loop without making the parse cheaper — 40 documents still took 2.63 to 2.71 seconds, against 2.51 inline. The one thing that changes the throughput is a second process: two workers parsed the same forty documents in 1.63 seconds, and the loop never stopped for longer than 14.4 ms.

Where the parse runsDocumentsWall timeDocuments per secondWorst event-loop gap
Inside the event loop402.51 s16.02,506.2 ms
asyncio.to_thread, all 40 at once402.71 s14.8165.5 ms
asyncio.to_thread, at most 4 at once402.63 s15.2126.0 ms
ProcessPoolExecutor, 2 processes401.63 s24.614.4 ms
Table 14. Forty BeautifulSoup(html.parser) parses of the same 109.1 KB page, and the worst gap a 1 ms ticker saw on the loop while they ran. A thread does not make a pure-Python parser faster — it only stops the parser from being the loop’s problem. A second process is the only row that changes the throughput, and it pays for that in pickling: 4.4 MB of HTML moved to a worker and 40 result lists moved back.

The bill for the process pool is the move. Forty documents at 109.1 KB is 4.4 MB over a pipe, and every result list comes back through it as well; at 5 MB per page that trade gets harder to like, and at 40 documents it looks free. It also costs a process per worker, each with its own BeautifulSoup import and its own tree in flight, and a start-up of a few hundred milliseconds that this 1.63 seconds already contains. The rule the table supports is narrow and worth stating: take the parse off the loop first, because a 2.5-second stall is a bug in any client; then decide between threads and processes by how much of the parse is Python. For lxml at 2.216 ms there is nothing to offload.

from typing import Iterable

import lxml.html


def extract_products(html: str) -> list[tuple[str, str]]:
    """Pull (title, price) out of a product page, without building a soup."""
    tree = lxml.html.fromstring(html)
    rows: list[tuple[str, str]] = []
    for card in tree.xpath("//li[@class='product-card']"):
        title = card.xpath(".//h3[@class='product-title']/text()")
        price = card.xpath(".//span[@class='price']/text()")
        if title and price:
            rows.append((title[0].strip(), price[0].strip()))
    return rows


def extract_all(pages: Iterable[str]) -> int:
    total = 0
    for page in pages:
        total += len(extract_products(page))
    return total

Whether 2.2 ms matters depends on the network in front of it. At the 120 ms latency used in section 1, parsing adds 1.8% to the time a slot is held. At 40 ms it adds 5.2%, and at 5 ms it adds 30.7% — the same 2.216 ms, three different verdicts. The same code is a rounding error against a slow API and the dominant cost against a fast one, which is why the first thing to measure when a run is slower than its arithmetic predicts is the parse, not the pool.

The second thing is that lxml.html.fromstring is not a general-purpose sanitizer, and it does not become one when you call a different constructor. It repairs malformed markup the way a browser does, which is what you want for scraping and not what you want for validation, and it will happily build a tree from input you did not expect. That is a reason to keep the parse away from the trust boundary rather than to change parsers: the tree is not the risk, and whatever the extracted text becomes next — HTML on a page, a line of SQL, an argument to a shell, a template — is. The 2.216 ms above is a speed measurement on a document this article generated; it says nothing about safety, and the fix for untrusted input is a sanitizer at the sink, not a different way to build the same tree.

10. Sessions: one pool, one close

A ClientSession owns three things worth keeping: the connection pool, the DNS cache and the cookie jar. Creating one per request throws all three away and turns every request into a TCP handshake. On a loopback interface the handshake is nearly free, which is exactly why this is worth measuring rather than asserting: the cost is small in milliseconds and large in connections, and connections are the resource the target counts.

PatternRequestsWall timereq/sTCP connections openedp50
One session, 20 concurrent3000.12 s2,581.8206.8 ms
One session, sequential3001.61 s186.315.3 ms
New session per request, 20 concurrent3000.18 s1,635.430010.5 ms
Table 15. The server counted distinct transports, so the connection column is the target’s view. A session per request opened 15 times as many connections, ran 1.6 times slower and added 3.7 ms to the median request — on loopback, where a handshake costs almost nothing.

Over a real network the same comparison is dominated by the round trips: a fresh TLS connection needs two or three round trips before the first byte of the response, and at 60 ms of RTT that is 120 to 180 ms added to every request in the batch. The loopback numbers above are the floor of the penalty, not the ceiling.

The other half of the session story is what happens when nobody closes it. Three hundred sessions were created, one per request, and deliberately kept referenced until the end of the run.

StateOpen descriptorsRSSWhat the process reports
Before the run841.9 MBnothing
300 unclosed sessions60846.9 MBnothing until garbage collection
After closing all 3008n/anothing
Table 16. Two descriptors per unclosed session when the server shares the process: one client socket and one server socket for each. Measured the same way with the server in its own process, the client’s table grew by 303 descriptors for 300 sessions — one socket per session — so at the default limit of 1,024 that client would have failed on its 1,021st unclosed session, with the same Errno 24 as the unbounded gather in section 2.

That table is the whole case for async with. The sessions in the successful runs above were all closed by a context manager; the 600 descriptors in the middle row are what an exception handler that skips the finally block leaves behind, and half of them belong to the test server rather than to the client. Counting only the client’s half is the honest number, and it is still one descriptor per abandoned session: three hundred leaks, three hundred sockets, and a process that can afford a thousand.

11. Memory: tasks, threads, and 39 MB of text

The reason to use asyncio for this job is not speed; a thread pool does the same network work. It is the cost per unit of concurrency, and the honest version of that claim is smaller and stranger than the folklore. Ten thousand coroutine objects that are never scheduled cost 1,880.2 KB, or 192.5 bytes each. Ten thousand scheduled tasks parked on an Event cost 18,842.8 KB, or 1,929.5 bytes each, and moved RSS by 26.4 MB. Both are fine; “a few megabytes” is not the number for the second one.

UnitCountTraced memoryPer unitRSS change
Coroutine object, never scheduled10,0001,880.2 KB192.5 bytesn/a
Scheduled Task, parked on an Event10,00018,842.8 KB1,929.5 bytes+26.4 MB
OS thread, blocked on an Event200n/a11.5 KB+2.2 MB
OS thread, blocked on an Event1,000 requested, 246 startedn/a12.5 KB+3.0 MB
Table 17. Measured on the same box in one process. The 1,000-thread run did not complete: it started 246 threads and then raised RuntimeError: can't start new thread on the next one.

The thread row is the interesting one, because the count is not the point. At roughly 12 KB of resident memory per thread, ten thousand threads would need 120 MB of stack pages — affordable on this box — yet the process refused to start thread number 247. The explanation that “it is address space” is a guess, and it is the wrong one. Two probes settle it. Starting threads until the OS says no, with the default 8 MB stack, reached 251 threads and then raised RuntimeError: can't start new thread with 252 threads in the process and 255 accounted to this user. Repeating the same loop with a 512 KB stack reached 252 and then 253 threads, and stopped at 256 for the user. Halving the stack size bought exactly one thread, which is the signature of a count limit and not of a memory limit: the ceiling is RLIMIT_NPROC, 256 here, and Linux counts every thread of the user against it — which is why the exact stopping point moves by a few threads between runs as other processes of the same user come and go. Read ulimit -u before you size a thread pool; on this machine the answer is 256, not ten thousand.

The second memory decision is bigger than tasks and threads combined: what you do with the responses. Ten thousand pages at 20 KB is 200 MB of text, and a list comprehension over gather keeps all of it alive at once. Two thousand payloads of 20 KB were processed both ways, once collected and once streamed.

ApproachRequestsText retained at the endPeak RSS growth
Collect every result in one list2,00039.1 MB44.1 MB
as_completed, drop the body after each result2,0000 MB0.4 MB
Table 18. Same 39.1 MB of payload, 110 times the memory when it is all held at once. The streaming version writes each record and lets the text go; the collecting version cannot finish before the last request because it needs the list.
import asyncio
import json

import aiohttp


async def stream_run(urls: list[str], sink_path: str, concurrency: int = 20) -> int:
    """Write one line per finished URL, holding one response at a time."""
    written = 0
    slots = asyncio.Semaphore(concurrency)
    connector = aiohttp.TCPConnector(limit=concurrency, limit_per_host=8, ttl_dns_cache=300)
    timeout = aiohttp.ClientTimeout(total=15, connect=5)
    async with aiohttp.ClientSession(connector=connector, timeout=timeout) as session:
        with open(sink_path, "a", encoding="utf-8") as sink:

            async def fetch(url: str) -> dict:
                async with slots:
                    try:
                        async with session.get(url) as resp:
                            text = await resp.text()
                            status = resp.status
                        return {"url": url, "status": status, "chars": len(text)}
                    except (aiohttp.ClientError, asyncio.TimeoutError, OSError) as exc:
                        return {"url": url, "status": None, "error": type(exc).__name__}

            tasks = [asyncio.create_task(fetch(url)) for url in urls]
            try:
                for fut in asyncio.as_completed(tasks):
                    record = await fut          # a record, never an exception
                    sink.write(json.dumps(record) + "\n")
                    sink.flush()
                    written += 1
            except asyncio.CancelledError:
                for task in tasks:
                    task.cancel()
                await asyncio.gather(*tasks, return_exceptions=True)
                raise
    return written

That block has three decisions in it, and each one is there because its absence was measured. The semaphore bounds what is in flight, so a million URLs are still twenty requests. The per-task try returns a record instead of raising, so a single 500 cannot end the loop. And the cancellation handler cancels and awaits the children before the session closes, so the function stops with the connections it owns rather than after them. Without the first two, the same 2,000 URLs and a salted one-in-a-hundred 500 produced 99 rows on disk and a ClientResponseError at 0.13 seconds: 112 requests had been sent, and every answer after the ninety-ninth was thrown away, for 15.2 MB of resident memory. With them, the same 2,000 URLs produced 2,000 rows in 0.64 seconds, no exception at all, and 2.0 MB of growth. The 0.4 MB figure in Table 18 is what the streaming decides; the 44.1 MB figure is what the same requests cost when the results are collected first and written afterwards.

12. Stopping a run without orphaning it

Every long run ends early sometimes: Ctrl-C, a SIGTERM from the scheduler, a CI timeout, a quota alarm. How it ends decides whether the next run starts from a clean process or inherits sockets, tasks and a half-written file. Two versions were measured. Both created 200 tasks against a one-second endpoint, then cancelled the supervisor after 0.25 seconds — the difference is whether the supervisor cancels and awaits its children.

ShutdownTasks still running 0.1 s laterOpen descriptors 0.1 s laterServer handlers cancelled
Supervisor cancelled, tasks created without references200400
client.run() cancelled: cancels and awaits its children0040
Table 19. Fire-and-forget tasks survive the cancellation of the function that created them. The 40 descriptors are 20 sockets at each end, and the server kept working on requests the client had already abandoned.

The orphan case is worse than it looks in a single run. Those 200 tasks continued, kept their sockets, and finished a second later with nobody to receive the results, which is the same silent loss as the missing return_exceptions in section 2 with a different cause. In a worker that restarts every few minutes, the abandoned requests are the ones the target counts against you.

import asyncio
import json
import signal
from pathlib import Path

from scrapekit import FetchResult


class Checkpoint:
    """One JSON line per attempt: a killed run resumes instead of restarting."""

    def __init__(self, path: Path) -> None:
        self.path = path

    def done(self) -> set[str]:
        """Only ok: true rows are finished work, and the last row for a URL decides.

        Reading every line as done is how a run that ended on a deferred
        Retry-After, an open circuit or a 503 skips those URLs next time and
        reports a batch as complete that never was.
        """
        if not self.path.exists():
            return set()
        state: dict[str, bool] = {}
        with self.path.open(encoding="utf-8") as fh:
            for line in fh:
                try:
                    row = json.loads(line)
                except json.JSONDecodeError:
                    continue
                if isinstance(row, dict) and isinstance(row.get("url"), str):
                    state[row["url"]] = row.get("ok") is True
        return {url for url, ok in state.items() if ok}


async def run_until_signalled(client, urls: list[str], path: Path, workers: int = 20) -> int:
    loop = asyncio.get_running_loop()
    stop = asyncio.Event()
    for sig in (signal.SIGINT, signal.SIGTERM):
        loop.add_signal_handler(sig, stop.set)

    done = Checkpoint(path).done()
    work: asyncio.Queue[str | None] = asyncio.Queue()
    for url in urls:
        if url not in done:
            work.put_nowait(url)
    results: asyncio.Queue[FetchResult | None] = asyncio.Queue()

    async def fetch_worker() -> None:
        while True:
            url = None
            taken = False
            try:
                url = await work.get()
                taken = True
                if url is None:               # one sentinel per worker, at the end
                    return
                results.put_nowait(await client.get(url))
            except asyncio.CancelledError:
                raise
            except Exception as exc:          # a per-URL failure is a row
                results.put_nowait(FetchResult(url=url or "", error=type(exc).__name__))
            except BaseException as exc:      # a bug in the loop is not a row
                results.put_nowait(
                    FetchResult(url=url or "", error=f"worker:{type(exc).__name__}")
                )
                raise                         # the caller surfaces it after cleanup
            finally:
                if taken:
                    work.task_done()

    async def write_worker() -> int:
        written = 0
        with path.open("a", encoding="utf-8") as sink:
            while True:
                result = await results.get()
                if result is None:
                    return written
                sink.write(json.dumps(result.as_row()) + "\n")
                sink.flush()
                written += 1

    async def close_queue() -> None:
        await work.join()                     # every URL fetched exactly once
        for _ in pool:                        # then one sentinel per worker
            work.put_nowait(None)

    async def drain() -> None:
        await asyncio.gather(*pool)

    pool = [asyncio.create_task(fetch_worker()) for _ in range(workers)]
    writer = asyncio.create_task(write_worker())
    stopper = asyncio.create_task(stop.wait())
    closer = asyncio.create_task(close_queue())
    drained = asyncio.create_task(drain())
    crash: BaseException | None = None
    try:
        # Two futures, once: the pool finishing, or the signal arriving. Nothing
        # here touches a task that is still running.
        await asyncio.wait({drained, stopper}, return_when=asyncio.FIRST_COMPLETED)
        if drained.done() and not drained.cancelled():
            crash = drained.exception()       # "it finished" is not "it succeeded"
    finally:
        for task in pool:
            task.cancel()
        outcomes = await asyncio.gather(*pool, return_exceptions=True)
        for task in (stopper, closer, drained):
            task.cancel()
        await asyncio.gather(stopper, closer, drained, return_exceptions=True)
        results.put_nowait(None)              # the writer drains, then returns
        written = await writer
        await client.close()
        if crash is None:
            for outcome in outcomes:          # a crash anywhere else in the pool
                if isinstance(outcome, BaseException) and not isinstance(
                    outcome, asyncio.CancelledError
                ):
                    crash = outcome
                    break
    if crash is not None:
        raise crash
    return written

Two simpler shapes of that loop are worth naming, because each one fails in a way that looks like success. The first takes asyncio.as_completed(tasks) and races the next result against the stop signal with asyncio.wait({fut, stopper}); on Python 3.12.16 the object as_completed yields is a coroutine, not a task, so the call raises TypeError: Passing coroutines is forbidden, use tasks explicitly — verified here, not inferred, and it fails on the first result rather than on the first signal. The second keeps the tasks in a list and cancels them in finally without awaiting them, so client.close() runs while they still hold connections.

A loop that gets both of those right can still be quadratic in its bookkeeping, which takes a review to notice and a counter to prove. The obvious way to race a batch against a stop event is to re-enter asyncio.wait on the pending set each time a result arrives: every call attaches a done callback to every task in the set and detaches it again when the call returns, so each result costs one registration for every URL still pending. Finishing 4,000 URLs that way costs 805,709 registrations; finishing 10,000 costs 10,304,737. That loop is not wrong — it buys a per-result question with a per-batch answer, and the bill grows faster than the work. The block above asks once, about two futures, and lets a queue do the bookkeeping: a fixed pool of workers takes URLs from one queue and puts results on another, a single writer drains the results, and the stop path is one task waiting on one event.

Two details in that block are the difference between a resumable run and one that only looks resumable. The checkpoint counts a URL as finished only when its last row says ok: true, because a row is a record of an attempt: a run that ended on a deferred 429, an open circuit or a 503 would otherwise skip exactly the URLs that still need fetching, and the next run would report a batch as complete that never was. And failure is a value in the worker, twice: a URL whose fetch raises becomes a row with the exception’s name, so one bad page does not cost the batch its remaining URLs; a worker that dies of something the loop cannot absorb is raised to the caller after the cleanup, because the shutdown path gathers the pool with return_exceptions=True so that it can always finish, and an exception that only ever reached that gather would end the run early and look exactly like a short, clean batch.

Both paths were run at 10,000 URLs, which is the batch size the title promises, against a server in its own process answering in 20 ms. To completion: 10,000 rows written, 10,000 lines on disk, 10.72 seconds (933.1 requests per second), zero tasks left and zero descriptors left. Interrupted by a real SIGINT 1.5 seconds in: 1,360 rows written and flushed, a total stop at 1.53 seconds, and again zero tasks and zero descriptors — the 20 ms that separates the two numbers is the time it took to cancel twenty in-flight requests and close the session. The old loop needed 13.93 seconds for the same 10,000 URLs, 3.2 seconds and 10,304,737 callback registrations more, and on the 1 ms server used to isolate the bookkeeping the two loops took 0.27 / 0.61 / 1.48 seconds at 1,000 / 2,000 / 4,000 URLs, against 0.29 / 0.52 / 0.93 for the pool: the pool grows with the work, the wait loop with the square of the batch. No traceback either way: the signal handler sets an event instead of raising, which is the difference between a scheduler’s SIGTERM ending a run and ending the process.

13. The module: one client that holds all of it

Every control in this article is small on its own. The failure mode of a scraping codebase is that they live in different files written by different people: a semaphore in the crawler, a connector in a helper, a retry decorator that predates both, and a session created somewhere in the middle. The module below is a single client that owns them together — 969 lines, no dependency outside aiohttp and the standard library, and 49 tests that run in about thirteen seconds against a loopback server.

It has one job: turn a list of URLs into a list of result records, with the eight decisions above made once. The retry loop is where they meet, so it is the part worth reading line by line.

import asyncio
from urllib.parse import urlsplit

import aiohttp

from scrapekit import (
    BreakerRegistry,
    FetchResult,
    HostCooldown,
    HostLimiter,
    RetryPolicy,
    TokenBucket,
    parse_retry_after,
)

RATE_LIMIT_STATUSES = frozenset({408, 425, 429})


class ScrapeClient:
    # Abbreviated class head: only the attributes the loop below touches.
    retry: RetryPolicy
    bucket: TokenBucket | None
    breakers: BreakerRegistry | None
    cooldowns: HostCooldown | None
    limiter: HostLimiter

    async def get(self, url: str, *, read_body: bool = True) -> FetchResult:
        started = self._clock()
        result = FetchResult(url=url)
        host = urlsplit(url).netloc or "unknown"
        breaker = self.breakers.for_host(host) if self.breakers is not None else None

        def held() -> bool:
            """True if the host is cooling down: defer this URL without a socket."""
            if self.cooldowns is None or self.cooldowns.remaining(host) is None:
                return False
            self.metrics.cooldown_skips += 1
            result.error = "host_cooldown"
            result.deferred = True
            return True

        for attempt in range(1, self.retry.max_attempts + 1):
            result.attempts = attempt
            if held():
                break
            if breaker is not None and not breaker.allow():
                self.metrics.fail_fast += 1
                result.error = "circuit_open"
                break
            if self.bucket is not None:
                await self.bucket.acquire()
            try:
                session = await self._ensure_session()
                async with self.limiter.slot(host):
                    if held():               # queued when the gate closed
                        break
                    t_in = self._clock()
                    async with session.get(url, allow_redirects=True) as resp:
                        body = await resp.read() if read_body else b""
                        result.net_ms += (self._clock() - t_in) * 1000
                        result.status = resp.status
                        result.bytes_read = len(body)
                        retry_after = resp.headers.get("Retry-After")
                        if 200 <= resp.status < 300:
                            result.ok = True
                            result.text = body.decode(resp.charset or "utf-8", errors="replace")
                            if breaker is not None:
                                breaker.record_success()
                            break
                        result.error = f"http_{resp.status}"
                        if resp.status not in self.retry.retry_statuses:
                            if breaker is not None:
                                breaker.record_success()   # a 404 is a reachable host
                            break
                        if resp.status not in RATE_LIMIT_STATUSES:
                            if breaker is not None:
                                breaker.record_failure()
                            delay = None
                        else:
                            asked = parse_retry_after(retry_after)
                            delay = self.retry.backoff(
                                attempt, asked, self._rng
                            )
                            if delay is None:            # "come back in an hour"
                                result.error = "retry_after_exceeded"
                                result.deferred = True
                                if self.cooldowns is not None and asked is not None:
                                    self.cooldowns.hold(host, asked)
                                break
            except (aiohttp.ClientError, asyncio.TimeoutError, OSError) as exc:
                result.error = type(exc).__name__
                delay = None
                if breaker is not None:
                    breaker.record_failure()

            if result.deferred or attempt == self.retry.max_attempts:
                break
            if delay is None:
                delay = self.retry.delay_for(attempt, self._rng)
            await self._sleep(delay)  # outside the slot: a sleeping task holds nothing

        if (
            not result.ok
            and not result.deferred
            and breaker is not None
            and result.status in RATE_LIMIT_STATUSES
        ):
            breaker.record_failure()   # asked to wait and ran out of retries: one failure

        result.elapsed_ms = (self._clock() - started) * 1000
        self.metrics.observe(result)
        return result

Read it as a checklist rather than as code. The breaker is consulted before any work, so an open circuit costs a counter increment rather than a request — and it is the breaker for this host, so an outage elsewhere does not reach it. The host gate is consulted twice, before the bucket and again inside the slot: the first check keeps a URL for a held host from queuing for a token it will not spend, the second one keeps a URL that was already queued from opening a socket after the gate closed. The bucket is acquired before the slot, so rate limiting cannot starve a host slot. The slot wraps the request and nothing else, so the retry sleep happens outside it. Retry-After is read before the status is classified, so the server’s own number always wins over the policy’s guess: obeyed exactly, jittered upward so a batch does not return in lockstep, and refused rather than shortened when the number is longer than 60 seconds, in which case the URL is recorded as deferred, the host is held for the rest of its queue, and both belong to a later run. A 4xx that is not a rate limit resets the breaker instead of tripping it, and a 429 only becomes a failure when the last retry is spent — a deferred 429 is not a failure, because the host answered. Every exit path records a result, including the fail-fast one, which is why a run of 10,000 URLs always returns 10,000 rows.

Two details are there for the tests rather than for production, and both earn their place. The clock and the sleep function are injected, so a test can assert that a 429 with Retry-After: 1 really waited 1 second without spending one. And connector_limit is validated against concurrency at construction time, because the failure it prevents — a connector below the semaphore — is silent at runtime and obvious at startup.

import asyncio
import time

from scrapekit import TokenBucket


def run(coro_fn):
    return asyncio.run(coro_fn())


def test_token_bucket_enforces_rate():
    async def inner():
        bucket = TokenBucket(rate=20, capacity=1)
        started = time.monotonic()
        for _ in range(20):
            await bucket.acquire()
        return time.monotonic() - started

    elapsed = run(inner)
    assert 0.85 <= elapsed <= 1.3, elapsed

That test would pass under any implementation that takes 20 tokens at 20 per second, including a wrong one that sleeps in the wrong place; the assertion is on the elapsed floor, not on the mechanism, so a refactor that keeps the rate keeps the test. A handful of the 49 tests work that way, including the one that asserts a 429 carrying Retry-After: 1 waits at least 0.95 seconds even though the policy’s own base delay is 10 ms — a floor no client that ignores the header can meet — and its opposite, which asserts that the same 429 carrying Retry-After: 3600 comes back as one deferred row in under a second with no second request, and its neighbour, which queues 20 URLs for that host and asserts that the first answer costs one request and nineteen host_cooldown rows. The rest cover the parts that are pure arithmetic or pure state: the backoff schedule, the jitter bounds, the Retry-After jitter and its upward-only rule, the deferral past the 60-second limit, the cooldown’s expiry, the breaker’s transitions, the 404 rule, the per-host registry, the percentile helper, the checkpoint’s rule that only ok: true rows are finished — including one that writes a deferred row and an error row and asserts the next run fetches both again — and the two loops’ promises that 12 URLs produce 12 rows even when two of them answer 500, that a fetch which raises becomes an error row rather than a missing one, that a worker which dies of a bug is raised to the caller instead of being collected by the shutdown path, and that 50 URLs stopped by an event leave nothing running.

What is printed in this article is the limiter, the bucket, the per-host breaker registry, the host cooldown, the Retry-After parser, the retry loop, the streaming writer and one test. What is not printed is the rest of the module — the metrics recorder, the JSONL checkpoint, the fetch_all convenience wrapper, the queued writer inside the signalled run and the module’s own test fixtures — and it is not published yet; it is being packaged as a repository, and this section will carry the link when it exists. Until then, the pieces above are complete enough to assemble on their own: each was executed either by the test suite or by one of the experiments in this article, and the two functions whose failure modes are measured in sections 11 and 12 — the streaming loop that threw away every answer after the first 500, and the signalled shutdown that left 200 tasks running — are shown there with the cost on both sides.

14. The run report that replaces “it seemed fine”

A scraper that prints its successes is a scraper you cannot operate. The two clients in section 2 differ in every outcome that matters and both exit with status zero, so the only thing that separates them is what they counted. The end-to-end comparison is a 300-URL run against a target with a real 20 req/s quota, a 5-token burst allowance, and a rule that bans a client sending more than 60 requests inside one second for five seconds.

ClientCompletedRequests seen by the targetBusiest second at the targetBannedWall time
Naive gather, 3 tries, 50 ms backoff5 of 300890 (61 x 429, 824 x 403, 5 x 200)521Yes1.49 s
Bounded client, bucket capacity 15300 of 300310 (10 x 429, 300 x 200)30No19.71 s
Bounded client, bucket capacity 1300 of 300300 (300 x 200)15No20.45 s
Table 20. The naive client finished first and completed 1.7% of the work; the bounded client was 13.7 times slower and completed all of it. “Banned” means the target refused every request for five seconds after the burst. The second and third rows are the same client at the same 15 req/s and differ only in the bucket’s burst allowance.

The second row is the one worth stopping on, because it looks impossible: a client that sent 15 requests per second to a 20-per-second target collected 10 rejections, 3.2% of its requests, in the first second. The cause is not the rate. It is the word first. That run built its token bucket with capacity = rate, which is exactly the mistake section 5 warns about: the bucket starts full, so it admits 15 requests at t=0 and then refills at 15 per second, while the target allows a burst of five and then 20 per second. Ten of those first fifteen arrivals were over the allowance before the client had done anything wrong in steady state. The third row changes one number — capacity 1 instead of 15 — and the rejections go to zero over the same 300 URLs, with the target’s busiest second at 15. Same code, same rate, same quota; only the burst was wrong. It is also why the alerting threshold below is stated as a share rather than a count: 10 rejections in 310 requests is a 3.2% signal that a bucket is misconfigured, and 10 in 100,000 is noise.

The numbers below are from the last row of Table 20, the run with the correct burst allowance. That report tells the same story as the server’s log without needing it:

FieldValue in the 300-URL runWhat would have caught the naive run
requests300Nothing on its own
ok / failed300 / 05 / 295 in the naive run
success_rate1.00.0167
retries0590 retries, all wasted
by_status200: 300403 and 429 dominating
p50_net_ms41.4 msNot reported at all
p95_net_ms42.3 msNot reported at all
p50_ms (queue included)10,250.8 msNot reported at all
p95_ms (queue included)19,418.7 msNot reported at all
Table 21. One run’s report. The two latency columns are the useful pair: a request took 41.4 ms of network time inside a queue that made it take 10,250.8 ms end to end, which is exactly what a 15 req/s bucket does to 300 URLs.

The distinction between p50_net_ms and p50_ms is worth a sentence of its own. Total elapsed time is the number the caller experiences, and in a rate-limited run it is dominated by waiting for a token — 10,250.8 ms of it against 41.4 ms of actual request. If you report only the total, a healthy 40 ms target looks broken; if you report only the network time, a queue that will take twenty minutes to drain is invisible. Both, or neither.

Three alerting thresholds follow directly from the measurements in this article: a success rate below 0.98, a 429 share above 2% of requests, and a retry count above 10% of the request count. The first catches the naive run immediately; the second catches a rate limit you set too high, or a burst allowance the target does not share, before the target starts refusing in numbers; the third catches a target that is failing slowly rather than loudly. The last row of Table 20 sits at 0% of 300 requests and the row above it at 3.2%, so the threshold separates them on the first sample rather than after a ban.

15. Politeness, and what this machine could not test

Everything above is a technical control, and technical controls only decide how politely you break a rule. The rule itself is robots.txt, the terms of the API, and the ordinary fact that the server belongs to somebody else. The cost of checking is small enough to measure: parsing a 15-line robots file takes 0.038 ms and a can_fetch decision takes 3.6 microseconds, which is nothing next to a 40 ms request.

AgentURLAllowed
TechBobbyBot/products/1Yes
TechBobbyBot/private/dataNo
TechBobbyBot/private/preview/1No: the first matching rule wins
OtherBot/admin/usersNo
OtherBot/products/1Yes
BadBot/products/1No: Disallow: /
Table 22. Six decisions from a 15-line robots file. The third row is the one to notice: the file carries an explicit Allow: /private/preview/ after a broad Disallow: /private/, and the standard-library parser says no.
import urllib.robotparser
from urllib.parse import urlsplit

import aiohttp


async def load_robots(
    session: aiohttp.ClientSession, url: str
) -> urllib.robotparser.RobotFileParser:
    """Fetch and parse robots.txt once per origin, per run."""
    parts = urlsplit(url)
    parser = urllib.robotparser.RobotFileParser()
    robots_url = f"{parts.scheme}://{parts.netloc}/robots.txt"
    async with session.get(robots_url) as resp:
        if resp.status == 200:
            parser.parse((await resp.text()).splitlines())
        else:
            parser.parse([])
    return parser

Two behaviours of urllib.robotparser are worth knowing before you trust it, both verified on Python 3.12.16. It returns the first rule that matches a path rather than the longest, so a narrow Allow placed after a broad Disallow is ignored — the RFC’s longest-match rule is not what the standard library implements. And it accepts a Crawl-delay only when the value is an integer: Crawl-delay: 0.5 under a named agent is silently dropped, while Crawl-delay: 1 under * is read, so crawl_delay("TechBobbyBot") returned None against 1 for an agent with no entry of its own. Neither behaviour is a bug you can fix by passing a flag; both are reasons to read the file you are obeying rather than only its parsed verdict.

The nine rules that kept these runs inside the limits, in the order they matter:

  1. Fetch robots.txt once per origin and respect the crawl delay it declares. The Crawl-delay line is the only place a site states a rate in its own words.
  2. Send a User-Agent with a product name and a URL. An ops engineer reading a log can tell a crawler from an attack by that one header.
  3. Cap per host. Two hundred concurrent requests to one origin is a denial of service with a friendly name.
  4. Prefer an official API with a key. One bulk endpoint can replace a hundred page fetches, which is the largest politeness win available.
  5. Honour 429 and Retry-After without argument. Treat the first 429 of a run as a signal to lower the rate for the rest of it, and when the server asks for longer than you are willing to wait, hold the whole host and defer its queue: deferring one URL and letting the other 199 find out for themselves is the same rudeness with better bookkeeping.
  6. Cache responses on disk, including the raw bodies. Reruns during development should cost zero requests.
  7. Use conditional requests: ETag and If-Modified-Since turn a poll into a 304 that costs no payload.
  8. Do not rotate identities to raise volume. Rotating proxies around a limit you were told about converts a speed limit into a terms violation.
  9. Log status codes as metrics, not just errors. A wall of 200s from a CDN can be a challenge page, and a rising 429 share is feedback you asked for.

What this machine could not test, and therefore what this article does not claim: real remote targets and their WAFs, TLS handshake latency over a real network, HTTP/2 multiplexing, IPv6 path behaviour, proxy rotation, Scrapy’s scheduler, Playwright and browser-based rendering, Windows and macOS event loops, and httpx‘s client. Two of those matter enough to state plainly. The loopback server has no TLS, so every handshake cost in section 10 is the floor rather than the real number. And the ban in section 14 is a five-second penalty invented for the test, not a model of any particular provider’s enforcement; the 20 req/s quota is invented too. The client behaviour those runs measure is real; the target’s policy is a stand-in.

The one comparison this article used to leave out is between asyncio and a thread pool for the same job, and it is measured now. Two thousand URLs at 120 ms with 200 in flight, both clients in one process against a server in another: asyncio finished in 1.37 seconds and grew by 5.9 MB; a thread pool with 200 workers, one keep-alive connection per thread, finished in 1.31 seconds and grew by 6.9 MB, with 203 threads alive at the peak against 2. Within 5%, and the thread pool is the faster of the two. Throughput is not the reason to choose asyncio here, and this article does not claim it is: a semaphore, a bucket and a breaker are shared state that coroutines can hold without locks, the queue in section 12 is one object rather than two hundred hand-offs, and the shutdown is one cancellation instead of two hundred thread joins.

FAQ

How many requests per second can asyncio handle?

On this machine, a single client with a semaphore of 20 sustained 161.5 req/s against a 120 ms server and 3,490.5 req/s against a zero-latency one, which is the same client code with a different target. That second figure is a 20-millisecond sample of sixty requests, not an afternoon’s rate. At 100 concurrent requests it reached 774.5 req/s and at 200 it reached 1,321.1, both against the 120 ms server. The client’s ceiling is therefore above 3,000 req/s for short requests, and irrelevant: what limits a real run is the target’s capacity and your willingness to spend it.

Is asyncio faster than threads for web scraping?

For pure network I/O the two are comparable, because both spend their time waiting — measured, not assumed: 2,000 URLs at 120 ms with 200 in flight took 1.37 seconds with asyncio and 1.31 seconds with a 200-worker thread pool holding one keep-alive connection each. What differs is the cost per unit and the coordination. Measured on the same box, a scheduled task parked on an event cost 1,929.5 bytes and an OS thread blocked on an event cost 11.5 KB of resident memory, but the process refused to start its 247th thread while it accepted 10,000 tasks without complaint. The refusal is RLIMIT_NPROC, a per-user cap of 256 processes and threads on this box, not memory: halving the thread stack from 8 MB to 512 KB bought exactly one more thread. asyncio wins on coordination rather than throughput: a semaphore, a token bucket and a breaker are shared state that coroutines hold without locks, and shutting down 10,000 tasks is one cancellation.

What concurrency limit should I use with asyncio.Semaphore?

Derive it from Little’s law: concurrency equals target requests per second multiplied by average latency in seconds. A target that tolerates 10 req/s at 200 ms needs two slots; 167 req/s at 120 ms needs twenty. The measured sweep matched that prediction within 3.3% at 20 slots and within 6.7% at 50. Start one step below the number you calculated and raise it only while the error rate stays near zero.

Why does asyncio raise “Too many open files”?

Because every in-flight connection is a file descriptor. Measured with the server in its own process, an uncapped gather over 2,000 URLs answered 1,018 of them, reached the 1,024-descriptor limit and failed the other 982 with Errno 24 — all of it inside 0.60 seconds. Raising ulimit -n moves the wall without removing it; a semaphore of 20 answered 2,000 of 2,000 in 12.32 seconds at 26 descriptors.

Should I use aiohttp or httpx for async scraping?

Both are capable, and this article does not choose between them: every measurement here was taken with aiohttp 3.14.5, and httpx was not part of the test matrix, so any claim about its relative speed would be a guess. The patterns transfer directly — a semaphore, a token bucket, a connector limit and Retry-After handling are the same arithmetic in either client — so decide by the rest of your codebase rather than by throughput.

How do I avoid getting blocked while scraping at scale?

Stay under the target’s stated rate, honour Retry-After, identify yourself in the User-Agent, cap concurrency per host, and stop when the 429 share rises. In the measured comparison, a naive fan-out sent 521 requests in one second to a target that allows 20 per second, completed 5 of 300 URLs and was banned; the bounded client kept the target’s busiest second at 15 requests and completed 300 of 300 in 20.45 seconds. The same bounded client at 15 req/s with the wrong burst allowance still collected 10 rejections, so the burst is part of the rate.

How many retries should I allow, and what backoff?

Seven attempts with a base of 0.25 seconds, doubling and capped at 10 seconds, and full jitter. The worst case is 15.75 seconds of waiting per URL, which is the number your total timeout has to accommodate. A Retry-After from the server replaces that schedule: obeyed exactly, never shortened, plus up to 10% of upward jitter so 200 clients told the same number do not return in the same millisecond (185 of them did without it; 50 with it). That jitter is not a rate limit — a tenth of a second still leaves a burst — so the throughput has to come from the token bucket in front: with a bucket of 20 per second, the same 200 retries arrive at 20 per second and never more than one in 20 ms. When the server asks for longer than 60 seconds the URL is marked deferred for a later run and the whole host is held, so the rest of its queue costs no requests. Without jitter on your own backoff, 200 retries landed inside 19.0 ms and all 200 arrived in a single 20 ms window; with full jitter they spread over 494.1 ms and the peak fell to 16.

Is BeautifulSoup too slow for scraping at scale?

For high volume, yes. On the same 109.1 KB document with 200 product cards, BeautifulSoup with the stdlib parser took 60.049 ms and lxml.etree took 2.216 ms per document, a factor of 27.1, and the traced peak was 18,801.4 KB against 28.5 KB. The RSS growth was larger still for BeautifulSoup — 35.4 MB against nothing measurable — because tracemalloc cannot see lxml‘s C allocations, and because the two instruments measure different things: BeautifulSoup on lxml shows more traced memory (22,454.3 KB) than resident growth (10.5 MB). BeautifulSoup is the right tool for exploratory work on a handful of pages; it is the bottleneck when a run is measured in tens of thousands, and off the event loop either way.

Written by TechBobby Engineering — an independent engineer publishing measured Python production runbooks. Every figure in this article came from one of twenty-six experiment scripts or the module’s test suite, executed on Python 3.12.16 in a two-vCPU Linux container with 1,998 MB of RAM, glibc 2.41, aiohttp 3.14.5 and lxml 6.1.3, with RLIMIT_NOFILE at 1,024 and RLIMIT_NPROC at 256. The client, limiter, bucket, per-host breaker, host cooldown, retry loop and streaming writer printed above are the ones that ran; the rest of the 969-line module and its 955-line test suite are not published yet and will be linked here when the repository is up. Claims this machine could not verify — real remote targets, TLS cost, HTTP/2, IPv6, proxies, Scrapy, Playwright, httpx, Windows and macOS — are listed as out of scope in section 15 instead of being presented as measurements.

This article is part of a series on Python behaviour that only shows up in production. The closest neighbours are the other client-side ones: httpx AsyncClient in production, where the same pool produces PoolTimeout and a keep-alive retry storm, and pytest-asyncio in production CI, where the tasks this client cancels become leaked tasks in a test.

For the layers a scraping worker usually sits on: memory leaks in Celery and asyncio workers for the RSS growth a long run produces, Celery production architecture for the queue that schedules the run, FastAPI on Gunicorn and UvicornWorker for the event loop the client shares, ProcessPoolExecutor in production for the parsing pool at the other end of the pipeline, SQLAlchemy 2.0 async for writing the results, Redis caching and distributed locks for sharing the politeness budget across workers, PostgreSQL slow query triage for the table the records land in, Docker multi-stage builds for Python for the image that carries the client, and The TechBobby Stack, the tooling map these runbooks belong to.

Take the next step

If you want the working pieces without retyping them, the Python Excel Automation Starter Pack on Gumroad is free to download and carries the same bounded-client patterns wrapped around spreadsheet output: five scripts, plain Python, and nothing beyond the standard library and openpyxl.

The newsletter is weekly and short: one automation pattern, one measurement, one thing that broke. No launch announcements. If you run scraping or automation work of your own, reply to any issue and I read every reply.


Keep reading

Get the next essay and every new code pack before anyone else — subscribe to the weekly letter. Free tier first, always.