runtime icon indicating copy to clipboard operation
runtime copied to clipboard

HttpClient throwing System.Net.Sockets.SocketException after 21 seconds

Open emilssonn opened this issue 7 years ago • 32 comments

We are getting random 21 second timeouts when making http calls using HttpClient. As far as I know this is an low-level TCP timeout. The exception message is the same as in issue dotnet/runtime#27232. What causes these errors?

The real world use case is that we have an Azure Webapp running the latest version of .Net Core 2.1. When this webapp receives a request it will do a request (using httpclient) to another API that is accessed through Azure API Management. When our webapp gets maybe 30+ requests at the same time (causing 30+ requests being made to APIM) we might get this timeout on some of the request made to APIM, after an retry it works.

I am trying to figure out why this timeout is happening. Can this exception indicate any errors in my code, setup or webapp performance? Or is the issue in API Management?

emilssonn avatar Dec 14 '18 12:12 emilssonn

Are you using HttpClientFactory?

MarcoRossignoli avatar Dec 14 '18 12:12 MarcoRossignoli

Yes, I am using a typed client with polly for retries.

emilssonn avatar Dec 14 '18 13:12 emilssonn

Maybe silly question...are you using .GetResult() in some code path?

MarcoRossignoli avatar Dec 14 '18 13:12 MarcoRossignoli

Simplified I use the following. The httpclient is injected using the pattern on https://docs.microsoft.com/sv-se/aspnet/core/fundamentals/http-requests?view=aspnetcore-2.1

var request = new HttpRequestMessage
{
    Method = method,
    RequestUri = new Uri(apiPath, UriKind.Relative),
    Content = content
};

using (var response = await _httpClient.SendAsync(request))
{
   return await response.Content.ReadAsAsync<T>();
}

emilssonn avatar Dec 14 '18 14:12 emilssonn

/cc @davidsh

MarcoRossignoli avatar Dec 14 '18 14:12 MarcoRossignoli

21 seconds is the built-in default for TCP connection timeout on Windows. It is 21 seconds because Windows TCP stack allows for 7 seconds per leg of the 3-leg TCP SYNC-ACK connection setup.

There is no current override to this timeout which is a built-in timeout to the Windows TCP layer.

This issue is basically a duplicate of dotnet/runtime#27232

davidsh avatar Dec 14 '18 16:12 davidsh

cc: @karelz

davidsh avatar Dec 14 '18 16:12 davidsh

@emilssonn I am curious how often it happens and if you are able to reproduce it in some debuggable/traceable environment outside of Azure WebApps.

karelz avatar Dec 14 '18 17:12 karelz

I have not been able to reproduce it "manually" yet. I apologize if this issue is a duplicate. My main question is if this exception always indicate an error in the target API (API Management in this case) or if this error/timeout can occur in some way where the cause is the caller and not the target. I have an ongoing ticket with Azure support and I am basically trying to rule out as many things as possible since we have not been able to find the reason yet.

It happens randomly when the load spikes from 0 rps to "high" rps. For example: 2018-12-08T18:12:42: 78 request to target, OK 2018-12-08T18:12:43: 24 request to target, OK 2018-12-08T18:12:43: 27 request to target, 21 sec timeout

emilssonn avatar Dec 14 '18 18:12 emilssonn

Unless there is some bug somewhere, it is indication the endpoints you call are not responding as they should on TCP level, triggering this timeout.

karelz avatar Dec 17 '18 21:12 karelz

I have been troubleshooting this for quite some time. After discussion with the Azure support, one possible cause is resource exhaustion on the Azure Webapp. The main reason I created this issue was that almost all references to hitting the connection limit in Azure Webapps says it results in a exception, “An attempt was made to access a socket in a way forbidden by its access permissions aaa.bbb.ccc.ddd.”.

And the reason for hitting(?) the connection limit is that the Webapp will under heavy load do alot of outgoing requests at the same time, limiting connection reuse (even when using HttpClient correctly).

emilssonn avatar Feb 28 '19 18:02 emilssonn

under heavy load do alot of outgoing requests at the same time

You could try setting the MaxConnectionsPerServer property on the handler, in order to throttle how many connections you actually open.

