Only one usage of each socket address (protocol/network address/port) is normally permitted
<p>The last few weeks we have been experiencing this error message while using the Azure Search SDK (1.1.1 - 1.1.2) and performing searches.</p>

<p>We consume the Search SDK from internal APIs (deployed as Azure Web Apps) that scale up-down based on traffic (so there could be more than 1 instance of the APIs doing the searches).</p>

<p>Our API queries 5 different indexes and maintains an in-memory copy of the SearchIndexClient object that corresponds to each index, a very simple implementation would look like:</p>

<pre><code>public class AzureSearchService
{
    private readonly SearchServiceClient _serviceClient;

    private Dictionary&lt;string, SearchIndexClient&gt; _clientDictionary;

    public AzureSearchService()
    {
        _serviceClient = new SearchServiceClient("myservicename", new SearchCredentials("myservicekey"));
        _clientDictionary = new Dictionary&lt;string, SearchIndexClient&gt;();
    }

    public SearchIndexClient GetClient(string indexName)
    {
        try
        {
            if (!_clientDictionary.ContainsKey(indexName))
            {
                _clientDictionary.Add(indexName, _serviceClient.Indexes.GetClient(indexName));
            }
            return _clientDictionary[indexName];
        }
        catch
        {
            return null;
        }
    }

    public async Task&lt;SearchResults&gt; SearchIndex(SearchIndexClient client, string text)
    {
        var parameters = new SearchParameters();
        parameters.Top = 10;
        parameters.IncludeTotalResultCount = true;
        var response = await client.Documents.SearchWithHttpMessagesAsync(text, parameters, null, null);
        return response.Body;
    }
}
</code></pre>

<p>And the API would invoke the service by:</p>

<pre><code>public class SearchController : ApiController
{
        private readonly AzureSearchService service;

        public SearchController()
        {
            service = new AzureSearchService();
        }


        public async Task&lt;HttpResponseMessage&gt; Post(string indexName, [FromBody] string text)
        {
            var indexClient = service.GetClient(indexName);
            var results = await service.SearchIndex(indexClient, text);
            return Request.CreateResponse(HttpStatusCode.OK, results, Configuration.Formatters.JsonFormatter);              
        }

}
</code></pre>

<p>We are using <code>SearchWithHttpMessagesAsync</code> due to a requirement to receive custom HTTP headers instead of the <code>SearchAsync</code> method.</p>

<p>This way we avoid opening/closing the client under traffic bursts. Before using this memory cache (and wrapping each client on a <code>using</code> clause) we would get port exhaustion alerts on Azure App Services.</p>

<p>Is this a good pattern? Could we be receiving this error because of the multiple instances running in parallel? </p>

<p>In case it is needed, the stack trace shows:</p>

<pre><code>System.Net.Http.HttpRequestException: Only one usage of each socket address (protocol/network address/port) is normally permitted service.ip.address.hidden:443


[SocketException:Only one usage of each socket address (protocol/network address/port)is normally permitted service.ip.address.hidden:443]

at System.Net.Sockets.Socket.EndConnect(IAsyncResult asyncResult)

at System.Net.ServicePoint.ConnectSocketInternal(Boolean connectFailure,Socket s4,Socket s6,Socket&amp; socket,IPAddress&amp; address,ConnectSocketState state,IAsyncResult asyncResult,Exception&amp; exception)



[WebException:Unable to connect to the remote server]

at System.Net.HttpWebRequest.EndGetRequestStream(IAsyncResult asyncResult,TransportContext&amp; context)

at System.Net.Http.HttpClientHandler.GetRequestStreamCallback(IAsyncResult ar)
</code></pre>

<p><strong>EDIT</strong>: We are <strong>also</strong> receiving this error <code>A connection attempt failed because the connected party did not properly respond after a period of time</code>:</p>

<pre><code>System.Net.Http.HttpRequestException: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond service.ip.address.hidden:443


[SocketException:A connection attempt failed because the connected party did not properly respond after a period of time,or established connection failed because connected host has failed to respond service.ip.address.hidden:443]

at System.Net.Sockets.Socket.EndConnect(IAsyncResult asyncResult)

at System.Net.ServicePoint.ConnectSocketInternal(Boolean connectFailure,Socket s4,Socket s6,Socket&amp; socket,IPAddress&amp; address,ConnectSocketState state,IAsyncResult asyncResult,Exception&amp; exception)



[WebException:Unable to connect to the remote server]

at System.Net.HttpWebRequest.EndGetRequestStream(IAsyncResult asyncResult,TransportContext&amp; context)

at System.Net.Http.HttpClientHandler.GetRequestStreamCallback(IAsyncResult ar)
</code></pre>