Fix Connection Pool Exhaustion in Your Scraper
Throughput collapses and latencies spike, yet no URL returns an error. Diagnose connection pool exhaustion in your scraping worker and size the pool correctly.
On this page
Symptom Profile: Throughput Falls 80% While Every Request Still Returns 200
Your scraper looks healthy. Dashboard is green. Status-code mix shows 100% 2xx. And yet your throughput graph looks like someone cut a wire: 240 pages/min this morning, 40 pages/min now. Latencies climbed from a p50 of 350 ms to a p99 of 18 seconds, but nothing failed. No timeouts. No 5xx. No connection errors.
That combination — collapsing throughput, spiking tail latency, zero errors — is the fingerprint of connection pool exhaustion. Every task in your worker is alive, every request eventually succeeds, but most of them spend their life waiting in line for a pooled connection. The queue grows, the tail latency grows with it, and your effective concurrency drops to the pool size no matter how many tasks you spawn.
Before you touch anything, rule out the lookalikes. Three other failure modes produce similar graphs, and each has one metric that separates it from pool exhaustion:
| Lookalike | Throughput | Tail latency | Non-2xx | Distinguishing metric |
|---|---|---|---|---|
| Pool exhaustion | Collapses, then plateaus | Climbs steadily | Zero | Connection acquisition wait (time spent queuing for a connection, not on the wire) |
| Slow origin server | Collapses proportionally to added origin latency | Climbs with p50, not just p99 | Zero or sporadic 5xx | p50 fetch time rises — the median request itself got slower |
| DNS resolution stalls | Collapses in bursts | Spikes in multi-second steps | Zero, then bursty timeouts | Time spent in getaddrinfo, visible via resolv timing or client trace hooks |
| Event-loop blocking | Collapses in sawtooth | Freezes entire event loop, all tasks stall together | Zero | Loop lag — every task stalls simultaneously, not just the queued ones |
Here’s a 10-minute metrics excerpt from a scraping worker hitting https://store.example.com/sitemap.xml pages. Read the wait_conn column — that’s tasks queued for a connection:
minute req/s p50 p95 p99 2xx% wait_conn(avg)
1 4.0 310ms 480ms 610ms 100 0
2 4.0 305ms 470ms 590ms 100 0
3 3.9 312ms 490ms 640ms 100 2
4 1.6 340ms 2.1s 4.8s 100 47
5 0.8 355ms 5.9s 11.2s 100 138
6 0.8 349ms 6.4s 12.9s 100 151
7 0.7 351ms 6.7s 14.1s 100 158
8 0.7 348ms 6.9s 15.5s 100 161
9 0.7 350ms 7.0s 15.8s 100 162
10 0.7 352ms 7.1s 16.3s 100 163
Three things to notice. First, the p50 barely moves — the median request that gets a connection is as fast as ever. Second, p95/p99 explode while p50 stays flat, which is exactly what a growing queue looks like: the wire time is unchanged, the queueing time is not. Third, throughput doesn’t decay to zero — it plateaus around 0.7 req/s. A plateau means a hard cap is being hit, and the cap is the pool. Slow origins decay smoothly; pool exhaustion hits a wall and stops.
If your graph shows that shape, stop debugging the network. The network is fine. Your tasks are queuing.
Confirm the Diagnosis: Measure Connection Acquisition Wait, Not Just Request Latency
Latency alone can’t prove this. A request that took 8 seconds might have spent 7.9 seconds waiting for a connection and 100 ms on the wire, or the reverse. You need to split request time into acquisition wait and exchange time, and you need to watch the pool’s own counters while the worker runs.
With httpx, the pool doesn’t expose counters directly, but you can wrap acquisition with a semaphore-style shim or — simpler and good enough — sample the transport’s connection tracker every second. Here’s a monitor I’ve used on live workers:
import asyncio, time, json
async def watch_pool(client, interval=1.0, duration=60):
"""Sample pool occupancy every second while the worker crawls."""
rows = []
transport = client._transport
pool = transport._pool # httpx HTTPConnectionPool internals
end = time.monotonic() + duration
while time.monotonic() < end:
open_conns = len(pool.connections)
idle_conns = sum(1 for c in pool.connections if c.is_closed is False)
# requests waiting in pool._requests for a connection to free up
waiting = len(getattr(pool, "_requests", []))
rows.append({
"ts": round(time.monotonic() % 1000, 1),
"open": open_conns,
"idle": idle_conns,
"waiting_for_conn": waiting,
})
await asyncio.sleep(interval)
return rows
And separately, time each fetch in two phases:
async def timed_fetch(client, url):
t0 = time.perf_counter()
req = client.build_request("GET", url)
# acquisition happens when the response context opens
resp = await client.send(req, stream=False)
t1 = time.perf_counter()
await resp.aread()
t2 = time.perf_counter()
return {
"acquisition_wait_ms": round((t1 - t0) * 1000, 1),
"exchange_ms": round((t2 - t1) * 1000, 1),
"total_ms": round((t2 - t0) * 1000, 1),
}
Run the worker against store.example.com sitemap pages for 60 seconds with 200 concurrent tasks and a default httpx AsyncClient. Here’s a representative log excerpt:
[00:12] open=10 idle=0 waiting=0 acq_wait p50=3ms
[00:20] open=10 idle=0 waiting=23 acq_wait p50=180ms
[00:28] open=10 idle=0 waiting=71 acq_wait p50=640ms
[00:36] open=10 idle=0 waiting=134 acq_wait p50=2.9s
[00:44] open=10 idle=0 waiting=150 acq_wait p50=6.1s
[00:52] open=10 idle=0 waiting=163 acq_wait p50=8.4s
[00:60] open=10 idle=0 waiting=168 acq_wait p50=9.1s
exchange p50 across run: 298ms (flat)
That’s the diagnosis, in one log. open=10 — the httpx default pool caps at 10 keepalive connections per host. idle=0 — every connection is busy, always. waiting climbs from 0 to 168 and stays there. Meanwhile the exchange time — the actual on-the-wire fetch against store.example.com — sits flat at ~300 ms the entire run. The origin isn’t slow. The pool is small. Two hundred tasks are fighting over ten connections.
If idle were high while waiting climbed, the problem would be a leak — connections never returned. Here, idle=0 with waiting>0 means connections are being held by tasks that aren’t using them. That distinction determines which fix applies, so log both.
Reproduce It Locally: A Throttled Mock of store.example.com
You will not debug this against a production target. You need a deterministic reproduction: same shape, same numbers, every run. A mock server with a concurrency cap and a fixed processing delay gives you that.
# mock_store.py
import asyncio
from aiohttp import web
CONCURRENCY_CAP = 20 # origin can only serve 20 at a time
PROCESSING_DELAY = 0.3 # 300 ms per response
sem = asyncio.Semaphore(CONCURRENCY_CAP)
async def handle_listing(request):
async with sem:
await asyncio.sleep(PROCESSING_DELAY)
return web.json_response({
"url": str(request.url),
"products": [{"id": i, "price": f"{19.99 + i:.2f}"}
for i in range(50)],
})
async def handle_sitemap(request):
async with sem:
await asyncio.sleep(PROCESSING_DELAY)
return web.Response(text="\n".join(
f"https://store.example.com/listing/{i}" for i in range(1000)
), content_type="text/xml")
app = web.Application()
app.router.add_get("/listing/{id}", handle_listing)
app.router.add_get("/sitemap.xml", handle_sitemap)
if __name__ == "__main__":
web.run_app(app, host="127.0.0.1", port=443 is None and 8080 or 8080)
The semaphore is the point. It models an origin that itself throttles — which most real storefronts do — so the mock punishes you for unbounded concurrency the same way production does, without banning you.
Point your existing scraper at it without touching its URL config. Add one line to your hosts file:
127.0.0.1 store.example.com
Then a single env var, assuming your scraper reads SCRAPE_BASE_URL (most do; if yours hardcodes, refactor that first — you’ll want it for staging environments anyway):
export SCRAPE_BASE_URL="http://127.0.0.1:8080"
python mock_store.py &
python -m yourscraper.worker --concurrency 100 --duration 30
Expected output from a 30-second run with 100 concurrent tasks and an exhausted pool:
30s run, 100 tasks, pool cap 10
requests completed: 84
throughput: 2.8 req/s
p50 acquisition: 3.4s
p95 acquisition: 11.9s
p50 exchange: 302ms <- unchanged, origin is fine
84 requests in 30 seconds from 100 concurrent tasks. Do the math: with a 300 ms exchange and a 10-connection pool, the theoretical ceiling is 10 / 0.3 ≈ 33 req/s, but the pool-holding anti-pattern (next section) drags it far below that. If you can reproduce the cliff locally in under 30 seconds, you can measure every fix against the same workload. That’s the whole reason to build the mock.
Root Cause: One Borrowed Connection Pinned for the Entire Scrape Task
Here’s the anti-pattern. I’ve seen this shape in production scrapers more times than I can count, usually written by someone who was told “always use a context manager” and applied it at the wrong granularity:
async def scrape_product(client, slug):
"""BAD: pins a pooled connection for the entire task lifetime."""
async with client.stream(
"GET", f"https://store.example.com/product/{slug}"
) as resp:
# Connection is now BORROWED from the pool.
# Chunked parsing while holding the connection.
# The parser yields on every await, but the connection
# stays checked out the whole time.
products = []
async for line in resp.aiter_lines():
products.append(parse_line(line))
# <- connection sits idle-but-unavailable here
# Politeness sleep, INSIDE the stream context.
# Connection held for 2-5 s doing literally nothing.
await asyncio.sleep(random.uniform(2, 5))
# <- connection still pinned
# Retry loop, also inside the context. If the parse
# failed and we back off with exponential delay, the
# connection is held through every backoff sleep.
for attempt in range(5):
try:
return normalize(products)
except ParseError:
await asyncio.sleep(2 ** attempt)
# <- connection pinned through backoff
One task, one connection, held for the parse, the politeness sleep, and up to 31 seconds of cumulative retry backoff. With a 10-connection pool, ten tasks are all it takes to starve the other ninety.
The second anti-pattern is the mirror image — no reuse at all:
async def scrape_product_bad(slug):
"""BAD: new client per task, fresh TLS handshake every request."""
async with httpx.AsyncClient() as client: # new pool per call
resp = await client.get(
f"https://store.example.com/product/{slug}"
)
# client closed; any keepalive connection to store.example.com
# is discarded. Next task pays a full TCP + TLS handshake again.
return resp.json()
This one doesn’t show pool exhaustion — it shows up as a handshake tax on every request and, on real targets, as a suspicious pattern of fresh connections that anti-bot systems love. Both bugs cost you the same thing: the pool never does its job. One version pins connections too long, the other throws them away before they can be reused. If your code contains both (I’ve seen it), the graphs look like neither clean failure mode, which is why you measure instead of guessing.
Fix 1: Shrink the Critical Section to the Network Exchange Only
The rule: a pooled connection is borrowed for the HTTP exchange and nothing else. Parse, sleep, and back off with zero connections in hand.
async def scrape_product(client, slug):
"""GOOD: connection held only for the byte exchange."""
url = f"https://store.example.com/product/{slug}"
# --- connection-held region: as short as possible ---
async with client.stream("GET", url) as resp:
resp.raise_for_status()
raw = b""
async for chunk in resp.aiter_bytes():
raw += chunk
# --- connection is BACK IN THE POOL here ---
# Everything below runs with zero connections borrowed.
products = parse_listing(raw) # CPU work, no connection
await asyncio.sleep(random.uniform(2, 5)) # politeness, no connection
for attempt in range(5):
try:
return normalize(products)
except ParseError:
await asyncio.sleep(2 ** attempt) # backoff, no connection
raise ScrapeError(f"unparseable listing: {url}")
The diff that matters, side by side:
async with client.stream("GET", url) as resp:
- products = []
- async for line in resp.aiter_lines():
- products.append(parse_line(line))
- await asyncio.sleep(random.uniform(2, 5))
- for attempt in range(5):
- try:
- return normalize(products)
- except ParseError:
- await asyncio.sleep(2 ** attempt)
+ resp.raise_for_status()
+ raw = b""
+ async for chunk in resp.aiter_bytes():
+ raw += chunk
+
+ products = parse_listing(raw) # moved out
+ await asyncio.sleep(random.uniform(2, 5)) # moved out
+ return normalize(products) # moved out (retry
+ # wrapper stays outside too)
Everything below the async with block moved out of the connection-held region. That’s the entire fix.
Measured against the local mock, with 100 concurrent tasks:
before: pool cap 10, waiting peaked at 163, throughput 2.8 req/s
after: pool cap 10, waiting peaked at 0, throughput 31.4 req/s
max connections actually open at once: 12
Waiting count drops to zero because no task ever holds a connection while doing anything else. Note the 12 open connections against a cap of 10 — httpx will open extra connections transientally under burst load; that’s fine, and it’s why the waiting count, not the open count, is your health metric. 100 tasks were served by 12 connections doing nothing but exchanging bytes.
Fix 2: Replace Library Defaults with Explicit Limits, Keepalive, and Timeouts
Fix 1 makes the pool effective. Fix 2 makes it deliberate. Library defaults are guesses made by people who never saw your workload.
httpx:
import httpx
client = httpx.AsyncClient(
limits=httpx.Limits(
max_connections=32,
max_keepalive_connections=32,
keepalive_expiry=30,
),
timeout=httpx.Timeout(
connect=5.0, # TCP+TLS handshake budget
read=15.0, # per-read budget on an open connection
write=5.0,
pool=10.0, # max time QUEUING for a connection -- the metric
),
)
The pool timeout deserves emphasis. Without it, an exhausted pool queues tasks forever and you get the silent-throughput-collapse signature from the first section. With pool=10.0, a task that can’t get a connection within 10 seconds raises httpx.PoolTimeout — a loud, countable, alertable failure instead of a quiet stall. I want the failure to be visible. Ten seconds of queueing is already a bug; waiting quietly is worse.
aiohttp:
import asyncio, aiohttp
connector = aiohttp.TCPConnector(
limit=32, # total pooled connections
limit_per_host=16, # per-origin cap -- politeness lives here
keepalive_timeout=30,
ttl_dns_cache=300,
)
timeout = aiohttp.ClientTimeout(total=30, connect=5)
session = aiohttp.ClientSession(connector=connector, timeout=timeout)
Now the defaults you’re overriding, because knowing what the library does when the pool runs dry is the whole game:
| Library | Default max connections | Default keepalive | When pool is exhausted |
|---|---|---|---|
urllib3 (used by requests) | No hard cap on pool; HTTPConnectionPool defaults to pool_connections=10 pools, pool_maxsize=10 each | Keepalive on, timeout not enforced per-conn | urlopen retries per Retry policy; if block=False (default), it silently creates extra connections past the cap |
| httpx | max_connections=100, max_keepalive_connections=20 | Keepalive enabled, expiry 5s | Queues the request until a connection frees or pool timeout fires (default: none — waits forever) |
| aiohttp | limit=100 total, limit_per_host=0 (unlimited) | Keepalive enabled | Queues with no default pool timeout; ClientTimeout(total=...) covers it only if set |
Read that last column twice. urllib3’s default doesn’t queue — it spawns extra connections, which is why a requests-based scraper often “works” until the target’s firewall notices 400 simultaneous connections from one IP. httpx and aiohttp queue instead, which is politer and exactly what produces the silent throughput cliff if you never set a pool timeout.
Size the Pool with Little’s Law, Then Validate Against the Throughput Plateau
Stop picking pool sizes by vibes. Little’s Law gives you the number directly:
pool size = target concurrency × average connection-hold time
Worked example. Say you need 50 pages/s from store.example.com, and after Fix 1 your average connection-hold time — the time a connection is actually borrowed, acquisition through response completion — is 0.6 s (300 ms exchange plus queuing jitter plus slow pages):
50 pages/s × 0.6 s hold = 30 requests in flight on average
So 30 connections covers the average load. But averages lie under bursty load, and scrapes are bursty. Split across 4 workers, that’s ~8 connections per worker for the average case, and I’d provision 2× headroom for retries, slow pages, and the burst when a sitemap batch lands: 16 connections per worker, 32 total. That’s not a coincidence with the config snippets above — that’s where those numbers came from.
Then validate empirically, because Little’s Law assumes your hold-time measurement is right and your target’s real concurrency tolerance is what you think it is. Run the mock at increasing pool sizes:
| Pool size | Requests/sec | p95 acquisition wait | p95 total latency |
|---|---|---|---|
| 8 | 22.1 | 4.9s | 5.3s |
| 16 | 39.8 | 1.1s | 1.5s |
| 32 | 62.4 | 12ms | 340ms |
| 64 | 62.1 | 9ms | 1.9s |
| 128 | 61.7 | 8ms | 3.8s |
Throughput plateaus at 32 — past that, extra connections buy you nothing because the mock’s semaphore caps concurrent responses at 20 anyway. But look at what happens past 64: throughput flat, and p95 total latency climbs from 340 ms to 3.8 s. Why? The mock’s semaphore queue grows, so requests sit inside the handler waiting for the origin semaphore — that wait happens while holding your connection. Oversizing the pool converts pool queueing into origin queueing, which is strictly worse: you’re now burning your own connections on the target’s internal queue.
This is the part where people push back: “just set the pool to 128 and forget about it.” No. Oversized pools make the failure mode quieter and more expensive. Size to the plateau, not past it.
Verify and Watch: Before/After Benchmarks and Acquisition-Wait Alerts
Prove the fix with the same workload that reproduced the bug. Same mock, same 100 tasks, 60-second run:
async def bench(client, duration=60):
latencies, waits, peak_waiting = [], [], 0
pool = client._transport._pool
stop = time.monotonic() + duration
async def one():
while time.monotonic() < stop:
m = await timed_fetch(
client, "http://store.example.com/listing/1"
)
latencies.append(m["total_ms"])
waits.append(m["acquisition_wait_ms"])
tasks = [asyncio.create_task(one()) for _ in range(100)]
sampler = asyncio.create_task(sample_waiting(pool, 1.0))
await asyncio.gather(*tasks)
peak_waiting = await sampler
latencies.sort()
waits.sort()
print(f"throughput: {len(latencies)/60:.1f} req/s")
print(f"p50/p95/p99: {latencies[len(latencies)//2]}ms / "
f"{latencies[int(len(latencies)*.95)]}ms / "
f"{latencies[int(len(latencies)*.99)]}ms")
print(f"peak waiting: {peak_waiting}")
Results, exhausted pool vs. fixed and correctly sized:
| Metric | Before | After |
|---|---|---|
| Throughput | 2.8 req/s | 62 req/s |
| p99 total latency | 16.3s | 410ms |
| Errors (timeouts) | 0 | 0 |
| Peak active connections | 10 (all pinned) | 12–32 (all exchanging) |
| Peak waiting-for-connection | 168 | 0 |
Twenty-two times the throughput, one-fortieth the tail latency, same error count (zero — which is precisely why this bug was invisible to error-based monitoring).
Last piece: alerts, so it doesn’t come back. Export these two rules and page on either:
- Page when median acquisition wait exceeds 50 ms for 5 minutes. Median, not mean — a healthy pool has the occasional queue blip, but a sustained median above zero means the pool is structurally undersized for current load.
- Page when the waiting-connection backlog stays above zero for 10 minutes. After Fix 1, waiting should be zero except during deliberate burst backfills. Any sustained backlog means someone added a new hold-time-inside-the-context code path.
Acquisition wait is the metric your standard APM won’t show you by default — request latency conflates queueing with wire time. Instrument it yourself, in the client wrapper, and ship it alongside your existing per-request metrics.
Wrap-Up
Connection pool exhaustion hides because it never fails loudly: every request eventually returns 200, throughput just quietly dies. The diagnostic chain is short — split request time into acquisition wait vs. exchange time, watch the pool’s waiting counter, and if p50 exchange time stays flat while p95 total explodes, you’ve found it.
The fixes, in order of impact:
- Shrink the connection-held region to the byte exchange. No parsing, sleeping, or backoff inside the stream context. This alone took the mock from 2.8 to 31 req/s.
- Configure the pool explicitly. httpx
Limits+ apooltimeout so exhaustion fails loudly instead of silently. aiohttpTCPConnectorwithlimit_per_host. - Size with Little’s Law, validate against the plateau. Target concurrency × hold time, then benchmark to find where throughput stops improving — and stop there, because past the plateau you’re paying to hold connections in the target’s own queue.
If you’re running this against a managed scraping API rather than your own fetch layer, the same law applies to how many concurrent jobs you submit — pool discipline is pool discipline regardless of who owns the sockets. For the broader picture on how retries inflate the hold times that feed Little’s Law, see How Retries Quietly Double Your Scraping Costs, and if your queueing shows up as batch-polling 429s instead of pool waits, Your Batch 429s Are Self-Inflicted covers that sibling failure mode.
Related Articles
Sudden 503s at Full Parallelism: Fix Concurrency Caps
Every scrape returns 503 the moment you hit full parallelism. Learn to tell a concurrency cap from a rate limit and fix it with one shared semaphore.
TutorialENOTFOUND Under Load: Fix Your Scraper's DNS Collapse
Bursts of ENOTFOUND and EAI_AGAIN errors hit your scraper only under load. Learn to diagnose resolver overload and fix it with caching and fan-out control.
TutorialYour Batch 429s Are Self-Inflicted: Fix the Polling Storm
Your batch jobs fail with 429s at scale, but the scrapes are fine. Learn to diagnose self-inflicted rate limits from status polling and fix them.