Fix concurrent payment request bug in Python HttpxHooks
Summary
Fixes a critical bug where the Python HttpxHooks class prevented concurrent payment requests from succeeding. Only the first request would succeed while all others would fail with 402 errors without attempting payment.
Resolves #398
Problem
The HttpxHooks class used a single shared _is_retry boolean flag across all concurrent requests:
class HttpxHooks:
def __init__(self, client: x402Client):
self.client = client
self._is_retry = False # ❌ Shared across ALL requests
Race condition:
- Request A hits 402 →
_is_retry = False→ sets_is_retry = True→ starts payment - Request B hits 402 →
_is_retry = True→ short-circuits, returns 402 immediately - Requests C, D, E → same as B, all fail with 402
Additional issues:
- Flag was never reset after successful payment (only in exception handlers)
- No per-request isolation
Solution
Replace the single boolean flag with a set that tracks each request individually:
class HttpxHooks:
def __init__(self, client: x402Client):
self.client = client
self._retrying_requests = set() # ✅ Track each request individually
How it works:
- Use
id(request)as a unique identifier for each request - Add request ID to set when starting retry
- Remove request ID from set after completion (success or error)
- Each concurrent request processes payment independently
Changes
-
python/x402/src/x402/clients/httpx.py:- Replaced
_is_retryboolean with_retrying_requestsset - Track requests using
id(response.request) - Clean up tracking in all code paths (success + error handlers)
- Replaced
-
python/x402/tests/clients/test_httpx.py:- Updated tests to use
_retrying_requestsset instead of_is_retryflag - Tests now verify requests are removed from set after completion
- Updated tests to use
Impact
This fix enables:
- ✅ AI agents making concurrent batch requests to paid endpoints
- ✅ Multiple simultaneous API calls from the same client
- ✅ High-throughput applications with parallel paid endpoint access
- ✅ Load testing of paid endpoints
Testing
All existing tests updated and passing. The fix maintains the same behavior for single requests while enabling proper concurrent request handling.
🟡 Heimdall Review Status
| Requirement | Status | More Info | ||||||||||||||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| Reviews |
🟡
0/1
|
Denominator calculation
|
@madisoncarter1234 is attempting to deploy a commit to the Coinbase Team on Vercel.
A member of the Team first needs to authorize it.