Search code examples
javaspring-bootspring-retrycircuit-breaker

Spring CircuitBreakerRetryPolicy: open the circuit for all requests


I want to implement the circuit breaker design pattern using Spring-Retry. The main problem that I am facing is opening the circuit for all requests. It still keeps retrying if I make a new request from the browser.

I have a RetryTemplate with a CircuitBreakerRetryPolicy defined as follows:

@Configuration
public class MyApplicationConfig {

    @Bean
    public RetryTemplate retryTemplate(RetryPolicy cbRetry) {
        RetryTemplate retryTemplate = new RetryTemplate();

        FixedBackOffPolicy fixedBackOffPolicy = new FixedBackOffPolicy();
        fixedBackOffPolicy.setBackOffPeriod(1000);

        retryTemplate.setBackOffPolicy(fixedBackOffPolicy);
        retryTemplate.setRetryPolicy(circuitBreakerRetryPolicy);
        return retryTemplate;
    }

    @Bean("cbRetry")
    public RetryPolicy circuitBreaker() {
        CircuitBreakerRetryPolicy circuitBreakerRetryPolicy = new CircuitBreakerRetryPolicy();
        circuitBreakerRetryPolicy.setResetTimeout(20000);
        circuitBreakerRetryPolicy.setOpenTimeout(2000);
        return circuitBreakerRetryPolicy;
    }
}

Then I use RestTemplate to make a call to a non-existing url, just to make the call fail and I count the retries. The circuit is supposed to open in 2 seconds, but if I try another call right after the first one fails, it keeps retrying again.

How do I make the circuit stay open for a given openTimeOut period for all incoming requests?

I experimented with RetryState by providing it to the retryTemplate call, but that doesn't help either.

Thank you!


Solution

  • spring-retry state is thread-bound.

    You would need to write a custom policy to maintain global state.