6

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?

Daniel Mann
  • 57,011
  • 13
  • 100
  • 120
JALLRED
  • 855
  • 1
  • 11
  • 23

1 Answers1

5

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.)

wnbates
  • 743
  • 7
  • 16
tezromania
  • 797
  • 1
  • 5
  • 18
  • How about having multiple endpoints on a single domain, such as www.api1.com/foo and www.api1.com/bar. Is a single HttpClient sufficient for those or would 2 be optimal? – JALLRED Jun 04 '14 at 17:51
  • 1
    I think it depends on how the back-end service is implemented. It seems like in most situations, you cannot guarantee that an API in the same domain will necessarily route to the same place. It could also be routing across a pool of servers or something like that. I think your best bet is HttpClient per each API. – tezromania Jun 04 '14 at 17:56