Resilience4j is a lightweight fault-tolerance library designed for Java and Spring Boot microservices. It helps applications gracefully handle failures, slow responses, network issues, traffic spikes, and temporary outages.
Client | V Order Service | V Payment Service (Slow / Down)
Without resilience mechanisms:
With Resilience4j:
| Module | Purpose | Example |
|---|---|---|
| Circuit Breaker | Stop repeated failing calls | Payment API Down |
| Retry | Retry temporary failures | Network Timeout |
| Rate Limiter | Control request rate | Prevent API Abuse |
| Bulkhead | Isolate resources | Prevent thread exhaustion |
| Time Limiter | Set timeout limits | Slow External API |
| Cache | Store frequently used data | Reference Data |
Circuit Breaker prevents continuous calls to a failing service.
CLOSED | Failures exceed threshold | OPEN | Wait Duration | HALF_OPEN | Success --> CLOSED Failure --> OPEN
@Service
public class PaymentService {
@CircuitBreaker(
name = "paymentService",
fallbackMethod = "fallbackResponse"
)
public String makePayment() {
if(new Random().nextBoolean()) {
throw new RuntimeException(
"Payment Service Failed"
);
}
return "Payment Success";
}
public String fallbackResponse(Exception ex) {
return "Fallback Response";
}
}
resilience4j:
circuitbreaker:
instances:
paymentService:
failureRateThreshold: 50
minimumNumberOfCalls: 10
slidingWindowSize: 20
waitDurationInOpenState: 30s
| State | Description |
|---|---|
| CLOSED | Normal traffic allowed |
| OPEN | Requests blocked |
| HALF_OPEN | Testing recovery |
Automatically retries failed requests for transient failures.
Failure | Retry 1 | Retry 2 | Retry 3 | Success / Fallback
@Retry(
name = "paymentRetry",
fallbackMethod = "fallback"
)
public String callService() {
throw new RuntimeException(
"Temporary Failure"
);
}
resilience4j:
retry:
instances:
paymentRetry:
maxAttempts: 3
waitDuration: 2s
Controls the number of requests allowed within a time period.
@RateLimiter(name = "rateLimiterService")
public String getData() {
return "Success";
}
resilience4j:
ratelimiter:
instances:
rateLimiterService:
limitForPeriod: 10
limitRefreshPeriod: 1s
timeoutDuration: 0
Only 10 requests per second are allowed.
Bulkhead isolates resources so one failing component does not consume all available threads.
Inspired by ship compartments:
Ship +-------+ | Room1 | +-------+ | Room2 | +-------+ | Room3 | +-------+ One room floods Ship survives
@Bulkhead(name = "bulkheadService")
public String process() {
return "Processed";
}
resilience4j:
bulkhead:
instances:
bulkheadService:
maxConcurrentCalls: 5
Prevents waiting indefinitely for slow services.
@TimeLimiter(name = "paymentTimeout") public CompletableFuturegetData() { return CompletableFuture.supplyAsync(() -> { Thread.sleep(10000); return "Success"; }); }
resilience4j:
timelimiter:
instances:
paymentTimeout:
timeoutDuration: 3s
Requests taking longer than 3 seconds will fail fast.
Store frequently requested responses to improve performance.
@Cacheable("users")
public User getUser(Long id) {
return repository.findById(id);
}
Client | API Gateway | Microservice | +---- Circuit Breaker | +---- Retry | +---- Rate Limiter | +---- Bulkhead | +---- Time Limiter | External Services / Database
Client | Payment Service | Fraud Detection | External Banking API
Suppose Banking API becomes slow.
| Problem | Resilience4j Solution |
|---|---|
| Payment API Failure | Circuit Breaker |
| Temporary Network Issue | Retry |
| High Traffic | Rate Limiter |
| Slow Fraud Service | Time Limiter |
| Thread Exhaustion | Bulkhead |
| Fallback Balance | Fallback Method |
Client | API Gateway | Payment Service | Fraud Service | +---- Rule Engine +---- Risk Scoring +---- Device Validation +---- Geo Validation +---- Velocity Check +---- ML Models | Approve / Reject / Hold
| Approach | Description |
|---|---|
| Rule-Based | Business Rules |
| ML-Based | Machine Learning Detection |
| Behavior Analysis | User Behavior Patterns |
| Risk Scoring | Fraud Probability Calculation |
| Best Practice | Purpose |
|---|---|
| Async Processing | Reduce latency |
| Kafka Streaming | Real-time fraud analysis |
| Caching | Improve performance |
| Distributed Tracing | Track requests end-to-end |
| Monitoring & Alerts | Detect failures quickly |
| Audit Logging | Compliance and traceability |
| Question | Answer |
|---|---|
| What is Resilience4j? | Lightweight fault-tolerance library for microservices. |
| Why use Resilience4j? | Prevent cascading failures and improve resilience. |
| What is Circuit Breaker? | Stops repeated calls to failing services. |
| What is Retry? | Automatically retries transient failures. |
| What is Bulkhead? | Isolates resources to prevent total failure. |
| What is Rate Limiter? | Controls request rate. |
| What is Time Limiter? | Applies timeout to slow operations. |
| What is Fallback? | Backup response during failures. |
| OPEN State? | Requests blocked. |
| CLOSED State? | Normal operation. |
| HALF_OPEN State? | Testing service recovery. |