{"id":1,"date":"2024-08-18T15:04:30","date_gmt":"2024-08-18T13:04:30","guid":{"rendered":"https:\/\/codeswarm.io\/?p=1"},"modified":"2026-07-19T13:35:45","modified_gmt":"2026-07-19T11:35:45","slug":"witaj-swiecie","status":"publish","type":"post","link":"https:\/\/codeswarm.io\/?p=1","title":{"rendered":"The Circuit breaker pattern in Java"},"content":{"rendered":"\n<p class=\"wp-block-paragraph\">The <strong>Circuit Breaker<\/strong> pattern is used to prevent an application from performing an operation that is likely to fail. In microservices architecture, it\u2019s commonly used to handle fault tolerance when calling external services that may fail or take a long time to respond.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Imagine a scenario where a microservice (<code>Service A<\/code>) calls another service (<code>Service B<\/code>). If <code>Service B<\/code> is down or slow to respond, without a circuit breaker, <code>Service A<\/code> will continue making requests, which may lead to cascading failures or resource exhaustion. The Circuit Breaker pattern \u201copens\u201d and stops calling the failing service for a period to allow it to recover, then \u201ccloses\u201d after the service is healthy again.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Key states of Circuit Breaker:<\/strong><\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li><strong>Closed<\/strong>: The circuit breaker allows requests to pass through as normal.<\/li>\n\n\n\n<li><strong>Open<\/strong>: The circuit breaker prevents requests from being sent, returning a fallback response immediately.<\/li>\n\n\n\n<li><strong>Half-Open<\/strong>: The circuit breaker allows a limited number of requests to check if the service has recovered.<\/li>\n<\/ol>\n\n\n\n<h2 class=\"wp-block-heading\">Implementation<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">There are different ways to implement Circuit Breaker pattern. In this case we\u2019ll use <code>Resilience4j<\/code> for implementing the Circuit Breaker in Spring Boot. Add the following dependency to your <code>pom.xml<\/code>:<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"xml\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">&lt;dependency>\n    &lt;groupId>io.github.resilience4j&lt;\/groupId>\n    &lt;artifactId>resilience4j-spring-boot2&lt;\/artifactId>\n    &lt;version>1.7.0&lt;\/version>\n&lt;\/dependency><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Here\u2019s an example of how we might use a <code>RestTemplate<\/code> to call another service:<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">import org.springframework.stereotype.Service;\nimport org.springframework.web.client.RestTemplate;\nimport org.springframework.beans.factory.annotation.Autowired;\n@Service\npublic class ExternalService {\n    @Autowired\n    private RestTemplate restTemplate;\n    public String callExternalService() {\n        String url = \"http:\/\/localhost:8081\/external-api\";\n        return restTemplate.getForObject(url, String.class);\n    }\n}<\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">This method will call an external API, but what happens if this API is down or slow? This is where the Circuit Breaker comes in.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">To apply the Circuit Breaker, annotate the method that makes the external call using the <code>@CircuitBreaker<\/code> annotation.<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">import io.github.resilience4j.circuitbreaker.annotation.CircuitBreaker;\nimport org.springframework.stereotype.Service;\n@Service\npublic class ExternalService {\n    @Autowired\n    private RestTemplate restTemplate;\n    private static final String EXTERNAL_SERVICE = \"externalService\";\n    @CircuitBreaker(name = EXTERNAL_SERVICE, fallbackMethod = \"fallbackResponse\")\n    public String callExternalService() {\n        String url = \"http:\/\/localhost:8081\/external-api\";\n        return restTemplate.getForObject(url, String.class);\n    }\n    public String fallbackResponse(Throwable t) {\n        return \"External Service is currently unavailable. Please try again later.\";\n    }\n}<\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><strong><code>@CircuitBreaker(name = \"externalService\")<\/code><\/strong>: This specifies that Resilience4j will manage the circuit breaker with the name <code>externalService<\/code>. <\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong><code>fallbackMethod = \"fallbackResponse\"<\/code><\/strong>: If the circuit breaker is in the <code>OPEN<\/code> state, or if the call to the external service fails, this fallback method will be executed.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Now we can configure the circuit breaker properties in our <code>application.yml<\/code> file.<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"yaml\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">resilience4j.circuitbreaker:\n  instances:\n    externalService:\n      slidingWindowSize: 5\n      failureRateThreshold: 50\n      waitDurationInOpenState: 10000\n      permittedNumberOfCallsInHalfOpenState: 3<\/pre>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong><code>slidingWindowSize<\/code><\/strong>: The number of calls to evaluate for the failure rate,<\/li>\n\n\n\n<li><strong><code>failureRateThreshold<\/code><\/strong>: The percentage of failures that trip the circuit breaker. In this case, if 50% of calls fail, the circuit opens,<\/li>\n\n\n\n<li><strong><code>waitDurationInOpenState<\/code><\/strong>: The amount of time (in milliseconds) the circuit breaker stays open before transitioning to half-open state,<\/li>\n\n\n\n<li><strong><code>permittedNumberOfCallsInHalfOpenState<\/code><\/strong>: The number of calls to allow in the half-open state to check if the external service has recovered.<\/li>\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\">How it works<\/h2>\n\n\n\n<ol class=\"wp-block-list\">\n<li>Initially, the circuit breaker is in the <strong>Closed<\/strong> state. All requests pass through to the external service.<\/li>\n\n\n\n<li>If the failure rate (e.g., timeouts or errors) exceeds the <code>failureRateThreshold<\/code>, the circuit breaker transitions to the <strong>Open<\/strong> state. In this state, all requests are blocked, and the fallback method is executed.<\/li>\n\n\n\n<li>After the <code>waitDurationInOpenState<\/code>, the circuit breaker transitions to the <strong>Half-Open<\/strong> state, allowing a limited number of requests to check if the service has recovered. <\/li>\n\n\n\n<li>If the service responds successfully during the Half-Open state, the circuit breaker transitions back to <strong>Closed<\/strong>. Otherwise, it reopens.<\/li>\n<\/ol>\n\n\n\n<h2 class=\"wp-block-heading\">Summary<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">The Circuit Breaker pattern prevents continuous calls to a failing service, providing a graceful degradation (using the fallback method) while the service recovers. Using Resilience4j with Spring Boot simplifies the implementation, allowing you to control fault tolerance with minimal effort.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>The Circuit Breaker pattern is used to prevent an application from performing an operation that is likely to fail. In microservices architecture, it\u2019s commonly used to handle fault tolerance when calling external services that may fail or take a long time to respond. Imagine a scenario where a microservice (Service A) calls another service (Service &hellip; <a href=\"https:\/\/codeswarm.io\/?p=1\" class=\"more-link\">Continue reading <span class=\"screen-reader-text\">The Circuit breaker pattern in Java<\/span> <span class=\"meta-nav\">&rarr;<\/span><\/a><\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[26,23],"tags":[18,25],"class_list":["post-1","post","type-post","status-publish","format-standard","hentry","category-design-patterns","category-programming","tag-java","tag-spring"],"_links":{"self":[{"href":"https:\/\/codeswarm.io\/index.php?rest_route=\/wp\/v2\/posts\/1","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/codeswarm.io\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/codeswarm.io\/index.php?rest_route=\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/codeswarm.io\/index.php?rest_route=\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/codeswarm.io\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=1"}],"version-history":[{"count":9,"href":"https:\/\/codeswarm.io\/index.php?rest_route=\/wp\/v2\/posts\/1\/revisions"}],"predecessor-version":[{"id":122,"href":"https:\/\/codeswarm.io\/index.php?rest_route=\/wp\/v2\/posts\/1\/revisions\/122"}],"wp:attachment":[{"href":"https:\/\/codeswarm.io\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=1"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/codeswarm.io\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=1"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/codeswarm.io\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=1"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}