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?
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.
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.
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
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With