Chapter 10.5☕ 16 min read

Circuit Breaker with Resilience4j

In microservices, if <code>payment-service</code> goes down, <code>user-service</code> will keep trying to call it, waiting for timeouts, and eventually run out of threads and crash too. This is a cascading failure. <strong>Resilience4j</strong> stops this by acting as a Circuit Breaker.

01The Concept: Circuit Breaking

The Hyderabad Electricity Fuse Analogy:

In your house, if there is a short circuit, a massive amount of current flows. If there were no fuse, the wire would melt and the house would catch fire. The fuse wire melts instantly, breaking the circuit and stopping the flow.

A Circuit Breaker in software works the same way. If payment-service fails 5 times in a row, the circuit "trips" (Opens). user-service stops calling it completely and instantly returns a fallback response. This saves user-service from crashing.

02Technical Explanation
  1. Resilience4j: The modern replacement for the dead Netflix Hystrix.
  2. Circuit States:
    * Closed: Everything works. Requests go through.
    * Open: Too many failures. Requests are blocked immediately. Returns fallback.
    * Half-Open: After a wait, it lets one request through to test if the server is back.
  3. @CircuitBreaker: Annotation applied to a method (usually a Feign client call).
  4. fallbackMethod: The method to execute if the circuit is open or the call fails.
03Full Working Code: Resilient API Call

1. pom.xml

<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-circuitbreaker-resilience4j</artifactId>
</dependency>

2. application.yml (Resilience4j Config)

resilience4j:
circuitbreaker:
instances:
paymentServiceCB:
failure-rate-threshold: 50 # Open circuit if 50% of calls fail
wait-duration-in-open-state: 10s # Stay open for 10 seconds
sliding-window-size: 4 # Look at last 4 calls

3. The Service Code with Fallback (PaymentService.java)

package com.devinhyderabad;

import io.github.resilience4j.circuitbreaker.annotation.CircuitBreaker;
import org.springframework.stereotype.Service;

@Service
public class PaymentService {

private final PaymentClient paymentClient;

public PaymentService(PaymentClient paymentClient) {
this.paymentClient = paymentClient;
}

// 1. If this method fails, route to fallbackPayment
@CircuitBreaker(name = "paymentServiceCB", fallbackMethod = "fallbackPayment")
public String processPayment(Long userId) {
return paymentClient.getPaymentStatus(userId); // Might fail
}

// 2. Fallback method (Must have same signature + Exception param)
public String fallbackPayment(Long userId, Exception e) {
return "Payment service is currently down. Please try again later. (Fallback)";
}
}
04Why It Matters

Interview Question: "What is the Circuit Breaker pattern, and why did Netflix Hystrix get replaced?"

Answer: A Circuit Breaker prevents cascading failures by stopping calls to a failing service. Hystrix was deprecated because it relied on blocking Servlet threads and wasn't designed for modern reactive Java. Resilience4j is lightweight, uses functional programming, and supports reactive/non-blocking architectures.

05Interview Note

Enterprise Note: Resilience4j isn't just for Circuit Breaking. It also provides Retry (try 3 times before failing), Rate Limiter (limit calls per second), and Bulkhead (limit concurrent threads to isolate failures).

Key Takeaways

  • ✅ Circuit Breaker prevents cascading failures by stopping calls to a failing service
  • ✅ Three states: Closed (normal), Open (blocking), Half-Open (testing recovery)
  • ✅ @CircuitBreaker annotation with fallbackMethod handles failures gracefully
  • ✅ Resilience4j also provides Retry, Rate Limiter, and Bulkhead for resilience