title: Spring Boot RestTemplate random ResourceAccessException: Connection reset errors
body: <p>I have a system that implements 4 micro-services. The four services need to occasionally share information and they do it via RESTful requests using Spring's RestTemplate. Currently about 5%-10% of the requests fail with an exception like:</p>
  
  <pre><code>org.springframework.web.client.ResourceAccessException: I/O error on POST request for "https://otherservice.com/path": Connection reset; nested exception is java.net.SocketException: Connection reset
  </code></pre>
  
  <p>Again, this appears random and only fails about 5%-10% of the time. I have tried multiple things but nothing seems to work. Currently I am trying this:</p>
  
  <p>Configuration:
  </p>
  
  <pre class="lang-java prettyprint-override"><code>@Configuration
  public class BeanConfiguration {
  
      @Bean
      public RestTemplate restTemplate() {
          ClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(HttpClients.createDefault());
          return new RestTemplate(requestFactory);
      }
  }
  </code></pre>
  
  <p>Service:</p>
  
  <pre class="lang-java prettyprint-override"><code>@Autowired
  public MyService(RestTemplate restTemplate) {
      this.restTemplate = restTemplate;
  }
  
  public Contact addContact(Contact contact) {
      HttpEntity&lt;Contact&gt; entity = new HttpEntity&lt;&gt;(contact, authenticationTokenInfo.setTokenHeaders());
      ResponseEntity&lt;Contact&gt; response = restTemplate.exchange(contact_base_url, HttpMethod.POST, entity, Contact.class);
      return response.getBody();
  }
  </code></pre>
  
  <p>I have tried a number of different approaches and nothing has made any difference. I tried this for example:</p>
  
  <pre class="lang-java prettyprint-override"><code>@Bean
  public RestTemplate restTemplate(RestTemplateBuilder builder) {
      return builder.build();
  }
  </code></pre>
  
  <p>I am logging all of the requests in each of my micro-services and it doesn't appear that the requests are actually hitting the other services. They just fail. According to the logs they fail in less than 50 ms so it isn't a timeout issue. For a couple of them I have implemented an exponential back-off retry but that isn't really a viable solution.</p>