.NET HttpClient should be shared

While toying around with Azure Functions for some app idea, I came across some documentation on best practices for using it.

The article continues further into detail on Patterns and Practices HTTP Performance Optimizations where I discovered something about HttpClient I would have never guessed:

[HttpClient is] intended to be instantiated once and reused throughout the lifetime of an application. However, it’s a common misunderstanding that these classes should be acquired only as necessary and released quickly

new HttpClient object is created for each user request. Under heavy load, the web server may exhaust the number of available sockets, resulting in SocketException errors.

The HttpClient class is designed to be shared rather than pooled

Well whaddayaknow, until know I have always designed my applications to keep the HttpClient as short-lived as possible, always wrapping it in a using block to ensure proper disposal.

Turns out this is an anti-pattern, they actually advice you to create a static readonly HttpClient, which you reuse in your app.

Going to apply some improvements right now!

Theme music for this blog post

.NET HttpClient should be shared

2 thoughts on “.NET HttpClient should be shared

  1. The Programmator says:

    Curious how you’d implement this in a high concurrency app, though, where the settings on the httpclient instances my vary by each call. BaseUrl’s, credentials, headers.. Could this lead to unexpected headers being present? According to MSDN, only endpoint operation calls are thread safe. (https://msdn.microsoft.com/en-us/library/system.net.http.httpclient(v=vs.110).aspx#Anchor_5) , but setting properties? (note the link also mentions the correct use of HttpClients)

    Like

  2. Came across this issue today while applying the improvements! 🙂

    You can use SendAsync instead, which accepts an HttpRequestMessage that allows you specify the headers for that specific call being made (https://msdn.microsoft.com/en-us/library/hh138176(v=vs.110)).

    If for some reason you still need/prefer some configuration on the HttpClient, based on what I understand from what I have just learned, having multiple separate static HttpClients for the specific use cases is to be preferred over recreating a new one at each call (e.g. a static readonly BlueCustomHttpClient, a static readonly RedAuthenticatedHttpClient, …)

    Like

Leave a comment