{"id":376,"date":"2023-06-06T16:27:34","date_gmt":"2023-06-06T09:27:34","guid":{"rendered":"https:\/\/thoaicoder.com\/?p=376"},"modified":"2024-01-07T22:54:05","modified_gmt":"2024-01-07T15:54:05","slug":"fault-tolerant-microservices-with-netflix-hystrix","status":"publish","type":"post","link":"https:\/\/thoaicoder.com\/index.php\/2023\/06\/06\/fault-tolerant-microservices-with-netflix-hystrix\/","title":{"rendered":"Fault-Tolerant Microservices with Hystrix Circuit Breaker"},"content":{"rendered":"\n<h1 class=\"wp-block-heading\">1. Fault Tolerance in Microservices Architecture<\/h1>\n\n\n\n<p class=\"wp-block-paragraph\">Fault tolerance is the property that enables a system to continue operating properly in the event of the failure of some of its components. In the context of <strong>microservices architecture<\/strong>, fault tolerance is especially important because the communication between services is distributed and many internal or external network traffic is created for the services to work together.<\/p>\n\n\n\n<figure class=\"wp-block-image size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"778\" height=\"474\" src=\"https:\/\/thoaicoder.com\/wp-content\/uploads\/2023\/08\/image-2.png\" alt=\"\" class=\"wp-image-576\" srcset=\"https:\/\/thoaicoder.com\/wp-content\/uploads\/2023\/08\/image-2.png 778w, https:\/\/thoaicoder.com\/wp-content\/uploads\/2023\/08\/image-2-300x183.png 300w, https:\/\/thoaicoder.com\/wp-content\/uploads\/2023\/08\/image-2-768x468.png 768w\" sizes=\"auto, (max-width: 778px) 100vw, 778px\" \/><\/figure>\n\n\n\n<p class=\"wp-block-paragraph\">To achieve fault tolerance in microservices architecture, there are various patterns, principles, and techniques that can be used, such as implementing circuit breakers, retry mechanisms, and graceful degradation. These techniques allow the system to handle and recover from failures without affecting the overall functionality of the system. Some common fault-tolerant patterns for microservices architecture include the use of <strong>bulkheads<\/strong>, <strong>timeouts<\/strong>, <strong>thread pools,<\/strong> or <strong>circuit breaker<\/strong>. <\/p>\n\n\n\n<h1 class=\"wp-block-heading\">2. Hystrix Circuit Breaker<\/h1>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Circuit breake<\/strong>r is a pattern that wraps requests to external services and detects when they fail. If a failure is detected, the circuit breaker opens. All the subsequent requests immediately return an error instead of making requests to the unhealthy service. It monitors and sees the service that is down and misbehaves with other services. It rejects calls until it becomes healthy again. <\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Hystrix<\/strong> is a library that controls the interaction between microservices to provide latency and fault tolerance. Additionally, it makes sense to modify the UI to let the user know that something might not have worked as expected or would take more time.<\/p>\n\n\n\n<h1 class=\"wp-block-heading\">3. Sample project<\/h1>\n\n\n\n<p class=\"wp-block-paragraph\">We will demonstrate how Hystrix is applied in a microservices system via a sample project. This project is a home loaning service which consume a KYC service to verify customers by the username. You can imagine these services are in a banking microservices-based system which can contain a lot of other services.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">We will use Spring Feign to make RESTful requests to the KYC service and integrate Hystrix into our service. The source code is really straightforward, the&nbsp;<strong>VerificationServiceClient<\/strong>&nbsp;makes request to the KYC API which is consumed by the&nbsp;<strong>VerificationUserService<\/strong>&nbsp;in order to return the verification result to customers via&nbsp;<strong>VerificationUserEndpoint<\/strong>.<\/p>\n\n\n\n<figure class=\"wp-block-image size-large\"><img loading=\"lazy\" decoding=\"async\" width=\"1024\" height=\"451\" src=\"https:\/\/thoaicoder.com\/wp-content\/uploads\/2023\/09\/image-1024x451.png\" alt=\"\" class=\"wp-image-584\" srcset=\"https:\/\/thoaicoder.com\/wp-content\/uploads\/2023\/09\/image-1024x451.png 1024w, https:\/\/thoaicoder.com\/wp-content\/uploads\/2023\/09\/image-300x132.png 300w, https:\/\/thoaicoder.com\/wp-content\/uploads\/2023\/09\/image-768x339.png 768w, https:\/\/thoaicoder.com\/wp-content\/uploads\/2023\/09\/image-1536x677.png 1536w, https:\/\/thoaicoder.com\/wp-content\/uploads\/2023\/09\/image.png 1826w\" sizes=\"auto, (max-width: 1024px) 100vw, 1024px\" \/><\/figure>\n\n\n\n<h2 class=\"wp-block-heading\">3.1. Tech stack<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">JDK 11, Gradle, Spring boot, Spring Feign, Hystrix<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Hystrix is enabled and configured via&nbsp;<em>application.yml<\/em>&nbsp;with some default configurations:<\/p>\n\n\n\n<pre class=\"wp-block-code has-white-color has-tangaroa-background-color has-text-color has-background\" style=\"padding-top:var(--wp--preset--spacing--40);padding-right:var(--wp--preset--spacing--40);padding-bottom:var(--wp--preset--spacing--40);padding-left:var(--wp--preset--spacing--40)\"><code>kyc-service:\n  url: localhost:8082\n\nfeign:\n  hystrix:\n    enabled: true\n\nhystrix:\n  command:\n    default:\n      execution:\n        isolation:\n          thread:\n            timeoutInMilliseconds: 3000\n      circuitBreaker:\n        requestVolumeThreshold: 5\n        sleepWindowInMilliseconds: 2000\n        errorThresholdPercentage: 40<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\">3.2. How Hystrix works?<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Hystrix supports the notion of a <strong>fallback<\/strong>: a default code path that is executed when the circuit is open OR there is an error (response is not 200-300 or timeout). To enable fallbacks for a given\u00a0<code>@FeignClient<\/code>\u00a0set the\u00a0<code>fallback<\/code>\u00a0attribute to the class name that implements the fallback as the <em>VerificationServiceClient<\/em> class below.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><em>VerificationServiceClient.java<\/em><\/p>\n\n\n\n<pre class=\"wp-block-code has-white-color has-tangaroa-background-color has-text-color has-background\" style=\"padding-top:var(--wp--preset--spacing--40);padding-right:var(--wp--preset--spacing--40);padding-bottom:var(--wp--preset--spacing--40);padding-left:var(--wp--preset--spacing--40)\"><code>@FeignClient(value = \"VerificationServiceClient\", url = \"${kyc-service.url}\", fallback = VerificationServiceClientFallback.class)\npublic interface VerificationServiceClient {\n  @PostMapping(value = \"\/kyc\/{userName}\", produces = MediaType.APPLICATION_JSON_VALUE)\n  String verify(@PathVariable String userName);\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><em>VerificationServiceClientFallback.java<\/em><\/p>\n\n\n\n<pre class=\"wp-block-code has-white-color has-tangaroa-background-color has-text-color has-background\" style=\"padding-top:var(--wp--preset--spacing--40);padding-right:var(--wp--preset--spacing--40);padding-bottom:var(--wp--preset--spacing--40);padding-left:var(--wp--preset--spacing--40)\"><code>@Component\npublic class VerificationServiceClientFallback implements VerificationServiceClient{\n\n  @Override\n  public String verify(String userName) {\n    return ApplicationUtil.FALLBACK_MESSAGE;\n  }\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Hystrix does not offer a circuit breaker that breaks after a given number of failures. That means when the fallback is executed, the circuit can be still closed. The Hystrix circuit will break if:<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">&#8221; <em>Within a timespan of duration&nbsp;<code><strong>timeoutInMilliseconds<\/strong><\/code>, the percentage of actions resulting in a handled exception exceeds&nbsp;<code><strong>errorThresholdPercentage<\/strong><\/code>, provided also that the number of actions through the circuit in the timespan is at least&nbsp;<code><strong>requestVolumeThreshold<\/strong><\/code><\/em> &#8220;<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Imagine there was no such minimum-volume-through-the-circuit threshold. Imagine the first call in a time window error. You would have 1 of 1 calls being an error, = 100% failure rate, which is higher than the 50% threshold you have set. So the circuit would open immediately.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Now you may have another question: how the circuit is closed again after opening? There are actually three states: <strong>OPEN<\/strong>, <strong>CLOSED<\/strong>, and <strong>HALF_OPEN<\/strong>. Once the circuit breaker is OPEN and a certain amount of time has passed it lets a single request sneak through. This is the HALF_OPEN state. If successful the circuit breaker is closed, otherwise, it returns to the OPEN state until that amount of time has passed again, where it enters the HALF_OPEN state once again. You can specify the amount of time between the transition from OPEN to HALF_OPEN using the <strong>sleepWindowInMilliseconds <\/strong>property.<\/p>\n\n\n\n<figure class=\"wp-block-image size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"737\" height=\"533\" src=\"https:\/\/thoaicoder.com\/wp-content\/uploads\/2023\/06\/circuit-breaker.png\" alt=\"\" class=\"wp-image-619\" srcset=\"https:\/\/thoaicoder.com\/wp-content\/uploads\/2023\/06\/circuit-breaker.png 737w, https:\/\/thoaicoder.com\/wp-content\/uploads\/2023\/06\/circuit-breaker-300x217.png 300w\" sizes=\"auto, (max-width: 737px) 100vw, 737px\" \/><\/figure>\n\n\n\n<p class=\"wp-block-paragraph\">In order to experiment with how Hystrix works, we will write an integration test with a few scenarios. We will use <a href=\"https:\/\/wiremock.org\/\">Wiremock <\/a>to mock the KYC API.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><em>VerificationServiceClientTest.java<\/em><\/p>\n\n\n\n<pre class=\"wp-block-code has-white-color has-tangaroa-background-color has-text-color has-background\" style=\"padding-top:var(--wp--preset--spacing--40);padding-right:var(--wp--preset--spacing--40);padding-bottom:var(--wp--preset--spacing--40);padding-left:var(--wp--preset--spacing--40)\"><code>@SpringBootTest\n@EnableConfigurationProperties\n@ExtendWith(SpringExtension.class)\n@ContextConfiguration(classes = { Application.class })\n@AutoConfigureWireMock(port = 8082)\npublic class VerificationServiceClientTest {\n\n  @Autowired\n  private VerificationServiceClient verificationServiceClient;\n\n  @BeforeEach\n  public void before() {\n    Hystrix.reset();\n    HealthCountsStream.reset();\n  }<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Scenario 1<\/strong>: the fallback method will be triggered when the response is not 200-300<\/p>\n\n\n\n<pre class=\"wp-block-code has-white-color has-tangaroa-background-color has-text-color has-background\" style=\"padding-top:var(--wp--preset--spacing--40);padding-right:var(--wp--preset--spacing--40);padding-bottom:var(--wp--preset--spacing--40);padding-left:var(--wp--preset--spacing--40)\"><code>  @Test\n  public void fallBackWillBeTriggered_after_responseIsError() throws InterruptedException {\n    WireMock.stubFor(WireMock.post(WireMock.urlPathEqualTo(\"\/kyc\/thoai\"))\n      .willReturn(WireMock.aResponse()\n        .withStatus(500)));\n    String response = verificationServiceClient.verify(\"thoai\");\n    Assertions.assertEquals(response, ApplicationUtil.FALLBACK_MESSAGE);\n  }<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Scenario 2<\/strong>: the fallback will not be triggered when the response is success<\/p>\n\n\n\n<pre class=\"wp-block-code has-white-color has-tangaroa-background-color has-text-color has-background\" style=\"padding-top:var(--wp--preset--spacing--40);padding-right:var(--wp--preset--spacing--40);padding-bottom:var(--wp--preset--spacing--40);padding-left:var(--wp--preset--spacing--40)\"><code>  @Test\n  public void fallBackWillNotBeTriggered_after_responseIsSuccess() throws InterruptedException {\n    WireMock.stubFor(WireMock.post(WireMock.urlPathEqualTo(\"\/kyc\/thoai\"))\n      .willReturn(WireMock.aResponse()\n        .withBody(ApplicationUtil.SUCCESS_MESSAGE)\n        .withStatus(200)));\n    String response = verificationServiceClient.verify(\"thoai\");\n    Assertions.assertEquals(response, ApplicationUtil.SUCCESS_MESSAGE);\n  }<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Scenario 3<\/strong>: the fallback will be triggered when the response is timeout.<br>&#8211; <em>Given<\/em>: hystrix circuit breaker is configured with <strong>timeoutInMilliseconds <\/strong>= 3000ms<br><em>&#8211; When<\/em>: the response will not be returned until after 4000ms<br><em>&#8211; Then<\/em>: fallback will be triggered<\/p>\n\n\n\n<pre class=\"wp-block-code has-white-color has-tangaroa-background-color has-text-color has-background\" style=\"padding-top:var(--wp--preset--spacing--40);padding-right:var(--wp--preset--spacing--40);padding-bottom:var(--wp--preset--spacing--40);padding-left:var(--wp--preset--spacing--40)\"><code>  @Test\n  public void fallBackWillBeTriggered_after_requestTimeOut() throws InterruptedException {\n\n    WireMock.stubFor(WireMock.post(WireMock.urlPathEqualTo(\"\/kyc\/thoai\"))\n      .willReturn(WireMock.aResponse()\n        .withFixedDelay(4000)\n        .withStatus(200)));\n    String response = verificationServiceClient.verify(\"thoai\");\n\n    Assertions.assertEquals(response, ApplicationUtil.FALLBACK_MESSAGE);\n  }<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Scenario 4<\/strong>: the fallback will not be triggered when the response is slow but is still less than <strong>timeoutInMilliseconds<\/strong>.<br>&#8211; <em>Given<\/em>: hystrix circuit breaker is configured with <strong>timeoutInMilliseconds <\/strong>= 3000ms<br><em>&#8211; When<\/em>: the response will not be returned until after 2000ms<br><em>&#8211; Then<\/em>: fallback will not be triggered<\/p>\n\n\n\n<pre class=\"wp-block-code has-white-color has-tangaroa-background-color has-text-color has-background\" style=\"padding-top:var(--wp--preset--spacing--40);padding-right:var(--wp--preset--spacing--40);padding-bottom:var(--wp--preset--spacing--40);padding-left:var(--wp--preset--spacing--40)\"><code>  @Test\n  public void fallBackWillBeTriggered_after_requestTimeOut() throws InterruptedException {\n\n    WireMock.stubFor(WireMock.post(WireMock.urlPathEqualTo(\"\/kyc\/thoai\"))\n      .willReturn(WireMock.aResponse()\n        .withFixedDelay(4000)\n        .withStatus(200)));\n    String response = verificationServiceClient.verify(\"thoai\");\n\n    Assertions.assertEquals(response, ApplicationUtil.FALLBACK_MESSAGE);\n  }<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Scenario 5<\/strong>: the circuit breaker will be opened<br>&#8211; <em>Given<\/em>: hystrix circuit breaker is configured with <strong>requestVolumeThreshold <\/strong>= 5, <strong>sleepWindowInMilliseconds <\/strong>= 2000ms, <strong>errorThresholdPercentage<\/strong> = 40 %<br><em>&#8211; When<\/em>: 3\/5  requests are failing (over 40%) and after 3000ms<br><em>&#8211; Then<\/em>: the circuit will be opened<\/p>\n\n\n\n<pre class=\"wp-block-code has-white-color has-tangaroa-background-color has-text-color has-background\" style=\"padding-top:var(--wp--preset--spacing--40);padding-right:var(--wp--preset--spacing--40);padding-bottom:var(--wp--preset--spacing--40);padding-left:var(--wp--preset--spacing--40)\"><code>  @Test\n\n  public void circuitWillBeOpened() throws InterruptedException {\n\n    WireMock.stubFor(WireMock.post(WireMock.urlPathEqualTo(\"\/kyc\/thoai\"))\n      .willReturn(WireMock.aResponse()\n        .withStatus(200)));\n\n    WireMock.stubFor(WireMock.post(WireMock.urlPathEqualTo(\"\/kyc\/camila\"))\n      .willReturn(WireMock.aResponse()\n        .withStatus(500)));\n\n    verificationServiceClient.verify(\"thoai\");\n    verificationServiceClient.verify(\"camila\");\n    verificationServiceClient.verify(\"camila\");\n    verificationServiceClient.verify(\"thoai\");\n    verificationServiceClient.verify(\"camila\");\n\n    Thread.sleep(3000);\n\n    HystrixCircuitBreaker myCircuitBreaker = HystrixCircuitBreaker.Factory.getInstance(\n      HystrixCommandKey.Factory.asKey(\"VerificationServiceClient#verify(String)\"));\n\n    Assertions.assertTrue(myCircuitBreaker.isOpen());\n  }<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Scenario 6<\/strong>: the circuit is still closed when the total execute time of all requests is less than <strong>sleepWindowInMilliseconds <\/strong>configure<br>&#8211; <em>Given<\/em>: hystrix circuit breaker is configured with <strong>requestVolumeThreshold <\/strong>= 5, <strong>sleepWindowInMilliseconds <\/strong>= 2000ms, <strong>errorThresholdPercentage<\/strong> = 40 %<br><em>&#8211; When<\/em>: 3\/5 requests are failing (over 40%)<br><em>&#8211; Then<\/em>: the circuit will still be closed<\/p>\n\n\n\n<pre class=\"wp-block-code has-white-color has-tangaroa-background-color has-text-color has-background\" style=\"padding-top:var(--wp--preset--spacing--40);padding-right:var(--wp--preset--spacing--40);padding-bottom:var(--wp--preset--spacing--40);padding-left:var(--wp--preset--spacing--40)\"><code>  @Test\r\n  public void circuitWillNotBeOpened_1() throws InterruptedException {\r\r\n    WireMock.stubFor(WireMock.post(WireMock.urlPathEqualTo(\"\/kyc\/thoai\"))\r\n      .willReturn(WireMock.aResponse()\r\n        .withStatus(200)));\r\n\r\n    WireMock.stubFor(WireMock.post(WireMock.urlPathEqualTo(\"\/kyc\/camila\"))\r\n      .willReturn(WireMock.aResponse()\r\n        .withStatus(500)));\r\n\r\n    verificationServiceClient.verify(\"thoai\");\r\n    verificationServiceClient.verify(\"camila\");\r\n    verificationServiceClient.verify(\"camila\");\r\n    verificationServiceClient.verify(\"thoai\");\r\n    verificationServiceClient.verify(\"camila\");\r\n\r\n    HystrixCircuitBreaker myCircuitBreaker = HystrixCircuitBreaker.Factory.getInstance(\r\n      HystrixCommandKey.Factory.asKey(\"VerificationServiceClient#verify(String)\"));\r\n\r\n    Assertions.assertTrue(!myCircuitBreaker.isOpen());\r\n  }<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Scenario 7<\/strong>: the circuit is still closed when the error rate is less than <strong>errorThresholdPercentage <\/strong>configure<br>&#8211; <em>Given<\/em>: hystrix circuit breaker is configured with <strong>requestVolumeThreshold <\/strong>= 5, <strong>sleepWindowInMilliseconds <\/strong>= 2000ms, <strong>errorThresholdPercentage<\/strong> = 40 %<br><em>&#8211; When<\/em>: 1\/5 requests (less than 40%) are failing  and after 3000ms<br><em>&#8211; Then<\/em>: the circuit will still be closed<\/p>\n\n\n\n<pre class=\"wp-block-code has-white-color has-tangaroa-background-color has-text-color has-background\" style=\"padding-top:var(--wp--preset--spacing--40);padding-right:var(--wp--preset--spacing--40);padding-bottom:var(--wp--preset--spacing--40);padding-left:var(--wp--preset--spacing--40)\"><code>  @Test\r\r\n  public void circuitWillNotBeOpened_2() throws InterruptedException {\r\r\n    WireMock.stubFor(WireMock.post(WireMock.urlPathEqualTo(\"\/kyc\/thoai\"))\r\n      .willReturn(WireMock.aResponse()\r\n        .withStatus(200)));\r\n\r\n    WireMock.stubFor(WireMock.post(WireMock.urlPathEqualTo(\"\/kyc\/camila\"))\r\n      .willReturn(WireMock.aResponse()\r\n        .withStatus(500)));\r\n\r\n    verificationServiceClient.verify(\"thoai\");\r\n    verificationServiceClient.verify(\"camila\");\r\n    verificationServiceClient.verify(\"thoai\");\r\n    verificationServiceClient.verify(\"thoai\");\r\n    verificationServiceClient.verify(\"thoai\");\r\n\r\n    Thread.sleep(3000);\r\n\r\n    HystrixCircuitBreaker myCircuitBreaker = HystrixCircuitBreaker.Factory.getInstance(\r\n      HystrixCommandKey.Factory.asKey(\"VerificationServiceClient#verify(String)\"));\r\n\r\n    Assertions.assertTrue(!myCircuitBreaker.isOpen());\r\n  }<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Scenario 8<\/strong>: the circuit is still closed when the total number of requests is less than <strong>requestVolumeThreshold <\/strong>configure<br>&#8211; <em>Given<\/em>: hystrix circuit breaker is configured with <strong>requestVolumeThreshold <\/strong>= 5, <strong>sleepWindowInMilliseconds <\/strong>= 2000ms, <strong>errorThresholdPercentage<\/strong> = 40 %<br>&#8211; <em>When<\/em>: 2\/2 requests (less than 5) are failing  and after 3000ms<br>&#8211; Then: the circuit will still be closed<\/p>\n\n\n\n<pre class=\"wp-block-code has-white-color has-tangaroa-background-color has-text-color has-background\" style=\"padding-top:var(--wp--preset--spacing--40);padding-right:var(--wp--preset--spacing--40);padding-bottom:var(--wp--preset--spacing--40);padding-left:var(--wp--preset--spacing--40)\"><code>  @Test\r\r\n  public void circuitWillNotBeOpened_3() throws InterruptedException {\r\r\n    WireMock.stubFor(WireMock.post(WireMock.urlPathEqualTo(\"\/kyc\/camila\"))\r\n      .willReturn(WireMock.aResponse()\r\n        .withStatus(500)));\r\n\r\n    verificationServiceClient.verify(\"camila\");\r\n    verificationServiceClient.verify(\"camila\");\r\n\r\n    Thread.sleep(3000);\r\n\r\n    HystrixCircuitBreaker myCircuitBreaker = HystrixCircuitBreaker.Factory.getInstance(\r\n      HystrixCommandKey.Factory.asKey(\"VerificationServiceClient#verify(String)\"));\r\n\r\n    Assertions.assertTrue(!myCircuitBreaker.isOpen());\r\n  }<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Scenario 9:<\/strong> the circuit is closed again <br>&#8211; <em>Given<\/em>: hystrix circuit breaker is configured with <strong>sleepWindowInMilliseconds <\/strong>= 2000ms, the circuit is opened <br>&#8211; <em>When<\/em>: after 2000ms and the request succeeds <br>&#8211; Then: the circuit-breaker transitions to closed again<\/p>\n\n\n\n<pre class=\"wp-block-code has-white-color has-tangaroa-background-color has-text-color has-background\" style=\"padding-top:var(--wp--preset--spacing--40);padding-right:var(--wp--preset--spacing--40);padding-bottom:var(--wp--preset--spacing--40);padding-left:var(--wp--preset--spacing--40)\"><code>  @Test\r\n  public void circuitWillBeClosedAgain() throws InterruptedException {\r\r\n    WireMock.stubFor(WireMock.post(WireMock.urlPathEqualTo(\"\/kyc\/thoai\"))\r\n      .willReturn(WireMock.aResponse()\r\n        .withBody(ApplicationUtil.SUCCESS_MESSAGE)\r\n        .withStatus(200)));\r\n    WireMock.stubFor(WireMock.post(WireMock.urlPathEqualTo(\"\/kyc\/camila\"))\r\n      .willReturn(WireMock.aResponse()\r\n        .withStatus(500)));\r\n\r\n    verificationServiceClient.verify(\"thoai\");\r\n    verificationServiceClient.verify(\"camila\");\r\n    verificationServiceClient.verify(\"camila\");\r\n    verificationServiceClient.verify(\"thoai\");\r\n    verificationServiceClient.verify(\"camila\");\r\n\r\n    Thread.sleep(3000);\r\n\r\n    HystrixCircuitBreaker myCircuitBreaker = HystrixCircuitBreaker.Factory.getInstance(\r\n      HystrixCommandKey.Factory.asKey(\"VerificationServiceClient#verify(String)\"));\r\n\r\n    \/**\r\n     * when the circuit is already opened\r\n     *\/\r\n\r\n    String response = verificationServiceClient.verify(\"thoai\");\r\n    \/\/then response is cached with fallback\r\n    Assertions.assertEquals(response, ApplicationUtil.FALLBACK_MESSAGE);\r\n\r\n    Thread.sleep(2000);\r\n    response = verificationServiceClient.verify(\"thoai\");\r\n    Assertions.assertEquals(response, ApplicationUtil.SUCCESS_MESSAGE);\r\n    \/\/the circuit will be closed again after 2000ms and the response is success\r\n    Assertions.assertTrue(!myCircuitBreaker.isOpen());\r\n  }<\/code><\/pre>\n\n\n\n<h1 class=\"wp-block-heading\">4. Conclusion<\/h1>\n\n\n\n<p class=\"wp-block-paragraph\">We\u2019ve looked at the Circuit Breaker pattern and how it works to achieve Fault Tolerance in Microservices Architecture by a sample project with some test scenarios. Hystrix also implements <strong>bulkhead <\/strong>which limits the number of concurrent calls to a component to achieve Fault Tolerance too, we will dive into bulkhead in another article. The sample project can be found on&nbsp;<a href=\"https:\/\/github.com\/ThoaiNguyenHuu842\/hystrix-circuit-breaker\">GitHub<\/a>.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>1. Fault Tolerance in Microservices Architecture Fault tolerance is the property that enables a system [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":619,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[1],"tags":[33,32,34,28,22,23,29],"class_list":["post-376","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-java","tag-circuit-breaker","tag-hystrix","tag-hystrix-circuit-breaker","tag-java","tag-micro-services","tag-spring","tag-wiremock"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v19.14 - https:\/\/yoast.com\/wordpress\/plugins\/seo\/ -->\n<title>Fault-Tolerant Microservices with Hystrix Circuit Breaker - I \u2764 Code<\/title>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/thoaicoder.com\/index.php\/2023\/06\/06\/fault-tolerant-microservices-with-netflix-hystrix\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Fault-Tolerant Microservices with Hystrix Circuit Breaker - I \u2764 Code\" \/>\n<meta property=\"og:description\" content=\"1. Fault Tolerance in Microservices Architecture Fault tolerance is the property that enables a system [&hellip;]\" \/>\n<meta property=\"og:url\" content=\"https:\/\/thoaicoder.com\/index.php\/2023\/06\/06\/fault-tolerant-microservices-with-netflix-hystrix\/\" \/>\n<meta property=\"og:site_name\" content=\"I \u2764 Code\" \/>\n<meta property=\"article:published_time\" content=\"2023-06-06T09:27:34+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2024-01-07T15:54:05+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/thoaicoder.com\/wp-content\/uploads\/2023\/06\/circuit-breaker.png\" \/>\n\t<meta property=\"og:image:width\" content=\"737\" \/>\n\t<meta property=\"og:image:height\" content=\"533\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/png\" \/>\n<meta name=\"author\" content=\"Thoai\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"Thoai\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"8 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\/\/schema.org\",\"@graph\":[{\"@type\":\"Article\",\"@id\":\"https:\/\/thoaicoder.com\/index.php\/2023\/06\/06\/fault-tolerant-microservices-with-netflix-hystrix\/#article\",\"isPartOf\":{\"@id\":\"https:\/\/thoaicoder.com\/index.php\/2023\/06\/06\/fault-tolerant-microservices-with-netflix-hystrix\/\"},\"author\":{\"name\":\"Thoai\",\"@id\":\"https:\/\/thoaicoder.com\/#\/schema\/person\/a3304c209434f63c501b05622d7d2720\"},\"headline\":\"Fault-Tolerant Microservices with Hystrix Circuit Breaker\",\"datePublished\":\"2023-06-06T09:27:34+00:00\",\"dateModified\":\"2024-01-07T15:54:05+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\/\/thoaicoder.com\/index.php\/2023\/06\/06\/fault-tolerant-microservices-with-netflix-hystrix\/\"},\"wordCount\":1047,\"commentCount\":0,\"publisher\":{\"@id\":\"https:\/\/thoaicoder.com\/#\/schema\/person\/a3304c209434f63c501b05622d7d2720\"},\"keywords\":[\"Circuit Breaker\",\"Hystrix\",\"Hystrix Circuit Breaker\",\"Java\",\"Micro-services\",\"Spring\",\"Wiremock\"],\"articleSection\":[\"Java\"],\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"CommentAction\",\"name\":\"Comment\",\"target\":[\"https:\/\/thoaicoder.com\/index.php\/2023\/06\/06\/fault-tolerant-microservices-with-netflix-hystrix\/#respond\"]}]},{\"@type\":\"WebPage\",\"@id\":\"https:\/\/thoaicoder.com\/index.php\/2023\/06\/06\/fault-tolerant-microservices-with-netflix-hystrix\/\",\"url\":\"https:\/\/thoaicoder.com\/index.php\/2023\/06\/06\/fault-tolerant-microservices-with-netflix-hystrix\/\",\"name\":\"Fault-Tolerant Microservices with Hystrix Circuit Breaker - I \u2764 Code\",\"isPartOf\":{\"@id\":\"https:\/\/thoaicoder.com\/#website\"},\"datePublished\":\"2023-06-06T09:27:34+00:00\",\"dateModified\":\"2024-01-07T15:54:05+00:00\",\"breadcrumb\":{\"@id\":\"https:\/\/thoaicoder.com\/index.php\/2023\/06\/06\/fault-tolerant-microservices-with-netflix-hystrix\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/thoaicoder.com\/index.php\/2023\/06\/06\/fault-tolerant-microservices-with-netflix-hystrix\/\"]}]},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\/\/thoaicoder.com\/index.php\/2023\/06\/06\/fault-tolerant-microservices-with-netflix-hystrix\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\/\/thoaicoder.com\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"Fault-Tolerant Microservices with Hystrix Circuit Breaker\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\/\/thoaicoder.com\/#website\",\"url\":\"https:\/\/thoaicoder.com\/\",\"name\":\"I \u2764 Code\",\"description\":\"\",\"publisher\":{\"@id\":\"https:\/\/thoaicoder.com\/#\/schema\/person\/a3304c209434f63c501b05622d7d2720\"},\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\/\/thoaicoder.com\/?s={search_term_string}\"},\"query-input\":\"required name=search_term_string\"}],\"inLanguage\":\"en-US\"},{\"@type\":[\"Person\",\"Organization\"],\"@id\":\"https:\/\/thoaicoder.com\/#\/schema\/person\/a3304c209434f63c501b05622d7d2720\",\"name\":\"Thoai\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/thoaicoder.com\/#\/schema\/person\/image\/\",\"url\":\"https:\/\/thoaicoder.com\/wp-content\/uploads\/2023\/03\/photo_2023-01-05_22-53-32.jpg\",\"contentUrl\":\"https:\/\/thoaicoder.com\/wp-content\/uploads\/2023\/03\/photo_2023-01-05_22-53-32.jpg\",\"width\":640,\"height\":640,\"caption\":\"Thoai\"},\"logo\":{\"@id\":\"https:\/\/thoaicoder.com\/#\/schema\/person\/image\/\"},\"sameAs\":[\"https:\/\/thoaicoder.com\",\"https:\/\/www.linkedin.com\/in\/huu-thoai-nguyen\/\"],\"url\":\"https:\/\/thoaicoder.com\/index.php\/author\/admin_cvyxq4b8\/\"}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Fault-Tolerant Microservices with Hystrix Circuit Breaker - I \u2764 Code","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/thoaicoder.com\/index.php\/2023\/06\/06\/fault-tolerant-microservices-with-netflix-hystrix\/","og_locale":"en_US","og_type":"article","og_title":"Fault-Tolerant Microservices with Hystrix Circuit Breaker - I \u2764 Code","og_description":"1. Fault Tolerance in Microservices Architecture Fault tolerance is the property that enables a system [&hellip;]","og_url":"https:\/\/thoaicoder.com\/index.php\/2023\/06\/06\/fault-tolerant-microservices-with-netflix-hystrix\/","og_site_name":"I \u2764 Code","article_published_time":"2023-06-06T09:27:34+00:00","article_modified_time":"2024-01-07T15:54:05+00:00","og_image":[{"width":737,"height":533,"url":"https:\/\/thoaicoder.com\/wp-content\/uploads\/2023\/06\/circuit-breaker.png","type":"image\/png"}],"author":"Thoai","twitter_card":"summary_large_image","twitter_misc":{"Written by":"Thoai","Est. reading time":"8 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/thoaicoder.com\/index.php\/2023\/06\/06\/fault-tolerant-microservices-with-netflix-hystrix\/#article","isPartOf":{"@id":"https:\/\/thoaicoder.com\/index.php\/2023\/06\/06\/fault-tolerant-microservices-with-netflix-hystrix\/"},"author":{"name":"Thoai","@id":"https:\/\/thoaicoder.com\/#\/schema\/person\/a3304c209434f63c501b05622d7d2720"},"headline":"Fault-Tolerant Microservices with Hystrix Circuit Breaker","datePublished":"2023-06-06T09:27:34+00:00","dateModified":"2024-01-07T15:54:05+00:00","mainEntityOfPage":{"@id":"https:\/\/thoaicoder.com\/index.php\/2023\/06\/06\/fault-tolerant-microservices-with-netflix-hystrix\/"},"wordCount":1047,"commentCount":0,"publisher":{"@id":"https:\/\/thoaicoder.com\/#\/schema\/person\/a3304c209434f63c501b05622d7d2720"},"keywords":["Circuit Breaker","Hystrix","Hystrix Circuit Breaker","Java","Micro-services","Spring","Wiremock"],"articleSection":["Java"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/thoaicoder.com\/index.php\/2023\/06\/06\/fault-tolerant-microservices-with-netflix-hystrix\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/thoaicoder.com\/index.php\/2023\/06\/06\/fault-tolerant-microservices-with-netflix-hystrix\/","url":"https:\/\/thoaicoder.com\/index.php\/2023\/06\/06\/fault-tolerant-microservices-with-netflix-hystrix\/","name":"Fault-Tolerant Microservices with Hystrix Circuit Breaker - I \u2764 Code","isPartOf":{"@id":"https:\/\/thoaicoder.com\/#website"},"datePublished":"2023-06-06T09:27:34+00:00","dateModified":"2024-01-07T15:54:05+00:00","breadcrumb":{"@id":"https:\/\/thoaicoder.com\/index.php\/2023\/06\/06\/fault-tolerant-microservices-with-netflix-hystrix\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/thoaicoder.com\/index.php\/2023\/06\/06\/fault-tolerant-microservices-with-netflix-hystrix\/"]}]},{"@type":"BreadcrumbList","@id":"https:\/\/thoaicoder.com\/index.php\/2023\/06\/06\/fault-tolerant-microservices-with-netflix-hystrix\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/thoaicoder.com\/"},{"@type":"ListItem","position":2,"name":"Fault-Tolerant Microservices with Hystrix Circuit Breaker"}]},{"@type":"WebSite","@id":"https:\/\/thoaicoder.com\/#website","url":"https:\/\/thoaicoder.com\/","name":"I \u2764 Code","description":"","publisher":{"@id":"https:\/\/thoaicoder.com\/#\/schema\/person\/a3304c209434f63c501b05622d7d2720"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/thoaicoder.com\/?s={search_term_string}"},"query-input":"required name=search_term_string"}],"inLanguage":"en-US"},{"@type":["Person","Organization"],"@id":"https:\/\/thoaicoder.com\/#\/schema\/person\/a3304c209434f63c501b05622d7d2720","name":"Thoai","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/thoaicoder.com\/#\/schema\/person\/image\/","url":"https:\/\/thoaicoder.com\/wp-content\/uploads\/2023\/03\/photo_2023-01-05_22-53-32.jpg","contentUrl":"https:\/\/thoaicoder.com\/wp-content\/uploads\/2023\/03\/photo_2023-01-05_22-53-32.jpg","width":640,"height":640,"caption":"Thoai"},"logo":{"@id":"https:\/\/thoaicoder.com\/#\/schema\/person\/image\/"},"sameAs":["https:\/\/thoaicoder.com","https:\/\/www.linkedin.com\/in\/huu-thoai-nguyen\/"],"url":"https:\/\/thoaicoder.com\/index.php\/author\/admin_cvyxq4b8\/"}]}},"_links":{"self":[{"href":"https:\/\/thoaicoder.com\/index.php\/wp-json\/wp\/v2\/posts\/376","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/thoaicoder.com\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/thoaicoder.com\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/thoaicoder.com\/index.php\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/thoaicoder.com\/index.php\/wp-json\/wp\/v2\/comments?post=376"}],"version-history":[{"count":34,"href":"https:\/\/thoaicoder.com\/index.php\/wp-json\/wp\/v2\/posts\/376\/revisions"}],"predecessor-version":[{"id":754,"href":"https:\/\/thoaicoder.com\/index.php\/wp-json\/wp\/v2\/posts\/376\/revisions\/754"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/thoaicoder.com\/index.php\/wp-json\/wp\/v2\/media\/619"}],"wp:attachment":[{"href":"https:\/\/thoaicoder.com\/index.php\/wp-json\/wp\/v2\/media?parent=376"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/thoaicoder.com\/index.php\/wp-json\/wp\/v2\/categories?post=376"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/thoaicoder.com\/index.php\/wp-json\/wp\/v2\/tags?post=376"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}