Full Stack • Java • System Design • Cloud • AI Engineering

Circuit Breaker Pattern in Java Microservices

Learn Circuit Breaker Pattern in Java with Resilience4j, Spring Boot, fallback mechanisms, Open-Closed-Half Open states, microservices resilience, enterprise architecture, and interview questions.

What You Will Learn

  • What is Circuit Breaker?
  • Why Circuit Breaker is Needed
  • Failure Cascading Problem
  • Circuit Breaker States
  • Open State
  • Closed State
  • Half Open State
  • Resilience4j Implementation
  • Fallback Mechanisms
  • Banking Examples
  • Enterprise Use Cases
  • Interview Questions

Introduction

Modern Microservices communicate constantly.

Example:

Order Service

↓

Payment Service

↓

Inventory Service

↓

Notification Service

What happens if:

Payment Service Down

Without protection:

Order Service Continues Calling

Payment Service

Again

Again

Again

Result:

Timeouts

Thread Exhaustion

Application Crash

Cascading Failure

Circuit Breaker solves this problem.


What is Circuit Breaker?

Circuit Breaker is a resilience pattern that prevents repeated calls to a failing service.

Inspired by:

Electrical Circuit Breaker

When failures exceed a threshold:

Circuit Opens

↓

Traffic Stops

↓

Service Gets Time To Recover

Purpose of Circuit Breaker

Primary Goal:

Prevent Cascading Failures

and

Improve System Resilience

Real World Analogy

Home Electricity:

Normal:

Current Flows

Power Surge:

Circuit Breaker Trips

Electricity Stops:

Prevent Damage

Same concept in software.


Problem Without Circuit Breaker

flowchart LR

A[Order Service]

B[Payment Service Down]

A --> B

A --> B

A --> B

A --> B

A --> B

Requests continue endlessly.


Cascading Failure

One service fails.

Then:

Thread Pool Exhausted

Connection Pool Exhausted

CPU Increases

Entire System Slows Down

Cascading Failure Flow

flowchart LR

A[Payment Service Down]

B[Order Service Waiting]

C[Thread Exhaustion]

D[System Failure]

A --> B
B --> C
C --> D

Circuit Breaker Solution

flowchart LR

A[Order Service]

B[Circuit Breaker]

C[Payment Service]

A --> B
B --> C

Circuit Breaker sits between services.


Core Idea

Monitor:

Failures

Timeouts

Slow Calls

If threshold exceeded:

Open Circuit

Circuit Breaker States

There are three states:

Closed

Open

Half Open

State Transition

flowchart LR

A[Closed]

B[Open]

C[Half Open]

A --> B

B --> C

C --> A

Closed State

Normal operation.

Requests allowed.

Success → Continue

Failure → Count Error

Closed State Flow

flowchart LR

A[Request]

B[Circuit Closed]

C[Remote Service]

A --> B
B --> C

Open State

Failure threshold reached.

Requests blocked immediately.

No Remote Calls

Open State Flow

flowchart LR

A[Request]

B[Open Circuit]

C[Fallback]

A --> B
B --> C

Half Open State

After waiting period:

Allow Few Requests

to test recovery.


Half Open Flow

flowchart LR

A[Test Request]

B[Half Open]

C[Service]

A --> B
B --> C

State Behavior Summary

State Behavior
Closed Normal Calls
Open Block Calls
Half Open Test Recovery

Example Scenario

Payment Service:

Failure Rate > 50%

Circuit opens.

Next requests:

Do Not Call Payment Service

Return:

Fallback Response

Circuit Breaker Workflow

flowchart LR

A[Client]

B[Order Service]

C[Circuit Breaker]

D[Payment Service]

A --> B
B --> C
C --> D

Fallback Mechanism

Instead of failure:

Return:

Cached Data

Default Response

Temporary Message

Fallback Example

Payment Service Unavailable

Please Try Again Later

instead of:

500 Internal Server Error

Banking Example

Fund Transfer Flow:

Transfer Service

↓

Fraud Service

↓

Payment Service

Banking Failure Scenario

Fraud Service Down.

Without Circuit Breaker:

Transfer Requests Hang

With Circuit Breaker:

Fallback Activated

Banking Architecture

flowchart LR

A[Transfer Service]

B[Circuit Breaker]

C[Fraud Service]

A --> B
B --> C

Insurance Example

Claim Processing:

Claim Service

↓

Policy Service

↓

Fraud Service

Insurance Failure Flow

