Skip to content

Redesign of the request retry strategy - #3328

Open
ok2c wants to merge 1 commit into
apache:masterfrom
ok2c:request_retry_strategy
Open

ok2c wants to merge 1 commit into
apache:masterfrom
ok2c:request_retry_strategy

Conversation

@ok2c

@ok2c ok2c commented Nov 30, 2026

Copy link
Copy Markdown
Member

@arturobernalg Please review.

Remark: I am not a particularly big fan of Optional given how terribly it gets abused. In this instance however i believe its use is appropriate. I am open to suggestions of different approaches such as using a custom value object to represent the result of the strategy methods.

@SuppressWarnings("deprecation")
public class HttpRequestRetryStrategyAdaptor implements RequestRetryStrategy {

private final org.apache.hc.client5.http.HttpRequestRetryStrategy strategy;

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@ok2c please avoid full qualifier. Otherwise LGTM

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@arturobernalg Yes, I know. But this is to avoid deprecation warnings that cannot be avoided otherwise. Suppress deprecation annotation does not apply to imports.

@xcapdevila xcapdevila left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks @ok2c for merging #3326 into 5.6.x and for the ping to review this redesign! I fetched 2b4428868 locally, ran the unit/checkstyle/japicmp checks, and left one design question on the I/O retry delay plus three small inline suggestions.

Overall design & Optional<TimeValue> vs. custom value object

Big +1 to collapsing the two-step contract (boolean retryRequest + TimeValue getRetryInterval) into a single method, and to adding HttpRequest request to the HTTP response overload (retryRequest(HttpRequest, HttpResponse, int, HttpContext)):

  1. Single-pass decision & interval calculation: Computing and validating the delay once eliminates the class of drift between the eligibility check and the actual pause, and also avoids parsing Retry-After twice (which previously called System.currentTimeMillis() twice when Retry-After was an HTTP-date, creating a small TOCTOU window around responseTimeout).
  2. HttpRequest available on 429/503 responses: Having request in the response overload makes it straightforward for custom strategies or subclasses to inspect the HTTP method, headers, or idempotency markers without reaching into HttpContext.
  3. On Optional<TimeValue> vs. a custom value object: I agree Optional<TimeValue> is a good fit here. Since "do not retry" carries no state and "retry" carries a single non-negative TimeValue (0 ms for immediate retry, > 0 for delayed retry), Optional<TimeValue> makes illegal states (retry = false, delay = 5s) unrepresentable without introducing another public type. The only reason to prefer a dedicated value object (e.g. RetryDecision.noRetry() / RetryDecision.retryAfter(TimeValue)) would be if you anticipate attaching extra metadata in the future (reason, attributes, etc.) or avoiding Optional wrapper allocation on hot error paths.

Minor non-inline notes

