failsafe-lib / failsafe

Fault tolerance and resilience patterns for the JVM
https://failsafe.dev
Apache License 2.0
4.2k stars 297 forks source link

[Question]Can withBackoff and withDelay be used at the same time? #369

Open ripley opened 1 year ago

ripley commented 1 year ago

Say if I want to apply retry delay by increasing the retry interval exponentially for most cases, but for some specific exceptions like client error 429 I would like to calculate the delay by myself, is that possible by setting delay withBackoff and withDelay at the same time?

It appears this is not supported since delay will be overwritten but it'll be good if this can be confirmed.

Thanks for your attention.

Tembrel commented 1 year ago

You can't use both withDelay and withBackoff in the same RetryPolicy, since they use the same configuration fields internally.

But you can use a backoff delay in conjunction with a computed delay, e.g., (uncompiled, untested):

RetryPolicy retryPolicy = RetryPolicy.builder()
    // other stuff
    .withBackoff(...)
    .withDelayFn(context -> is429OrOtherSpecial(context) ? computeCustomDelay(context) : -1)
    .build();

I'm basing that idea on this Javadoc:

A negative return value will cause Failsafe to use a configured fixed or backoff delay

ripley commented 1 year ago

Thanks @Tembrel 👍 This works as expected.