flowchart LR

A[Claim Service]

B[Circuit Breaker]

C[Policy Service]

A --> B
B --> C

E-Commerce Example

Order Placement:

Order Service

↓

Inventory Service

↓

Payment Service

Retail Architecture

flowchart LR

A[Order Service]

B[Circuit Breaker]

C[Inventory Service]

A --> B
B --> C

Spring Boot Implementation

Dependency:

<dependency>
 <groupId>
   io.github.resilience4j
 </groupId>
 <artifactId>
   resilience4j-spring-boot3
 </artifactId>
</dependency>

Basic Example

@Service
public class PaymentService {

    @CircuitBreaker(
        name = "paymentService",
        fallbackMethod = "fallback"
    )
    public String processPayment() {

        return restTemplate.getForObject(
            "http://payment-service/pay",
            String.class
        );
    }

    public String fallback(
            Exception ex) {

        return "Payment Service Unavailable";
    }
}

Execution Flow

sequenceDiagram

OrderService->>CircuitBreaker: Request

CircuitBreaker->>PaymentService: Call

PaymentService-->>CircuitBreaker: Failure

CircuitBreaker-->>OrderService: Fallback

Resilience4j Configuration

resilience4j:
  circuitbreaker:
    instances:
      paymentService:
        failureRateThreshold: 50
        waitDurationInOpenState: 30s
        slidingWindowSize: 10

Important Parameters

failureRateThreshold

Maximum Failure Percentage

Example:

50%

waitDurationInOpenState

Time Before Half Open

Example:

30 Seconds

slidingWindowSize

Number Of Requests

Used For Evaluation

Circuit Breaker + Retry

Common combination:

Retry First

Circuit Breaker Second

Retry Flow

flowchart LR

A[Request]

B[Retry]

C[Circuit Breaker]

D[Service]

A --> B
B --> C
C --> D

Circuit Breaker + Bulkhead

Bulkhead isolates failures.

Together:

Bulkhead

+

Circuit Breaker

=

High Resilience

Netflix Hystrix

Older implementation:

Netflix Hystrix

Status:

Maintenance Mode

Today use:

Resilience4j

Enterprise Use Cases

Banking

Fund Transfers

Fraud Detection

Payment Processing

Insurance

Claim Processing

Policy Verification

Retail

Order Management

Inventory Systems

Healthcare

Patient Services

Insurance Validation

Travel

Flight Booking

Hotel Booking

Payment Systems

Circuit Breaker vs Retry

Feature Retry Circuit Breaker
Purpose Retry Failures Stop Failures
Calls Remote Service Yes No
Prevent Cascading Failure No Yes

Circuit Breaker vs Timeout

Feature Timeout Circuit Breaker
Stops Waiting Yes Yes
Blocks Future Calls No Yes
Tracks Failure Rate No Yes

Real Enterprise Architecture

flowchart LR

A[Client]

B[API Gateway]

C[Order Service]

D[Circuit Breaker]

E[Payment Service]

A --> B

B --> C

C --> D

D --> E

Benefits

✅ Prevents Cascading Failures

✅ Improves Availability

✅ Protects Resources

✅ Faster Failure Detection

✅ Better User Experience

✅ Cloud Native Friendly


Limitations

❌ Additional Complexity

❌ Requires Monitoring

❌ Incorrect Configuration Causes Issues


When To Use Circuit Breaker

Use when:

Remote Service Calls

Microservices

External APIs

Cloud Native Applications

When NOT To Use

Avoid when:

Standalone Applications

No Network Calls

Simple Utilities

Interview Questions

What is Circuit Breaker?

A pattern that prevents repeated calls to failing services.


Why Use Circuit Breaker?

To prevent cascading failures.


Three States?

Closed

Open

Half Open

What Happens In Open State?

Requests are blocked.

Fallback is returned.


Popular Java Library?

Resilience4j

Hystrix Alternative?

Resilience4j

Biggest Benefit?

Improved system resilience.


Biggest Drawback?

Additional complexity.


Key Takeaways

  • Circuit Breaker prevents cascading failures.
  • Inspired by electrical circuit breakers.
  • Has three states: Closed, Open, and Half Open.
  • Commonly implemented using Resilience4j.
  • Works well with Retry, Bulkhead, and Timeout patterns.
  • Essential for Microservices and Cloud Native Architectures.
  • Widely used in Banking, Insurance, Retail, Healthcare, and Enterprise Systems.