title: "An operation on a socket could not be performed" with HttpClientFactory
body: <p>I'm having a long-running triggered webjob on Azure, that uses multiple typed http clients to access remote services. The amount of requests per launch goes as far as millions, but after ~30k I'm getting the following exception:</p>
  
  <blockquote>
    <p>System.Net.Http.HttpRequestException: An operation on a socket could not be performed because the system lacked sufficient buffer space or because a queue was full.</p>
  </blockquote>
  
  <p>I'm using the Microsoft.Extensions.Http 2.2.0 to inject typed http clients with Http Client Factory.</p>
  
  <p>By now I've tried running this locally with fake data and receiver; and monitor the connections with</p>
  
  <blockquote>
    <p>netstat -b</p>
  </blockquote>
  
  <p>...and</p>
  
  <blockquote>
    <p>var ipProperties = IPGlobalProperties.GetIPGlobalProperties();</p>
    
    <p>var tcpConnections = ipProperties.GetActiveTcpConnections();</p>
  </blockquote>
  
  <p>...but I couldn't reproduce the error; and amount of connections stayed around the same the whole time. It makes me think something other than connection limit causes this error.</p>
  
  <p>I'd try the same in Azure; but this does not seem to work as Kudu doesn't allow netstat or similar command.</p>
  
  <p>The clients are added to services like this:</p>
  
  <pre class="lang-cs prettyprint-override"><code>collection.AddHttpClient&lt;ISenderClient, SenderClient&gt;()
                  .ConfigureHttpClient((provider, client) =&gt;
              {
                   //... configuring base url and headers
              })
                  .SetHandlerLifetime(TimeSpan.FromMinutes(1));
  </code></pre>
  
  <p>Then injected into SenderClient:</p>
  
  <pre class="lang-cs prettyprint-override"><code>public sealed class SenderClient : ISenderClient, IDisposable
      {
          private readonly HttpClient _httpClient;
  
          public SenderClient(HttpClient httpClient)
          {
              _httpClient = httpClient ?? throw new ArgumentNullException(nameof(httpClient));
          }
  
          public void Dispose()
          {
              _httpClient?.Dispose();
          }
      }
  </code></pre>
  
  <p>SenderClient itself is retrieved from service provider:</p>
  
  <pre class="lang-cs prettyprint-override"><code>_client = _provider.GetService&lt;ISenderClient&gt;();
  </code></pre>
  
  <p>...and later used in Parallel.ForEach loop to distribute http requests:</p>
  
  <pre class="lang-cs prettyprint-override"><code>Parallel.ForEach(batches, new ParallelOptions { MaxDegreeOfParallelism = 8 }, (batch, state, i) =&gt;
              {
                  using (var scope = _provider.CreateScope())
                  {
                      var provider = scope.ServiceProvider;
  
                      //... dto mapping
  
                      var response = _client.SendAsync&lt;Request, Response&gt;(request).GetAwaiter().GetResult();
                   }
               }
  </code></pre>
  
  <p>where SendAsync is</p>
  
  <pre class="lang-cs prettyprint-override"><code>public async Task&lt;TResponse&gt; SendAsync&lt;TRequest, TResponse&gt;(TRequest request)
          {
              var json = JsonConvert.SerializeObject(request);
              using (var content = new StringContent(json, Encoding.UTF8, "application/json"))
              using (var response = await _client.PostAsync(_url, content))
              {
                  var responseString = await response.Content.ReadAsStringAsync();
                  return JsonConvert.DeserializeObject&lt;TResponse&gt;(responseString);
              }
          }
  </code></pre>
  
  <p>Could anybody please explain what could cause this exception, as I'm having hard times trying to fix this issue for a long time by now..?</p>
  
  <p>EDIT: I believe that my question is not a duplicate of <a href="https://stackoverflow.com/questions/23211017/azure-server-got-error-system-lacked-sufficient-buffer-space-or-because-a-queue">this post</a>, because I'm using HttpClientFactory rather than handling clients manually. This should take care of managing, refreshing and disposing of connections; and is considered a preferred way of handling http clients.</p>
  
  <p>I should only have one connection of a type at a certain period of time with this approach.</p>