Lesson 8 of 14 · 18m
Bulk lookups: ThreadPoolExecutor, bounded workers, and rate limits
Parallelize IO-bound enrichment correctly — the GIL releases on sockets, sessions aren't thread-safe, and 429s are your problem.
Three thousand IPs from last night's auth.log need enrichment — two API calls each, roughly a second per request. Sequentially that's an hour forty of wall time for what is, in CPU terms, a nap. The instinct "Python can't parallelize, GIL" is wrong for exactly this workload: the GIL is released whenever a thread blocks on socket IO, and requests is blocking IO. Thirty lines of concurrent.futures turns the job into minutes.
The right mechanism for IO-bound work
from concurrent.futures import ThreadPoolExecutor, as_completed
import requests
def enrich(ip, session):
r = session.get(f"https://api.example.com/ip/{ip}",
timeout=(5, 15))
r.raise_for_status()
return ip, r.json()
ips = [line.split()[0] for line in open("auth-ips.txt")] # however you extracted them
results, failures = {}, {}
session = requests.Session() # shared for now — see the caveat below
with ThreadPoolExecutor(max_workers=16) as pool:
futures = {pool.submit(enrich, ip, session): ip for ip in ips}
for fut in as_completed(futures):
ip = futures[fut]
try:
_, data = fut.result()
results[ip] = data
except Exception as e:
failures[ip] = str(e)Three decisions carry the load. max_workers=16 bounds in-flight work — one thread per IP means 3,000 threads fighting over file descriptors and tripping every rate limit on the way. 8–32 is the working range for API-bound jobs; tune against the remote's rate limit, not your core count. as_completed streams results as they finish instead of blocking on the first future's result() — and it loses ordering, so keep the futures → input map (or return the key in the result). The try around fut.result() is how failures surface: a worker's exception doesn't raise in the worker, it re-raises when you call result() — skip the try and one 500 from the API kills the whole batch at the end.
Sessions are not thread-safe; timeouts still apply per call
requests.Session is not documented as thread-safe — connection pools mutate under concurrent use. The cheap fix is one session per thread:
import threading
_local = threading.local()
def get_session():
if not hasattr(_local, "session"):
_local.session = requests.Session()
_local.session.headers["Authorization"] = f"Bearer {KEY}"
return _local.sessionTimeouts are per-request, unchanged: the (5, 15) tuple inside enrich still bounds every call. The pool itself doesn't enforce "the whole batch within N minutes" — that's fut.result(timeout=...) or a bounded retry count upstream. If you keep one shared session anyway, size its connection pool to the worker count — session.mount("https://", requests.adapters.HTTPAdapter(pool_maxsize=16)) — because the default pool_maxsize=10 leaves workers eleven through sixteen queued for a connection slot, a serialization point that never shows in the logs.
Rate limits are your problem, not the API's
Threads don't exempt you from 429s. If the feed allows 10 req/s, max_workers=16 with sub-second calls will get you throttled. A per-worker time.sleep bounds the aggregate only loosely — worker count times per-thread rate is your ceiling, so time.sleep(1.0) at max_workers=10 holds you near ~10 req/s — and a token bucket is the honest version when the feed publishes a hard number. For most feeds, max_workers below the limit plus the mounted Retry from the requests lesson (status_forcelist=(429, ...)) absorbing the overflow is enough plumbing. More workers than the limit sustains doesn't speed anything, it generates retries.
Try this
Take the domain list from the subprocess lesson and bulk-resolve it via a public DNS-over-HTTPS endpoint (https://cloudflare-dns.com/dns-query?name=...&type=A, Accept: application/dns-json) with ThreadPoolExecutor(max_workers=8). Log per-IP failures without aborting the run, then time it against the sequential version.
Field notes
executor.mappreserves input order and reads cleaner when failures can be handled per-item — same underlying pool, less bookkeeping.as_completedwins when you want results in finish order.executor.shutdown(cancel_futures=True)(Python 3.9+) lets aKeyboardInterruptcancel queued work instead of waiting on 2,900 pending futures.- This pattern breaks for CPU-bound work — parsing, hashing, compression. The GIL is held there;
ProcessPoolExecutoris the tool for that, with real process-startup cost, which is why nobody reaches for it first. ThreadPoolExecutor's default grew in 3.8 tomin(32, os.cpu_count() + 4)— already too many for a rate-limited API. Explicit beats default.- Asyncio is the "correct" answer at scale — and it rewrites every call site async. For a batch script, threads are the honest 20-line answer; don't apologize for them.
Was this lesson helpful?
Keep reading
Related articles from the SudoSecurity blog.
RSA Is Simple. Deploying RSA Correctly Almost Never Is.
The capstone to our RSA series. The math checks out. Shipping it as written gets you breached. This is the nineteen-year-old attack that proves it, and what belongs in production instead.
Implementing RSA, AES-GCM, and a TLS 1.3 Handshake from Scratch in Python
Your HTTPS Is Toast (But Google Has a Plan): Merkle Tree Certificates and the Post-Quantum Web
RSA-2048 can be broken with fewer than 100,000 qubits. What that means for TLS, certificate infrastructure, and the post-quantum transition already underway.
RSA Signatures: The Version in Most Tutorials Is Forgeable
Signing is encryption with the keys swapped, and that symmetry is exactly what makes the naive implementation breakable. Here are two forgeries executed against textbook RSA signatures, and what PSS does that hashing alone cannot.