Sobes.tech
Senior

Tell about a challenging task from your work experience — API integration and solving timeout issues.

sobes.tech AI

Answer from AI

In one of the projects, there was a task to integrate with an external API that often returned timeouts due to high load and network instability. To solve this problem, I implemented several approaches:

  1. Retry mechanism with exponential backoff. This allowed automatically retrying requests at increasing intervals, reducing load and giving the API time to recover.

  2. Asynchronous request processing. Instead of blocking calls, I used CompletableFuture for parallel request sending, which improved system responsiveness.

  3. Timeout settings at the HTTP client level. I set reasonable connection and read timeout values to avoid waiting too long and to free resources.

  4. Response caching. For repeated requests, I stored results for some time to reduce the number of API calls.

Example code using HttpClient and retries:

HttpClient client = HttpClient.newHttpClient();

public CompletableFuture<HttpResponse<String>> sendWithRetry(HttpRequest request, int retries) {
    return client.sendAsync(request, HttpResponse.BodyHandlers.ofString())
        .handleAsync((response, ex) -> {
            if (ex != null && retries > 0) {
                try {
                    Thread.sleep((long) Math.pow(2, 3 - retries) * 1000); // exponential delay
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                }
                return sendWithRetry(request, retries - 1).join();
            }
            return response;
        });
}

This approach significantly increased integration stability and reduced failures due to timeouts.