1

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?

Prerak Sola
  • 9,517
  • 7
  • 36
  • 67

1 Answers1

0

This cannot be done by any app, unless you have access to your DNS server source to make him choose in which ip to send the request.

If the DNS records where editable by any means, like for example using a hosts file to determine to which IP a domain points, then you could change on the fly that file, and job done. but Android OS/IOS will not let you do that even if there was a hosts file.

You cannot choose to send the request to the a certain ip unless you know of a magic way to pass the domain name to that request in the headers and especially if it has an SSL on it.

The only way to fail over to one server, if the other is down, is if you place in your infrastructure a director which will know which of your two servers is up and running and routes the request to that one.

Tch
  • 1,055
  • 5
  • 11