HttpWebRequest is extremely slow!

C#PerformanceHttpHttpwebrequest

C# Problem Overview


I am using an open source library to connect to my webserver. I was concerned that the webserver was going extremely slow and then I tried doing a simple test in Ruby and I got these results

> Ruby program: 2.11seconds for 10 HTTP > GETs > > Ruby program: 18.13seconds for 100 HTTP > GETs > > C# library: 20.81seconds for 10 HTTP > GETs > > C# library: 36847.46seconds for 100 HTTP > GETs

I have profiled and found the problem to be this function:

private HttpWebResponse GetRawResponse(HttpWebRequest request) {
  HttpWebResponse raw = null;
  try {
    raw = (HttpWebResponse)request.GetResponse(); //This line!
  }
  catch (WebException ex) {
    if (ex.Response is HttpWebResponse) {
      raw = ex.Response as HttpWebResponse;
    }
  }
  return raw;
}

The marked line is takes over 1 second to complete by itself while the ruby program making 1 request takes .3 seconds. I am also doing all of these tests on 127.0.0.1, so network bandwidth is not an issue.

What could be causing this huge slow down?

UPDATE

Check out the changed benchmark results. I actually tested with 10 GETs and not 100, I updated the results.

C# Solutions


Solution 1 - C#

What I have found to be the main culprit with slow web requests is the proxy property. If you set this property to null before you call the GetResponse method the query will skip the proxy autodetect step:

request.Proxy = null;
using (var response = (HttpWebResponse)request.GetResponse())
{
}

The proxy autodetect was taking up to 7 seconds to query before returning the response. It is a little annoying that this property is set on by default for the HttpWebRequest object.

Solution 2 - C#

It may have to do with the fact that you are opening several connections at once. By default the Maximum amount of open HTTP connections is set to two. Try adding this to your .config file and see if it helps:

<system.net>
  .......
  <connectionManagement>
    <add address="*" maxconnection="20"/>
  </connectionManagement>
</system.net>

Solution 3 - C#

I was having a similar issue with a VB.Net MVC project.
Locally on my pc (Windows 7) it was taking under 1 second to hit the page requests, but on the server (Windows Server 2008 R2) it was taking 20+ seconds for each page request.

I tried a combination of setting the proxy to null

  System.Net.WebRequest.DefaultWebProxy = Nothing
  request.Proxy = System.Net.WebRequest.DefaultWebProxy

And changing the config file by adding

 <system.net>
   .......
   <connectionManagement>
     <add address="*" maxconnection="20"/>
   </connectionManagement>
 </system.net>

This still did not reduce the slow page request times on the server. In the end the solution was to uncheck the “Automatically detect settings” option in the IE options on the server itself. (Under Tools -> Internet Options select the Connections tab. Press the LAN Settings button)

Immediately after I unchecked this browser option on the server all the page request times dropped from 20+ seconds to under 1 second.

Solution 4 - C#

I started observing a slow down similar to the OP in this area which got a little better when increasing the MaxConnections.

ServicePointManager.DefaultConnectionLimit = 4;

But after building this number of WebRequests the delays came back.

The problem, in my case, was that I was calling a POST and not bothered about the response so wasn't picking up or doing anything with it. Unfortunately this left the WebRequest floating around until they timed out.

The fix was to pick up the Response and just close it.

WebRequest webRequest = WebRequest.Create(sURL);
webRequest.Method = "POST";
webRequest.ContentLength = byteDataGZ.Length;
webRequest.Proxy = null;
using (var requestStream = webRequest.GetRequestStream())
{
    requestStream.WriteTimeout = 500;
    requestStream.Write(byteDataGZ, 0, byteDataGZ.Length);
    requestStream.Close();
}
// Get the response so that we don't leave this request hanging around
WebResponse response = webRequest.GetResponse();
response.Close();

Solution 5 - C#

Use a computer other than localhost, then use WireShark to see what's really going over the wire.

Like others have said, it can be a number of things. Looking at things on the TCP level should give a clear picture.

Solution 6 - C#

I don't know how exactly I've reach to this workaround, I didn't have time to do some research yet, so it's up to you guys. There's a parameter and I've used it like this (at the constructor of my class, before instantiating the HTTPWebRequest object):

System.Net.ServicePointManager.Expect100Continue = false;

I don't know why exactly but now my calls look quite faster.

Solution 7 - C#

I know this is some old thread, but I have lost whole day with slow HttpWebRequest, tried every provided solution with no luck. Every request for any address was more than one minute.

Eventually, problem was with my Antivirus Firewall (Eset). I'm using firewall with interactive mode, but Eset was somehow turned off completely. That caused request to last forever. After turning ON Eset, and executing request, prompt firewall message is shown, and after confirmation, request executing for less than one second.

Solution 8 - C#

For me, using HttpWebRequest to call an API locally averaged 40ms, and to call an API on a server averaged 270ms. But calling them via Postman averaged 40ms on both environments. None of the solutions in this thread made any difference for me.

