Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement HttpRequestRetryHandler with Exponential Backoff?

I wish to implement a HttpRequestRetryHandler for a HttpClient in case the request fails first time.

I also wish to implement Exponential backoff for subsequent retries. Mathematically it can be implemented as

E(c) = 1/2(2 power (c) -1)

enter image description here

but I am struggling for quite some time now to implement it in the code with HttpRequestRetryHandler.

like image 566
Gaurav Agarwal Avatar asked Dec 10 '12 21:12

Gaurav Agarwal


People also ask

How do you implement an exponential back off?

An exponential backoff algorithm retries requests exponentially, increasing the waiting time between retries up to a maximum backoff time. For example: Make a request to Cloud IoT Core. If the request fails, wait 1 + random_number_milliseconds seconds and retry the request.

How do you implement exponential backoff in node JS?

First, make sure to wait only before retries and not the first request. Waiting first and sending a request then introduces a delay even for successful requests. And second, make sure to put a limit to the number of retries so that the code eventually gives up and throws an error.

What is exponential backoff API?

Exponential backoff is an algorithm that retries requests to the server based on certain status codes in the server response. The retries exponentially increase the waiting time up to a certain threshold.


2 Answers

HttpRequestRetryHandler doesn't allow you that level of control; if you want to do something very specific like that, I'd recommend implementing something like a Handler where you can post Runnables to be executed with a delay, using for example Handler.postDelayed() with increasing delays as per your formula.

Handler mHandler = new Handler();
int mDelay = INITIAL_DELAY;

// try request
mHandler.postDelayed(mDelay, new Runnable() {
   public void run() {
      // try your request here; if it fails, then repost:
      if (failed) {
          mDelay *= 2;  // or as per your formula
          mHandler.postDelayed(mDelay, this);
      }
      else {
          // success!
      }
   }
});
like image 195
Bruno Oliveira Avatar answered Oct 17 '22 04:10

Bruno Oliveira


Here is a good framework with backoff algorithms - https://github.com/rholder/guava-retrying

like image 44
Nikita Koksharov Avatar answered Oct 17 '22 03:10

Nikita Koksharov