title: Best way to implement "retries" when hitting api endpoint?
body: <p>I am using the <strong>ApacheHttpClient</strong></p>
  
  <p>I have a Java method (inside a Java microservice) that makes an Http <strong>POST</strong> request to an external endpoint (Endpoint that I do not own). Everything usually works well, but sometimes the endpoint is down and fails. The code looks something like this (simplified):</p>
  
  <pre><code>private HttpResponseData postRequest(String url) throws Exception {
          HttpResponseData response = null;
          try (InputStream key = MyAPICaller.class.getResourceAsStream(keyPath)) {
              MyAPICaller.initializeApiClient(Username, PassString, key);
              int attempts = REQUEST_RETRY_COUNT; // starts at 3
  
              while (attempts-- &gt; 0) {
                  try {
                      response = MyAPICaller.getInstance().post(url);
                      break;
                  } catch (Exception e) {
                      log.error("Post Request to {} failed. Retries remaining {}", url, attempts);
                      Thread.sleep(REQUEST_RETRY_DELAY * 1000);
                  }
              }
  
              if (response == null)
                  throw new Exception("Post request retries exceeded. Unable to complete request.");
  
          }
          return response;
      }
  </code></pre>
  
  <p>I didn't write the original code, but as you can see, it looks like it makes a request, and while the <em>REQUEST_RETRY_COUNT</em> is greater than 0 (which it always will be it seems),  it will try to make a <strong>post</strong> to the url. It looks like for some reason there is a break point there, so after it jumps into the <code>try</code> block, it will always break out and there is no retry mechanism.</p>
  
  <p>Is there a common design pattern in Java for implementing a Retry pattern for hitting an external endpoint? I Know in Javascript you can use the Fetch API with returns a promise, is there something similar with Java?</p>