Polling REST API in Java

Polling REST API in Java

Polling REST API in Java

Polling is Expensive

Running a job on the database to perform operations at End of Day (EOD) is a scheduled operation. If the job is scheduled we can time our calls. Typically schedulers are not ran at peak hours. The difference between polling and running a scheduler is that polling for information does not timed. Polling does not know the state of the API server, its peak hours and traffic conditions. On the contrary, polling is expected to be performed at peak hours. Polling at peak hours can lead to timeouts due to network congestions.

Polling needs to be performed at regular intervals. Polling is expensive since 98% of the API calls are wasted.

Polling a Third Party API

Polling a third party API is the only choice, when the API is not under our control. If the API was within clients domain i.e not third-party, the API can implement techniques like long polling, server sent events and web-sockets to push information when available.

Error Handling during polling

Common error that occur during polling are

  1. Timeouts: Due to heavy load and network congestions the API server cannot serve all requests. The requests in the queue are timed out. In such a case the client needs to account for these timeouts and prepare for a retry.
  2. Error response: Server can send a 5XX error due to changes in the server. Client must log these error messages.
  3. Follow Redirect: The client should always implement auto-redirects. Since the API servers can change over time.

Polling using OK HTTP

We will demonstrate OKHttp as a client library to perform polling. Also perform error handling and retries in case of failure.

String url = "";      

OkHttpClient client = new OkHttpClient();

Request request = new Request.Builder().url(url).build();

client.newCall(request).enqueue(new Callback() {

    public void onFailure(Call call, IOException e) {
        // retry here

    public void onResponse(Call call, final Response response) throws IOException {
        if (!response.isSuccessful()) {
            // failure
            // retry here
        } else {
            // success
Icon For Arrow-up