Is httpx.Client thread safe? #1633
-
I'm writing a multi-threaded application that makes HTTP requests. The way I have my code structured, I'd like to share a single I could probably structure my code to use a client per worker (or maybe I'd need to do one per connection if I can't work out how to add setup code to Just for completeness, I'll note that I can't use async, because one of my classes needs a sync interface. |
Beta Was this translation helpful? Give feedback.
Replies: 5 comments 8 replies
-
Yes. HTTPX is intended to be thread-safe, and yes, a single client-instance across all threads will do better in terms of connection pooling, than using an instance-per-thread. We might want to figure a good place in the docs to write about this. (?) I've not looked through requests or urllib3 to see where they choose to discuss this in their own docs. Their docs choices here might be a useful pointer for us. (And thank you for the clearly framed question, much appreciated 💚) |
Beta Was this translation helpful? Give feedback.
-
Hi, is the same true with the async interface? Can I use the same (async) client in concurrent tasks? |
Beta Was this translation helpful? Give feedback.
-
For what it's worth, this is currently the top hit on Google for "httpx thread safety", which arguably is worth as much as finding the right place for it in the docs! |
Beta Was this translation helpful? Give feedback.
-
I doubt that there are race conditions in Client code Think about this case
In this case, thread A tries to send a request on an already-closed client. Client.close method Lines 1251 to 1261 in 87f39f1 Client.send method Lines 888 to 892 in 87f39f1 |
Beta Was this translation helpful? Give feedback.
-
By saying httpx is Closing the client in one thread and making requests in another would probably break the client state, as you mentioned. In most cases, you simply create a client instance locally or globally, make concurrent requests, and then close it. |
Beta Was this translation helpful? Give feedback.
Yes. HTTPX is intended to be thread-safe, and yes, a single client-instance across all threads will do better in terms of connection pooling, than using an instance-per-thread.
We might want to figure a good place in the docs to write about this. (?)
I've not looked through requests or urllib3 to see where they choose to discuss this in their own docs. Their docs choices here might be a useful pointer for us.
(And thank you for the clearly framed question, much appreciated 💚)