I have one request for a specific domain that take a really long time to complete : 22 seconds in average. The request itself does not return a lot of data.
var httpClient = new HttpClient(); //instantiated at app start and reused
var request = new HttpRequestMessage(HttpMethod.Get, "http://www.somedomain.com");
var result = await httpClient.SendAsync(request); //take a really long time
After some debugging, it seems related to DNS. If I run the exact same request but replace domain name by IP, it's fast (< 200 ms).
It's also fast if I run the request a second time using same HttpClient instance. However, if I run that second request after more than one minute it's slow again (probably because connections are closed automatically after 1 minute).
Is there a way to improve this ? (eg: to make sure resolved DNS entries would stay in cache for a long period). Also why is DNS so slow for that domain when using HttpClient ? If I try to access that domain using Chrome it's blazing fast (even after flushing DNS and clearing cache). A DNS lookup of that domain using an online service is also very fast. Reported TTL is 60 minutes.
EDIT: I have tried to increase ServicePointManager.DnsRefreshTimeout (which is set by default to 2 minutes). But it does not help.
Calling Dns.GetHostEntry("somedomain.com") is instantaneous and return the right IP. I don't know why request with HttpClient are so slow.
I found out what is wrong: the domain that is slow has an IPV6 address in the DNS records. This can be confirmed by calling this function:
First it tries to connect using IPV6. Eventually, a timeout occurs. Then it tries IPV4 (and it works). This explains why it is so slow. The solution I have found so far is to force IPV4 by resolving the domain name myself:
Maybe there is a better way. I can't use
SocketsHttpHandlersince i'm stuck with.NET Framework 4.5