HTTPX2: Fix Timeouts and Connection Reuse in Python
Two small changes to your Requests code: set a timeout, reuse one Client.
Reviewed by Abhijith N M · 24 October 2026 · Editorial standards
Here's a pattern you've probably written: `requests.get(url)` in a loop, once per item. It works, and it hides two problems. The first is that with no timeout argument, a stalled server can leave your script waiting far longer than you intended. The second is that each call may open a fresh connection, so a batch of calls pays the connection setup cost over and over. HTTPX2 is a fork of HTTPX maintained by Pydantic, and it keeps the Requests-style API. So the migration is mostly mechanical. Create one `httpx2.Client()` and use it for every request in the batch. The client pools connections: it keeps them open and reuses them instead of opening a new one per call. HTTPX2 also ships with default timeouts, so a request that hangs doesn't hang forever by default. If you need many calls at once, `AsyncClient` runs them concurrently under asyncio, Python's standard library for cooperative concurrency. That's the honest tradeoff: async code is harder to read, harder to debug, and infects the call stack. Use it when concurrency is the actual bottleneck, not because it sounds faster. HTTP/2 is also available, and per the tutorial it costs one extra dependency and one argument. Granular timeouts and a clear exception hierarchy let you tell a timeout apart from a connection error instead of catching a generic exception. Streaming lets you process a large response without loading it fully into memory. A concrete example: fetching 50 URLs. The Requests version without a timeout and without a session is the version that bites you in production. The HTTPX2 version is a `with httpx2.Client() as client:` block and a loop inside it. Same shape, fewer surprises.
HTTPX2: Fix Timeouts and Connection Reuse in Python — Visual Breakdown
Requests, beginner pattern
- ✓New call per URL in the loop
- ✓No timeout argument: a stalled server stalls you
- ✓No connection reuse across calls
- ✓Sync only
HTTPX2 with one Client
- ✓One Client reused for the whole batch
- ✓Default timeouts unless you override them
- ✓Connections pooled and reused
- ✓AsyncClient available when you need concurrency
import httpx2
urls = [
"https://example.com/a",
"https://example.com/b",
"https://example.com/c",
]
# One client, reused: connections are pooled.
# Default timeouts apply; pass timeout= to override.
with httpx2.Client(timeout=5.0) as client:
for url in urls:
try:
response = client.get(url)
print(url, response.status_code)
except httpx2.TimeoutException:
print(url, "timed out")Quick Concept Check
Test your understanding in 15 seconds
What is the main benefit of reusing a single HTTPX2 Client across many requests?
Related Concepts
Written and edited by the nexGenCoders team. Spotted a mistake? Tell us and we will fix it.