Saturday, 23 January 2021

OkHttp retry connection on another IP if 503

In my backend application, my load balancer uses round robin to distribute traffic. So, I have two A records against my hostname:

- x.x.x.x myapp.com
- y.y.y.y myapp.com

In any one of them is down it returns 503 Service Unavailable.

Now, in my Android application, I am using OkHttp 4.x to do network operations and the DNS resoulution is cached on the device. So, if the cahced IP goes down, it does not try to reach the other IP and the request fails. I tried multiple approaches to make it work but no cussess till now. The things I tried:

  • Add a Network interceptor and set Retry-After: 0 header to force it to retry the request.
  • Add a count variable and send the request again until count becomes 0
  • Set Connection Pool to .connectionPool(new ConnectionPool(0, 1, TimeUnit.MILLISECONDS)) to avoid caching the connection and retry the request
  • As per the docs, it says it should retry automatically on failed conenction, but it doesn't for status code 503. I verified this in the profiler and I could see only 1 request going.

To make sure both the IPs are resolved, I added the below code:

OkHttpClient client = new OkHttpClient.Builder().build();

Thread thread = new Thread(new Runnable() {
    @Override
    public void run() {
        try  {
            List<InetAddress> addr = client.dns().lookup("myapp.com");

            for ( InetAddress a : addr ) {
                Log.d(TAG, a.toString());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
});

thread.start();

And I get both the entries in the log:

myapp.com/x.x.x.x
myapp.com/y.y.y.y

So, is there a way to make the OkHttp client try the other IP in case of failure?



from OkHttp retry connection on another IP if 503

No comments:

Post a Comment