Skip to main content

Command Palette

Search for a command to run...

(Resilence4j- Circuit Breaker and retry)

Published
3 min read

What is @CircuitBreaker Annotation?

@CircuitBreaker is used in Spring Boot (with Resilience4j) to stop calling a failing service after a certain number of failures and return a fallback response instead.

It helps in fault tolerance and prevents cascading failures.


✅ Syntax

@CircuitBreaker(name = "serviceName", fallbackMethod = "fallbackMethod")

1️⃣ Simple Example

@Service
public class OrderService {

    @CircuitBreaker(name = "orderCB", fallbackMethod = "orderFallback")
    public String placeOrder() {
        // external service call
        throw new RuntimeException("Service down");
    }

    public String orderFallback(Exception ex) {
        return "Order service is temporarily unavailable";
    }
}

2️⃣ How Annotation Works Internally

  • Spring AOP proxy intercepts the method call

  • Resilience4j tracks:

    • failures

    • slow calls

    • success rate

  • Based on config, circuit moves between:

    • Closed

    • Open

    • Half-Open


3️⃣ Configuration (application.yml)

resilience4j:
  circuitbreaker:
    instances:
      orderCB:
        failureRateThreshold: 50
        minimumNumberOfCalls: 5
        slidingWindowSize: 10
        waitDurationInOpenState: 10s
        permittedNumberOfCallsInHalfOpenState: 2

4️⃣ Circuit States with Annotation

StateBehavior
ClosedMethod executes normally
OpenMethod NOT executed, fallback called
Half-OpenLimited calls allowed for testing

5️⃣ Fallback Method Rules ❗ (Very Important)

✔ Same return type
✔ Same class
✔ Last parameter must be Exception or Throwable

Valid:

public String orderFallback(Exception ex)

Invalid ❌:

public void orderFallback()

1️⃣ Closed → Open

  • Failure threshold is reached

  • Circuit goes to OPEN

  • Message to callers:

    ❌ “Don’t call me now — service is down”

  • All requests go directly to fallback


2️⃣ Open State (Wait period)

  • Circuit stays OPEN for 5 seconds
    (waitDurationInOpenState = 5s)

  • No real calls allowed

  • Fallback is always returned


3️⃣ Open → Half-Open

  • After 5 seconds, circuit moves to HALF-OPEN

  • Circuit says:

    🧪 “Service might be up now — you can try”


4️⃣ Half-Open State (Test calls)

  • Allows 2 real calls
    (permittedNumberOfCallsInHalfOpenState = 2)

  • These calls hit the actual service

Outcomes:

  • If even 1 call fails

    • Circuit → OPEN again

    • Wait another 5 seconds

  • If both calls succeed

    • Circuit → CLOSED

    • Normal traffic resumes


🔁 Final Flow Diagram

CLOSED
  ↓ (failures exceed threshold)
OPEN (wait 5 sec, fallback only)
  ↓
HALF-OPEN (allow 2 test calls)
  ↓
❌ fail → OPEN again
✅ success → CLOSED

Retry Mechanism (Resilence4j)

@Retry automatically retries a failed method call a fixed number of times before giving up.

It is used when:

  • Failures are temporary (network glitch, timeout)

  • Service is likely to recover quickly


✅ Syntax

@Retry(name = "serviceRetry", fallbackMethod = "fallbackMethod")

1️⃣ Simple Example

@Service
public class InventoryService {

    @Retry(name = "inventoryRetry", fallbackMethod = "inventoryFallback")
    public String checkStock() {
        System.out.println("Calling inventory service...");
        throw new RuntimeException("Temporary failure");
    }

    public String inventoryFallback(Exception ex) {
        return "Inventory service unavailable after retries";
    }
}

2️⃣ Retry Configuration (application.yml)

resilience4j:
  retry:
    instances:
      inventoryRetry:
        maxAttempts: 3
        waitDuration: 2s

Meaning:

  • maxAttempts: 3 → 1 original + 2 retries

  • waitDuration: 2s → wait between retries


3️⃣ How Retry Works (Flow)

Call 1 → fail
   ↓
Retry 1 → fail
   ↓
Retry 2 → fail
   ↓
Fallback method called

4️⃣ Retry vs Circuit Breaker (Very Important)

Feature@Retry@CircuitBreaker
PurposeTry againStop calling
When usedTemporary issuesContinuous failures
Calls service again✅ Yes❌ No (Open state)
RiskCan overload serviceProtects system