Circuit Breaker chặn cascade failure khi service phụ thuộc đang lỗi: sau N fail liên tiếp, breaker "ngắt mạch" → trả fail/fallback tức thì, sau cooldown cho probe call thử lại. Resilience4j là thư viện hiện đại thay Hystrix (đã EOL).
Ba trạng thái: CLOSED (cho qua, đếm fail) → OPEN (fail-fast) → HALF_OPEN (vài probe) → CLOSED/OPEN.
@CircuitBreaker(name = "paymentService", fallbackMethod = "fallback")
@Retry(name = "paymentService")
public PaymentResult charge(Order order) {
return restClient.post().uri("/charge").body(order).retrieve().body(PaymentResult.class);
}
PaymentResult fallback(Order order, Throwable t) {
return PaymentResult.queuedForRetry(order.id());
}Cấu hình qua application.yml (failureRateThreshold, waitDurationInOpenState, slidingWindowSize).
- Kết hợp
@Retry,@RateLimiter,@TimeLimiter. - Metrics tự đẩy qua Micrometer → Prometheus.
- Fallback phải business-safe: hoãn (queue), trả cached data, fail-fast có context — đừng "trả thành công giả" làm sai sổ sách.
A Circuit Breaker prevents cascade failures when a downstream service is failing: after N consecutive failures it "opens the circuit" → fails fast / invokes a fallback, then probes the service again after a cooldown. Resilience4j is the modern library that replaced Hystrix (end-of-life).
Three states: CLOSED (calls flow, failures counted) → OPEN (fail-fast) → HALF_OPEN (a few probes) → CLOSED/OPEN.
@CircuitBreaker(name = "paymentService", fallbackMethod = "fallback")
@Retry(name = "paymentService")
public PaymentResult charge(Order order) {
return restClient.post().uri("/charge").body(order).retrieve().body(PaymentResult.class);
}
PaymentResult fallback(Order order, Throwable t) {
return PaymentResult.queuedForRetry(order.id());
}Configure via application.yml (failureRateThreshold, waitDurationInOpenState, slidingWindowSize).
- Combine with
@Retry,@RateLimiter,@TimeLimiter. - Metrics flow through Micrometer → Prometheus.
- The fallback must be business-safe: defer (queue), return cached data, or fail fast with context — do not "fake success" and corrupt the books.