Senior
If an external service has a timeout of 60 seconds, can we set the same? How to solve the problem of a long response?
sobes.tech AI
Answer from AI
Setting a client-side timeout (your service) equal to the third-party service timeout (60 seconds) is not recommended. If the timeouts match, the client will simply receive an error after 60 seconds without being able to handle the situation in advance.
It is better to set the client timeout lower, for example, 30-50 seconds, to have the opportunity to handle the error or switch to a backup scenario.
To address the issue of a long response time from a third-party service, you can:
- Use asynchronous calls with subsequent result processing (e.g., via message queues).
- Cache results if the data does not require instant updates.
- Implement a retry mechanism with exponential backoff.
- Use a Circuit Breaker to prevent system overload during long delays.
Example of setting a timeout in Java using HttpClient:
HttpClient client = HttpClient.newBuilder()
.connectTimeout(Duration.ofSeconds(10))
.build();
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("https://example.com/api"))
.timeout(Duration.ofSeconds(30)) // request timeout less than third-party service
.build();
try {
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
// handle response
} catch (HttpTimeoutException e) {
// handle timeout
}