Question

I am seeing a lot of Connection Resets in Production.There could be multiple causes to it but I wanted to ensure that there are no Connection leakages coming from in code.I am using Jersey Client in code

Client this.client = ApacheHttpClient.create();

client.resource("/stores/"+storeId).type(MediaType.APPLICATION_JSON_TYPE).put(ClientResponse.class,indexableStore);

Originally I was instantiating client in the following fashion Client this.client = Client.create() and we changed it to ApacheHttpClient.create(). I am not calling close() on the response but I am assuming ApacheHttpClient would do that internally as HttpClient executeMethod gets invoked which handles all the boiler plate stuff for us. Could there be a potential connection leakage in the way the code is written ?

Was it helpful?

Solution

Like you said Connection Reset could be caused by many possible reasons. One such possibility could be that server timed out while processing the request, thats why the client receives connection reset. The comments section of the answered question here discusses possible causes of connection reset in detail. One possible solution I can think of is to configure HttpClient to retry the request in case of a failure. You could set the HttpMethodRetryHandler like below to do so (Reference). You may perhaps need to modify the code based on the exception you receive.

HttpMethodRetryHandler retryHandler = new HttpMethodRetryHandler()
      {
         public boolean retryMethod(
                 final HttpMethod method,
                 final IOException exception,
                 int executionCount)
         {
            if (executionCount >= 5)
            {
               // Do not retry if over max retry count
               return false;
            }
            if (exception instanceof NoHttpResponseException)
            {
               // Retry if the server dropped connection on us
               return true;
            }
            if (!method.isRequestSent())
            {
               // Retry if the request has not been sent fully or
               // if it's OK to retry methods that have been sent
               return true;
            }
            // otherwise do not retry
            return false;
         }
      };

      ApacheHttpClient client = ApacheHttpClient.create();
      HttpClient hc = client.getClientHandler().getHttpClient();
      hc.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, retryHandler);    
       client.resource("/stores/"+storeId).type(MediaType.APPLICATION_JSON_TYPE).put(ClientResponse.class,indexableStore);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top