Fix SSL context memory issue by breaking reference cycles (#3734) #3746
+111
−4
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Summary
This PR fixes issue #3734 by breaking reference cycles in
BoundSyncStreamandBoundAsyncStreamthat prevent timely garbage collection of SSL contexts.Problem
When using
httpx.Clientorhttpx.AsyncClient, thecreate_ssl_context()function is called for each Transport instantiation. Each SSL context can consume 10s or 100s of MB of memory.The issue is exacerbated by reference cycles between
Responseobjects and their associatedBoundSyncStream/BoundAsyncStreaminstances:This cycle prevents the garbage collector from immediately reclaiming response objects and their associated resources (including SSL contexts), leading to excessive memory usage.
Solution
Use
weakref.refto break the reference cycle. The stream now holds a weak reference to the response instead of a strong reference:When closing the stream, we safely dereference and only set
elapsedif the response is still alive:Changes
httpx/_client.py: ModifiedBoundSyncStreamandBoundAsyncStreamto useweakref.reftests/test_bound_stream.py: Added 9 new tests covering:Testing
ruff format,ruff check,mypy)test_bound_stream.py)Risk Assessment
Low risk because:
elapsedif the response was already garbage collected (edge case)Fixes #3734
Checklist