Cloud Native 11 min read

Microservices Practice: Hystrix Circuit Breaking and Fallback – Step-by-Step Guide

This article explains the role of Hystrix as a circuit‑breaker in Spring Cloud microservices, describes why service failures can cascade, and provides a detailed, hands‑on implementation—including Maven dependencies, annotations, fallback methods, configuration of circuit thresholds, and integration with Ribbon and Feign – complete with code snippets and test steps.

Pan Zhi's Tech Notes
Pan Zhi's Tech Notes
Pan Zhi's Tech Notes
Microservices Practice: Hystrix Circuit Breaking and Fallback – Step-by-Step Guide

Background

Feign simplifies HTTP client development in Spring Cloud. This article extends the discussion to another core component, Hystrix.

Hystrix Overview

Spring Cloud Hystrix is a Netflix‑originated circuit‑breaker library that isolates potentially failing remote service calls to prevent system‑wide crashes. In a typical microservice call chain, if a downstream service becomes overloaded or unavailable, all callers receive exceptions, potentially causing cascading failures.

Hystrix works like an electrical circuit‑breaker: when the failure rate of a remote call exceeds a configured threshold, the circuit opens, blocking further calls to the downstream service. After a cooldown period, the circuit closes and calls resume.

Implementation with Ribbon

3.1 Hystrix usage example

3.1.1 Create service consumer

Copy the existing eureka-consumer-ribbon project and rename it eureka-consumer-ribbon-hystrix. Add the Hystrix starter dependency to pom.xml:

<dependency>
  <groupId>org.springframework.cloud</groupId>
  <artifactId>spring-cloud-starter-hystrix</artifactId>
</dependency>

3.1.2 Enable Hystrix scanning

Create the main application class and add @EnableCircuitBreaker (or @EnableHystrix) to activate Hystrix:

@EnableCircuitBreaker
@EnableDiscoveryClient
@SpringBootApplication
public class Application {
    @Bean
    @LoadBalanced
    public RestTemplate restTemplate() {
        return new RestTemplate();
    }
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

3.1.3 Write fallback method

Define a remote‑call service RpcService and annotate the method with @HystrixCommand, specifying a fallback method:

@Service
public class RpcService {
    @Autowired
    private RestTemplate restTemplate;

    @HystrixCommand(fallbackMethod = "fallback")
    public String hello() {
        String url = "http://eureka-provider/hello";
        return restTemplate.getForObject(url, String.class);
    }

    public String fallback() {
        return "Remote call failed, service automatically circuit‑breaks";
    }
}

3.1.4 Create controller

Expose an endpoint that triggers the remote call:

@RestController
public class HelloController {
    @Autowired
    private RpcService rpcService;

    @GetMapping("/rpc")
    public String rpc() {
        return "Remote call result: " + rpcService.hello();
    }
}

3.1.5 Service testing

Start eureka-server, eureka-provider, and eureka-consumer-ribbon-hystrix. Access /rpc in a browser. While the call is running, stop eureka-provider. The response shows that the circuit opened and the fallback method executed.

3.1.6 Circuit‑breaker threshold configuration

Default: if a protected method is called more than 20 times within 10 seconds and the failure rate exceeds 50 %, the circuit opens. After 5 seconds the circuit enters a half‑open state and retries the original method; a successful call closes the circuit.

Custom thresholds can be set via @HystrixProperty:

@HystrixCommand(fallbackMethod = "fallback", commandProperties = {
    @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold", value = "30"),
    @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage", value = "30"),
    @HystrixProperty(name = "metrics.rollingStats.timeInMilliseconds", value = "20000"),
    @HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds", value = "60000")
})
public String hello() { /* same implementation as above */ }

Feign integration with Hystrix

3.2 Feign usage example

Copy the eureka-consumer-feign project to eureka-consumer-feign-hystrix and keep the same dependencies.

3.2.1 Enable Hystrix in properties

# Enable Hystrix for Feign
feign.hystrix.enabled=true

3.2.2 Write fallback class

@Component
public class RpcServiceHystrix implements RpcService {
    @Override
    public String findByName(@RequestParam(value = "name") String name) {
        return "Request failed, service degraded, param: " + name;
    }
}

3.2.3 Specify fallback in @FeignClient

@FeignClient(name = "eureka-provider", fallback = RpcServiceHystrix.class)
public interface RpcService {
    @RequestMapping(value = "/findByName")
    String findByName(@RequestParam(value = "name") String name);
}

3.2.4 Create controller for Feign call

@RestController
public class HelloController {
    @Autowired
    private RpcService rpcService;

    @GetMapping("/rpc")
    public String rpc(@RequestParam(value = "name") String name) {
        return "Feign call (with Hystrix) result: " + rpcService.findByName(name);
    }
}

3.2.5 Service testing

Start eureka-server, eureka-provider, and eureka-consumer-feign-hystrix. Access /rpc. Stopping eureka-provider during the request triggers the fallback method, confirming identical Hystrix behavior with Feign.

Conclusion

In microservice architectures, complex service dependencies mean a single failure can cascade and crash the whole system. Hystrix provides circuit‑breaker, fallback, request caching, request merging, thread isolation, and automatic rollback capabilities. Although Netflix has stopped maintaining Hystrix, it remains a valuable learning tool for understanding distributed system resilience.

References

http://www.ityouknow.com/springcloud/2017/05/16/springcloud-hystrix.html

https://www.didispace.com/spring-cloud/springcloud3.html#netflix-hystrix

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

microservicesFeignSpring CloudCircuit BreakerHystrixRibbon
Pan Zhi's Tech Notes
Written by

Pan Zhi's Tech Notes

Sharing frontline internet R&D technology, dedicated to premium original content.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.