Then I found this article which mentioned the Nagle algorithm:

> The Nagle algorithm increases network efficiency by decreasing the number of packets sent across the network. It accomplishes this by instituting a delay on the client of up to 200 milliseconds when small amounts of data are written to the network. The delay is a wait period for additional data that might be written. New data is added to the same packet.

Setting ServicePoint.UseNagleAlgorithm to false was the magic I needed, it made a huge difference and the performance on the server is now almost identical to local.

var webRequest = (HttpWebRequest)WebRequest.Create(url);
webRequest.Method = "POST";
webRequest.ServicePoint.Expect100Continue = false;
webRequest.ServicePoint.UseNagleAlgorithm = false; // <<<this is the important bit

Note that this worked for me with small amounts of data, however if your request involves large data then it might be worth making this flag conditional depending on the size of the request/expected size of the response.

Solution 9 - C#

I tried all the solutions described here with no luck, the call took about 5 minutes.

What was the issue: I needed the same session and obviously the same cookies (request made on the same server), so I recreated the cookies from Request.Cookies into WebRequest.CookieContainer. The response time was about 5 minutes.

My solution: Commented out the cookie-related code and bam! Call took less then one second.

Solution 10 - C#

This worked for me:

<configuration>
  <system.net>
    <defaultProxy enabled="false"/>
  </system.net>
</configuration>

Credit: Slow HTTPWebRequest the first time the program starts

Solution 11 - C#

For me, the problem was that I had installed LogMeIn Hamachi--ironically to remotely debug the same program that then started exhibiting this extreme slowness.

FYI, disabling the Hamachi network adapter was not enough because it seems that its Windows service re-enables the adapter.

Also, re-connecting to my Hamachi network did not solve the problem. Only disabling the adapter (by way of disabling the LogMeIn Hamachi Windows service) or, presumably, uninstalling Hamachi, fixed the problem for me.

Is it possible to ask HttpWebRequest to go out through a specific network adapter?

Solution 12 - C#

In my case add AspxAutoDetectCookieSupport=1 to the code and the problem was solved

Uri target = new Uri("http://payroll");

string responseContent;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(target);

request.CookieContainer = new CookieContainer();         
request.CookieContainer.Add(new Cookie("AspxAutoDetectCookieSupport", "1") { Domain = target.Host });

using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
    using (Stream responseStream = response.GetResponseStream())
    {
        using (StreamReader sr = new StreamReader(responseStream))
            responseContent = sr.ReadToEnd();
    }
}

Solution 13 - C#

We encountered a similar issue at work where we had two REST APIs communicating locally with each other. In our case all HttpWebRequest took more than 2 seconds even though the request url was http://localhost:5000/whatever which was way to slow.

However upon investigating this issue with Wireshark we found this:

wireshark

It turned out the framework was trying to establish an IPv6 connection to localhost first, however as our services were listening on 0.0.0.0 (IPv4) the connection attempt failed and after 500 ms timeout it retried until after 4 failed attempts (4 * 500 ms = 2 seconds) it eventually gave up and used IPv4 as a fallback (which obviously succeeded almost immediately).

The solution for us was to change the request URI to http://127.0.0.1/5000/whatever (or to also listen on IPv6 which we deemed unnecessary for our local callbacks).

Solution 14 - C#

I was experiencing a 15 second or so delay upon creating a session to an api via httpwebrequest. The delay was around waiting for the getrequeststream() . After scrounging for answers, I found this article and the solution was just changing a local windows policy regarding ssl:

https://www.generacodice.com/en/articolo/1296839/httpwebrequest-15-second-delay-performance-issue

Solution 15 - C#

We had the same problem on web app. We waited on response 5 seconds. When we change user on applicationPool on IIS to networkService, the response began to arrive less than 1 second

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionEarlzView Question on Stackoverflow
Solution 1 - C#James RolandView Answer on Stackoverflow
Solution 2 - C#ManuView Answer on Stackoverflow
Solution 3 - C#jamiebView Answer on Stackoverflow
Solution 4 - C#tonycouplandView Answer on Stackoverflow
Solution 5 - C#kervinView Answer on Stackoverflow
Solution 6 - C#user753746View Answer on Stackoverflow
Solution 7 - C#Šemsudin TafilovićView Answer on Stackoverflow
Solution 8 - C#demoncodemonkeyView Answer on Stackoverflow
Solution 9 - C#mihai_omegaView Answer on Stackoverflow
Solution 10 - C#mmmmmmView Answer on Stackoverflow
Solution 11 - C#Craig SilverView Answer on Stackoverflow
Solution 12 - C#ashkufarazView Answer on Stackoverflow
Solution 13 - C#Frederik HoeftView Answer on Stackoverflow
Solution 14 - C#user2814916View Answer on Stackoverflow
Solution 15 - C#user2693593View Answer on Stackoverflow