Blog speaking .Net C# Javascript, Wordpress

Slow HTTP requests in .NET

When profiling a web application I have noticed constant delays of about 200ms on some HTTP calls it was making to an external API. Both the web application and the API were on the same network segment and thus network latency was out of the question. Besides the target API has previously been subject to jMeter load tests and proven to handle 1500req/s. What was even more peculiar in this situation was that only the POST requests were exhibiting this delay. GET requests were pretty fast as expected.

It turned out that those delays were caused by the Nagle’s algorithm that is enabled by default in the HttpWebRequest class. 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.

Turning it off for the particular endpoint I was POSTing to removed the 200ms delay:

System.Net.ServicePointManager.FindServicePoint(uri).UseNagleAlgorithm = false;

Disabling the Nagle algorithm for all requests might not be best practice either. I would recommend you experiment and perform extensive profiling before disabling it.

Leave a comment

Your email address will not be published. Required fields are marked *