codingstuff.io
ExploreTutorialsProblemsCS Subjects
Get Started
ExploreTutorialsProblemsCS Subjects
Get Started
codingstuff.io

Master the art of building software through interactive tutorials, real-world problems, and guided projects.

Pune, Maharashtra, India

codingstuffmail@gmail.com

Product

  • Explore
  • Tutorials
  • Problems
  • CS Subjects

Company

  • About
  • Contact
  • Privacy Policy
  • Terms & Conditions
  • Sitemap

© 2026 codingstuff.io. All rights reserved.

Built with ❤️ for developers everywhere

/
/
All Tutorials
🍃

Spring Boot

39 / 62 topics
35Microservices Basics with Spring Boot36Service Discovery with Eureka37API Gateway with Zuul38Spring Cloud Config Server39Circuit Breaker Pattern with Hystrix
Tutorials/Spring Boot/Circuit Breaker Pattern with Hystrix
🍃Spring Boot

Circuit Breaker Pattern with Hystrix

Updated 2026-05-15
10 min read

Circuit Breaker Pattern with Hystrix

Introduction

In the realm of microservices architecture, services often depend on each other to function. However, network issues or failures in dependent services can lead to cascading failures, affecting the entire system's stability. The Circuit Breaker Pattern is a design pattern used to prevent such scenarios by isolating failed or slow services and redirecting traffic away from them until they recover.

Netflix Hystrix is an open-source library that implements the Circuit Breaker Pattern among other resilience patterns like Bulkhead, Fallback, and Isolation. It helps in building fault-tolerant systems by managing failures gracefully and preventing cascading errors.

Concept

The Circuit Breaker pattern operates on a simple state machine with three states:

  1. Closed State: The circuit is closed, allowing requests to pass through. If the request fails or times out, it increments a failure counter.
  2. Open State: When the failure threshold is reached, the circuit opens, and all requests are redirected to a fallback mechanism. This prevents further failures from overwhelming the system.
  3. Half-Open State: After a specified timeout period, the circuit enters the half-open state where a limited number of requests are allowed through. If these requests succeed, the circuit closes; otherwise, it reopens.

Examples

Setting Up Hystrix in Spring Boot

To use Hystrix in a Spring Boot application, you need to add the necessary dependencies and configure your services.

Step 1: Add Dependencies

First, include the Hystrix dependency in your pom.xml if you're using Maven:

XML
1<dependency>
2 <groupId>org.springframework.cloud</groupId>
3 <artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
4</dependency>

Or, if you're using Gradle, add the following to your build.gradle:

groovy
1implementation 'org.springframework.cloud:spring-cloud-starter-netflix-hystrix'

Step 2: Enable Hystrix

Enable Hystrix in your Spring Boot application by adding the @EnableHystrix annotation to your main class or a configuration class:

Java
1import org.springframework.boot.SpringApplication;
2import org.springframework.boot.autoconfigure.SpringBootApplication;
3import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker;
4
5@SpringBootApplication
6@EnableCircuitBreaker
7public class HystrixApplication {
8 public static void main(String[] args) {
9 SpringApplication.run(HystrixApplication.class, args);
10 }
11}

Step 3: Implement a Circuit Breaker

Now, let's create a service that uses Hystrix to implement the Circuit Breaker pattern. Suppose you have a UserService that calls an external API:

Java
1import org.springframework.beans.factory.annotation.Autowired;
2import org.springframework.stereotype.Service;
3import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
4
5@Service
6public class UserService {
7
8 @Autowired
9 private UserClient userClient;
10
11 @HystrixCommand(fallbackMethod = "fallbackGetUser")
12 public String getUser(String userId) {
13 return userClient.getUser(userId);
14 }
15
16 public String fallbackGetUser(String userId) {
17 return "Fallback: Unable to fetch user details.";
18 }
19}

In this example, the getUser method is annotated with @HystrixCommand, which wraps the call to userClient.getUser. If the call fails or times out, it invokes the fallbackGetUser method.

Testing Hystrix

To test the Circuit Breaker functionality, you can simulate failures in the external API. For instance, if the UserClient throws an exception or returns a timeout error, the circuit breaker should open and redirect traffic to the fallback method.

Step 4: Simulate Failure

Modify the getUser method in UserClient to throw an exception:

Java
1import org.springframework.stereotype.Component;
2import java.util.concurrent.TimeoutException;
3
4@Component
5public class UserClient {
6
7 public String getUser(String userId) throws TimeoutException {
8 // Simulate a timeout or failure
9 throw new TimeoutException("Simulated timeout");
10 }
11}

Step 5: Run the Application

Run your Spring Boot application and make a request to the getUser method. You should see that it falls back to the fallbackGetUser method, returning the fallback message.

Output
Fallback: Unable to fetch user details.

What's Next?

Now that you have implemented the Circuit Breaker Pattern using Hystrix in your Spring Boot application, you can explore more advanced features and patterns such as Bulkhead, Fallback strategies, and monitoring. Additionally, learning about Testing Basics in Spring Boot will help you ensure the reliability of your microservices architecture.

By mastering these concepts, you'll be well-equipped to build robust and resilient microservices that can handle failures gracefully and maintain high availability.


PreviousSpring Cloud Config ServerNext Testing Basics in Spring Boot

Recommended Gear

Spring Cloud Config ServerTesting Basics in Spring Boot