Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How many HttpClients should I create?

Originally my code created a new HttpClient in a using statement on every request. Then I read several articles about reusing HttpClient to increase performance.

Here is an excerpt from one such article:

I do not recommend creating a HttpClient inside a Using block to make a single request. When HttpClient is disposed it causes the underlying connection to be closed also. This means the next request has to re-open that connection. You should try and re-use your HttpClient instances.

http://www.bizcoder.com/httpclient-it-lives-and-it-is-glorious

It seems to me that leaving a connection open is only going to be useful if multiple requests in a row go to the same places - such as www.api1.com.

My question is, how may HttpClients should I create?

My website talks to about ten different services on the back end.

Should I create a single HttpClient for all of them to consume, or should I create a separate HttpClient per domain that I use on the back end?

Example: If I talk to www.api1.com and www.api2.com, should I create 2 distinct HttpClients, or only a single HttpClient?

like image 393
JALLRED Avatar asked Jun 04 '14 17:06

JALLRED


1 Answers

Indeed, Disposing of HttpClient will not forcibly close the underlying TCP/IP connection from the connection pool. Your best performance scenario is what you have suggested:

  • Keep an instance of HttpClient alive for each back-end service you need to connect to or the lifetime of your application.

  • Depending on the details you have about the back-end service, you may also want to have a client for each distinct API on that back-end service as well. (API's in the same domain could be routing all over the place.)

like image 120
tezromania Avatar answered Sep 21 '22 13:09

tezromania