Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HttpWebRequest Port Exhaustion

We are using a Windows Service to make very frequent HTTP calls to an internal REST service (20-40 calls per second), but notice a long delay in getting responses after the service runs for several minutes.

Looking at netstat, there are quite a few ports with "TIME_WAIT" status, and it seems we may be running out of ports.

How can we ensure that ports are reused?

like image 361
user2966445 Avatar asked Nov 10 '15 14:11

user2966445


People also ask

How do you stop port exhaustion?

Reboot of the server will resolve the issue temporarily, but you would see all the symptoms come back after a period of time. If you suspect that the machine is in a state of port exhaustion: Try making an outbound connection.

What is socket exhaustion?

A TCP socket is a specific TCP port on a specific node. Port exhaustion occurs when a node runs out of available ports. When an application stops using a specific port, the port enters a "time-wait state" before it becomes available for use by another application.


2 Answers

There is a limit in the number of simultaneous outgoing HTTP connections. You can control this by using the System.Net.ServicePointManager.DefaultConnectionLimit static property before creating the HttpWebRequest objects

It might be worthwhile setting this to a higher value than the default which I believe is 2.

If this does not help then you can also increase the default ThreadPool size to allow you to create more requests quicker. The thread pool only ramps up its number of threads gradually - a new thread per every half second, IIRC

like image 77
James Moore Avatar answered Oct 19 '22 22:10

James Moore


How can we ensure that ports are reused? Not set the connection limit to a value that almost guarantees that they won't be.

It looks like someone has monkeyed with the ServicePointManager at some point. I'd limit the ServicePoint for this origin: to encourage http pipelining and connection reuse:

ServicePointManager.FindServicePoint(Uri).ConnectionLimit = someSensibleValue;
like image 44
spender Avatar answered Oct 19 '22 22:10

spender