stephentoub avatar Feb 28 '19 20:02 stephentoub

@stephentoub, is that only per HttpClient object (I have multiple services using typed HttpClients that connects to the same domain)? What happens if the MaxConnectionsPerServer is hit?

At the moment I use a shared Polly bulkhead policy to throttle outgoing requests.

emilssonn avatar Mar 01 '19 11:03 emilssonn

is that only per HttpClient object

It's per handler, so if you were to use the same handler instance with multiple HttpClient instances, all of those clients would share in the same max. The parameterless HttpClient ctor creates its own handler, in which case it ends up having the same effect as being per client.

stephentoub avatar Mar 01 '19 12:03 stephentoub

@emilssonn did you ever get a resolution to this issue? we are using .netcore3.1 with a named HttpClientFactory and are having the same issues. The azure app service diagnostics show no problem with SNAT port exhaustion so we are at a loss as to what the problem could be.

paulandrewc avatar Jun 26 '20 19:06 paulandrewc

We are also seeing this a lot over the past week, .NET Core 2.2 and 3.1 both using HttpClientFactory and hosted in Azure App Services (Windows).

krispenner avatar Jun 26 '20 19:06 krispenner

@krispenner I am interested that you said you have been seeing this over the last week. Has this just started happening for you without changing the code? That would imply something environmental potentially. I know for instance I can't replicate locally.

paulandrewc avatar Jun 27 '20 20:06 paulandrewc

@paulandrewc, our problem was with SNAT port exhaustion. The "resolution" we had to implement was to limit the number of concurrent outbound requests to the same ip/domain.

services.AddHttpClient("name").ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler
{
    MaxConnectionsPerServer = 110
}).SetHandlerLifetime(Timeout.InfiniteTimeSpan)

This will limit the number of concurrent outbound requests to 110. If you have multiple http clients targeting the same ip/domain, they need to use the same httphandler.

https://4lowtherabbit.github.io/blogs/2019/10/SNAT/

emilssonn avatar Jun 29 '20 06:06 emilssonn

UPDATE

The issue is not related to Azure's outbound NAT for App Services, see my comment on October 23, 2020 below for the actual reason and solution for our specific issue.

ORIGINAL COMMENT

What we have found or believe at this time, is that it's an issue with Azure's outbound NAT for App Services. The outbound port is being re-used too quickly across different App Services and is causing the destination to think it's a continuation of a previously established connection.

Example

  1. App Service A connects to Destination D on port 443, Azure uses port 24064 as the source port.
  2. Destination D sees this as TCP connection from source 52.1.2.3:24064.
  3. App Service A finishes its request.
  4. 54 seconds later....
  5. App Service B connects to Destination D on port 443, Azure uses port 24064 as the source port.
  6. Destination D sees this as TCP connection from source 52.1.2.3:24064.
  7. However, because there hasn't been at least four minutes or so of inactivity on the stream, (TCP WAIT TIMEOUT) Destination D thinks this new connection is actually a continuation of the previous connection and gets confused with the SYN packets, it returns ACK instead of SYN/ACK. This then causes multiple SYN attempts at 3 and 6 seconds later and eventually the connection fully times out at 21 seconds. Windows WinSock then tries a new connection and it succeeds.

The only solution I can think of currently is to move all our App Services onto distinct App Service Plans that have different outbound IP address ranges as this would ensure that Destination D always sees the connections from distinct sources.

I've engaged with Azure support and they have forwarded my findings to the App Service Network team to comment. I'm not aware of any configuration or code changes that I could apply to fix this myself. It seems to me to be an issue with Azure and how it re-uses ports too quickly across different App Services and not taking in to consideration that the destination for all these requests is the same. If it was a different destination then it wouldn't matter.

krispenner avatar Jul 13 '20 18:07 krispenner

@krispenner I just wanted to add that I started seeing this issue from June 24th 2020 coinciding with the rollout of a new version of App Services. The new version is 88.0.7.45 (master-837f2f8549e). It might be a coincidence, but the timing of my issues quite perfectly fits the rollout.

HansOlavS avatar Jul 19 '20 14:07 HansOlavS