Circuit Breaker bảo vệ service khỏi cascade failure khi downstream service chậm hoặc lỗi.
3 trạng thái:
- CLOSED (bình thường) → request pass through.
- OPEN (lỗi nhiều) → fail-fast, không gọi downstream.
- HALF_OPEN → thử một số request để kiểm tra recovery.
<dependency>
<groupId>io.github.resilience4j</groupId>
<artifactId>resilience4j-spring-boot3</artifactId>
</dependency>resilience4j:
circuitbreaker:
instances:
payment-service:
slidingWindowSize: 10 # đánh giá 10 request gần nhất
failureRateThreshold: 50 # >50% fail → OPEN
waitDurationInOpenState: 30s # chờ 30s trước khi HALF_OPEN
permittedCallsInHalfOpenState: 3@Service
class PaymentService {
@CircuitBreaker(
name = "payment-service",
fallbackMethod = "paymentFallback"
)
@Retry(name = "payment-service")
public PaymentResult charge(Long orderId, BigDecimal amount) {
return paymentClient.post().uri("/charge")
.body(new ChargeRequest(orderId, amount))
.retrieve().body(PaymentResult.class);
}
private PaymentResult paymentFallback(Long orderId, BigDecimal amount, Exception ex) {
log.warn("Payment service unavailable, queuing order {}", orderId);
pendingOrderQueue.add(orderId); // async retry
return PaymentResult.pending(orderId);
}
}Kết hợp pattern:
- Retry — thử lại trước khi báo lỗi.
- Bulkhead — giới hạn concurrent call.
- TimeLimiter — timeout cho async call.
Actuator endpoint: /actuator/circuitbreakers — xem state hiện tại.
Circuit Breaker protects a service from cascade failure when a downstream service is slow or unavailable.
3 states:
- CLOSED (normal) → requests pass through.
- OPEN (too many failures) → fail-fast, downstream not called.
- HALF_OPEN → tries a limited number of requests to check recovery.
<dependency>
<groupId>io.github.resilience4j</groupId>
<artifactId>resilience4j-spring-boot3</artifactId>
</dependency>resilience4j:
circuitbreaker:
instances:
payment-service:
slidingWindowSize: 10
failureRateThreshold: 50 # >50% fail → OPEN
waitDurationInOpenState: 30s
permittedCallsInHalfOpenState: 3@Service
class PaymentService {
@CircuitBreaker(
name = "payment-service",
fallbackMethod = "paymentFallback"
)
@Retry(name = "payment-service")
public PaymentResult charge(Long orderId, BigDecimal amount) {
return paymentClient.post().uri("/charge")
.body(new ChargeRequest(orderId, amount))
.retrieve().body(PaymentResult.class);
}
private PaymentResult paymentFallback(Long orderId, BigDecimal amount, Exception ex) {
pendingOrderQueue.add(orderId);
return PaymentResult.pending(orderId);
}
}Combined patterns:
- Retry — retry before reporting failure.
- Bulkhead — limit concurrent calls.
- TimeLimiter — timeout for async calls.
Actuator endpoint: /actuator/circuitbreakers — view current state.