0
0
Spring Bootframework~5 mins

Circuit breaker with Resilience4j in Spring Boot

Choose your learning style9 modes available
Introduction

A circuit breaker helps your system avoid repeated failures by stopping calls to a failing service temporarily. Resilience4j is a tool that makes adding this protection easy in Spring Boot apps.

When calling an external payment service that might be down sometimes.
When your app depends on a slow database or API that can timeout.
When you want to prevent cascading failures in a microservices setup.
When you want to improve system stability by quickly failing fast on errors.
When you want to monitor and control retries and failures automatically.
Syntax
Spring Boot
1. Add Resilience4j dependency to your Spring Boot project.
2. Configure circuit breaker properties in application.yml or application.properties.
3. Annotate your service method with @CircuitBreaker(name = "serviceName", fallbackMethod = "fallbackMethodName").
4. Implement the fallback method to handle failures gracefully.

The name in @CircuitBreaker links to configuration settings.

The fallbackMethod is called when the circuit is open or an error occurs.

Examples
This example protects the callPaymentService method with a circuit breaker named 'paymentService'.
Spring Boot
@CircuitBreaker(name = "paymentService", fallbackMethod = "paymentFallback")
public String callPaymentService() {
    // call external payment API
}
This fallback method returns a friendly message when the payment service call fails.
Spring Boot
public String paymentFallback(Exception e) {
    return "Payment service is down, please try later.";
}
Example configuration in application.properties to set circuit breaker behavior.
Spring Boot
resilience4j.circuitbreaker.instances.paymentService.registerHealthIndicator=true
resilience4j.circuitbreaker.instances.paymentService.slidingWindowSize=10
resilience4j.circuitbreaker.instances.paymentService.failureRateThreshold=50
Sample Program

This Spring Boot app has a REST endpoint /pay that simulates a payment service. It fails twice and succeeds on the third call. The circuit breaker stops calls when failures are high and uses the fallback method to respond gracefully.

Spring Boot
package com.example.demo;

import io.github.resilience4j.circuitbreaker.annotation.CircuitBreaker;
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;

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

@RestController
class PaymentController {

    private int attempt = 0;

    @GetMapping("/pay")
    @CircuitBreaker(name = "paymentService", fallbackMethod = "paymentFallback")
    public String pay() {
        attempt++;
        if (attempt % 3 != 0) {
            throw new RuntimeException("Payment service failure");
        }
        return "Payment successful on attempt " + attempt;
    }

    public String paymentFallback(Exception e) {
        return "Payment service is currently unavailable. Please try again later.";
    }
}
OutputSuccess
Important Notes

Configure circuit breaker properties carefully to balance between sensitivity and availability.

Fallback methods should be quick and safe to avoid further failures.

Use monitoring tools to track circuit breaker states and metrics.

Summary

Circuit breakers protect your app from repeated failures by stopping calls temporarily.

Resilience4j integrates easily with Spring Boot using annotations and configuration.

Fallback methods provide graceful responses when services fail.