  • Source-compatibility / release notes: HttpClientBuilder, HttpAsyncClientBuilder, and H2AsyncClientBuilder now overload setRetryStrategy(HttpRequestRetryStrategy) (@Deprecated) and setRetryStrategy(RequestRetryStrategy). Binary compatibility (japicmp against 5.6) and typed arguments are unaffected, though a literal builder.setRetryStrategy(null) call becomes ambiguous at compile time unless cast (or unless the new setter is named setRequestRetryStrategy). Worth a small mention in the 5.7 migration/release notes if keeping the overloaded name.
  • Test naming / adaptor coverage: TestDefaultHttpRequestRetryStrategy.java now tests DefaultRequestRetryStrategy rather than the deprecated DefaultHttpRequestRetryStrategy—might be worth renaming to TestDefaultRequestRetryStrategy (and optionally keeping a small test covering HttpRequestRetryStrategyAdaptor + DefaultHttpRequestRetryStrategy).

Comment on lines +144 to +146
if (handleAsRetriable(exception) && handleAsIdempotent(request)) {
return Optional.of(defaultRetryInterval);
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Previously, HttpRequestRetryStrategy#getRetryInterval(HttpRequest, IOException, int, HttpContext) defaulted to TimeValue.ZERO_MILLISECONDS (not overridden by DefaultHttpRequestRetryStrategy), so recoverable I/O errors on idempotent requests—most notably NoHttpResponseException on stale keep-alive connections—were retried immediately (0 ms).

With DefaultRequestRetryStrategy.INSTANCE, those I/O retries will now pause for defaultRetryInterval (1 s).

  1. Is this 0 ms -> 1 s change on recoverable I/O errors intentional (so defaultRetryInterval governs both overloads), or should I/O retries still default to TimeValue.ZERO_MILLISECONDS to avoid adding 1 s latency on stale keep-alive recovery?
  2. If using defaultRetryInterval here is intentional, would it also make sense to guard against defaultRetryInterval.compareTo(responseTimeout) > 0 as in the HttpResponse overload below (L164-171)?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is this 0 ms -> 1 s change on recoverable I/O errors intentional

@xcapdevila Yes, it is intentional. I think the old behavior of retrying the request immediately in case of a I/O error is wrong. This also makes the i/o error recovery consistent between with that of 429 and 503 responses.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If using defaultRetryInterval here is intentional, would it also make sense to guard against defaultRetryInterval.compareTo(responseTimeout) > 0 as in the HttpResponse overload below (L164-171)?

@xcapdevila defaultRetryInterval is set by the user explicitly or 1 second by default and cannot be influenced by the opposite endpoint. I do not think the responseTimeout applies here.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fair point on both counts @ok2c — keeping responseTimeout strictly as a guard against untrusted server-supplied Retry-After values, and defaulting to 1 s in DefaultRequestRetryStrategy.INSTANCE, makes sense for 5.7.

One small API ergonomics suggestion while DefaultRequestRetryStrategy is still new: since a single defaultRetryInterval now governs both IOException retries and headerless 429/503 responses, callers who still want 0 ms on I/O retries (e.g. classic HTTP/1.1 clients hitting NoHttpResponseException on half-closed pooled connections reused within the 2 s validateAfterInactivity window) cannot pass TimeValue.ZERO_MILLISECONDS without also making headerless 429/503 retry at 0 ms.

Would you consider adding an overload DefaultRequestRetryStrategy(int maxRetries, TimeValue defaultIoRetryInterval, TimeValue defaultResponseRetryInterval) — plus a default no-arg public DefaultRequestRetryStrategy() like DefaultHttpRequestRetryStrategy had for subclasses? Totally your call either way, the PR looks great!

Comment on lines +156 to +161
Args.notNull(response, "response");

if (execCount > this.maxRetries) {
// Do not retry if over max retries
return Optional.empty();
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In the IOException overload above (L134-143), request is validated with Args.notNull(request, "request") and checked for CancellableDependency#isCancelled(). Adding the same checks here avoids sleeping/retrying an already cancelled request when a 429/503 arrives.

(Also confirming: keeping 429/503 retries independent of handleAsIdempotent(request) by default remains intentional, while subclasses can now easily enforce handleAsIdempotent(request) thanks to the new request parameter.)

Suggested change
Args.notNull(response, "response");
if (execCount > this.maxRetries) {
// Do not retry if over max retries
return Optional.empty();
}
Args.notNull(request, "request");
Args.notNull(response, "response");
if (execCount > this.maxRetries) {
// Do not retry if over max retries
return Optional.empty();
}
if (request instanceof CancellableDependency && ((CancellableDependency) request).isCancelled()) {
return Optional.empty();
}

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@xcapdevila Request validation is now done consistently in case of an i/o error and recoverable status.

Comment on lines +55 to +66
if (strategy.retryRequest(request, exception, execCount, context)) {
return Optional.of(strategy.getRetryInterval(request, exception, execCount, context));
}
return Optional.empty();
}

@Override
public Optional<TimeValue> retryRequest(final HttpRequest request, final HttpResponse response, final int execCount, final HttpContext context) {
if (strategy.retryRequest(response, execCount, context)) {
return Optional.of(strategy.getRetryInterval(response, execCount, context));
}
return Optional.empty();

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Previously, if a legacy custom HttpRequestRetryStrategy returned null (or a negative TimeValue) from getRetryInterval(...), HttpRequestRetryExec / AsyncHttpRequestRetryExec guarded it via TimeValue.isPositive(delay) and retried immediately without failing. With Optional.of(...), a null return from a legacy strategy will throw NullPointerException (and Optional.ofNullable cannot be used since Optional.empty() means "do not retry").

Normalizing with the same idiom used in AsyncHttpRequestRetryExec preserves the exact legacy behavior for both overloads:

Suggested change
if (strategy.retryRequest(request, exception, execCount, context)) {
return Optional.of(strategy.getRetryInterval(request, exception, execCount, context));
}
return Optional.empty();
}
@Override
public Optional<TimeValue> retryRequest(final HttpRequest request, final HttpResponse response, final int execCount, final HttpContext context) {
if (strategy.retryRequest(response, execCount, context)) {
return Optional.of(strategy.getRetryInterval(response, execCount, context));
}
return Optional.empty();
if (strategy.retryRequest(request, exception, execCount, context)) {
final TimeValue interval = strategy.getRetryInterval(request, exception, execCount, context);
return Optional.of(TimeValue.isPositive(interval) ? interval : TimeValue.ZERO_MILLISECONDS);
}
return Optional.empty();
}
@Override
public Optional<TimeValue> retryRequest(final HttpRequest request, final HttpResponse response, final int execCount, final HttpContext context) {
if (strategy.retryRequest(response, execCount, context)) {
final TimeValue interval = strategy.getRetryInterval(response, execCount, context);
return Optional.of(TimeValue.isPositive(interval) ? interval : TimeValue.ZERO_MILLISECONDS);
}
return Optional.empty();

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@xcapdevila Makes sense. Made the classic exec behave the same way.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks @ok2c! Guarding in HttpRequestRetryExec is even better since it covers any RequestRetryStrategy implementation.

Just two small spots left in d3dccf3109:

  1. HttpRequestRetryExec L159 (IOException branch) still uses final TimeValue delay = retryPeriod.get(); without the TimeValue.isPositive(...) check added on L128 (unlike AsyncHttpRequestRetryExec L193).
  2. HttpRequestRetryStrategyAdaptor (L56, L64) still calls Optional.of(...) directly, which would throw NPE before reaching the exec handler if a legacy HttpRequestRetryStrategy#getRetryInterval returns null (the suggestion above on the adaptor still applies if you want to guard that too).

Comment on lines +41 to +75
* Strategy interface to determine if the request should be retied in case
* of an i/o error or a 4xx or 5xx status response.
*
* @since 5.7
*/
@Contract(threading = ThreadingBehavior.STATELESS)
public interface RequestRetryStrategy {

/**
* Determines if a method should be retried after an I/O exception
* occurred during execution.
*
* @param request the request failed due to an I/O exception
* @param exception the exception that occurred
* @param execCount the number of times this method has been
* unsuccessfully executed
* @param context the context for the request execution
*
* @return {@code true} if the request should be retried, {@code false}
* otherwise
*/
Optional<TimeValue> retryRequest(HttpRequest request, IOException exception, int execCount, HttpContext context);

/**
* Determines if a method should be retried given the response from
* the target server.
*
* @param response the response from the target server
* @param execCount the number of times this method has been
* unsuccessfully executed
* @param context the context for the request execution
*
* @return {@code true} if the request should be retried, {@code false}
* otherwise
*/

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Minor Javadoc fixes: typo retied -> retried, missing @param request on the second overload, and updating @return from the old boolean contract to Optional<TimeValue>:

Suggested change
* Strategy interface to determine if the request should be retied in case
* of an i/o error or a 4xx or 5xx status response.
*
* @since 5.7
*/
@Contract(threading = ThreadingBehavior.STATELESS)
public interface RequestRetryStrategy {
/**
* Determines if a method should be retried after an I/O exception
* occurred during execution.
*
* @param request the request failed due to an I/O exception
* @param exception the exception that occurred
* @param execCount the number of times this method has been
* unsuccessfully executed
* @param context the context for the request execution
*
* @return {@code true} if the request should be retried, {@code false}
* otherwise
*/
Optional<TimeValue> retryRequest(HttpRequest request, IOException exception, int execCount, HttpContext context);
/**
* Determines if a method should be retried given the response from
* the target server.
*
* @param response the response from the target server
* @param execCount the number of times this method has been
* unsuccessfully executed
* @param context the context for the request execution
*
* @return {@code true} if the request should be retried, {@code false}
* otherwise
*/
* Strategy interface to determine if the request should be retried in case
* of an I/O error or a 4xx or 5xx status response.
*
* @since 5.7
*/
@Contract(threading = ThreadingBehavior.STATELESS)
public interface RequestRetryStrategy {
/**
* Determines if a method should be retried after an I/O exception
* occurred during execution.
*
* @param request the request failed due to an I/O exception
* @param exception the exception that occurred
* @param execCount the number of times this method has been
* unsuccessfully executed
* @param context the context for the request execution
*
* @return an {@link Optional} containing the retry delay if the request
* should be retried, or {@link Optional#empty()} otherwise
*/
Optional<TimeValue> retryRequest(HttpRequest request, IOException exception, int execCount, HttpContext context);
/**
* Determines if a method should be retried given the response from
* the target server.
*
* @param request the request executed
* @param response the response from the target server
* @param execCount the number of times this method has been
* unsuccessfully executed
* @param context the context for the request execution
*
* @return an {@link Optional} containing the retry delay if the request
* should be retried, or {@link Optional#empty()} otherwise
*/

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@xcapdevila Corrected.

@ok2c
ok2c force-pushed the request_retry_strategy branch 2 times, most recently from 253fc63 to ade5ebc Compare December 2, 2026 12:34
@ok2c

ok2c commented Dec 2, 2026

Copy link
Copy Markdown
Member Author

Source-compatibility / release notes: HttpClientBuilder, HttpAsyncClientBuilder, and H2AsyncClientBuilder now overload setRetryStrategy(HttpRequestRetryStrategy)

@xcapdevila OK. I renamed the new setter to avoid the conflict with the deprecated method

@ok2c
ok2c force-pushed the request_retry_strategy branch from ade5ebc to 46b1ac9 Compare December 2, 2026 12:36
@ok2c
ok2c force-pushed the request_retry_strategy branch from 46b1ac9 to d3dccf3 Compare December 2, 2026 13:02
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

5.7.x 5.7 release series

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants