0
0
SpringbootHow-ToBeginner · 4 min read

How to Use Circuit Breaker in Spring Boot: Simple Guide

Use @CircuitBreaker annotation from Resilience4j in Spring Boot to wrap methods that call external services. Configure fallback methods to handle failures gracefully and add resilience to your app.
📐

Syntax

The @CircuitBreaker annotation wraps a method to monitor failures and open the circuit when needed. It requires a name to identify the circuit and a fallbackMethod to handle errors.

  • name: The circuit breaker instance name.
  • fallbackMethod: The method called on failure.
java
@CircuitBreaker(name = "serviceCircuitBreaker", fallbackMethod = "fallbackMethod")
public String callExternalService() {
    // code calling external service
}

public String fallbackMethod(Exception e) {
    return "Service is down, please try later.";
}
💻

Example

This example shows a Spring Boot service calling an external API with a circuit breaker. If the call fails, the fallback method returns a friendly message.

java
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import io.github.resilience4j.circuitbreaker.annotation.CircuitBreaker;

@SpringBootApplication
public class CircuitBreakerApp {
    public static void main(String[] args) {
        SpringApplication.run(CircuitBreakerApp.class, args);
    }
}

@RestController
class MyController {

    @GetMapping("/external")
    @CircuitBreaker(name = "externalService", fallbackMethod = "fallbackResponse")
    public String callExternal() {
        if (Math.random() > 0.5) {
            throw new RuntimeException("Service failure");
        }
        return "External service response";
    }

    public String fallbackResponse(Exception e) {
        return "Fallback: External service is unavailable.";
    }
}
Output
When calling /external endpoint: - 50% chance to get "External service response" - 50% chance to get "Fallback: External service is unavailable."
⚠️

Common Pitfalls

  • Not defining a fallbackMethod causes runtime errors when the circuit opens.
  • Fallback method signature must match the original method's parameters plus an Exception parameter.
  • Forgetting to add @EnableCircuitBreaker or missing Resilience4j dependency prevents circuit breaker from working.
  • Using blocking calls inside circuit breaker can reduce effectiveness; prefer non-blocking/reactive if possible.
java
/* Wrong fallback signature example */
@CircuitBreaker(name = "cb", fallbackMethod = "wrongFallback")
public String riskyCall() {
    // ...
}

public String wrongFallback() {
    return "No exception parameter";
}

/* Correct fallback signature */
public String correctFallback(Exception e) {
    return "Handled exception: " + e.getMessage();
}
📊

Quick Reference

Remember these key points when using circuit breaker in Spring Boot:

  • Add Resilience4j dependency in pom.xml or build.gradle.
  • Use @CircuitBreaker(name, fallbackMethod) on methods calling external services.
  • Fallback methods must accept the same parameters plus an Exception.
  • Configure circuit breaker properties in application.yml for thresholds and wait durations.

Key Takeaways

Use @CircuitBreaker annotation from Resilience4j to protect external calls in Spring Boot.
Always define a fallback method with matching parameters plus an Exception to handle failures.
Add Resilience4j dependencies and enable circuit breaker support in your application.
Configure circuit breaker settings in application properties for fine control.
Test fallback behavior to ensure graceful degradation when services fail.