What Is Netflix-hystrix?

Reading Time: 2 minutes
Hystrix logo.

In very simple terms, a circuit breaker is a pattern, and Netflix-hystrix is an implementation of this pattern. This library was designed to control the interactions between distributed services by adding latency tolerance and fault tolerance logic. Hystrix does this by isolating points of access between the services, stopping cascading failures across them, and providing fallback options — all of which improve your system’s overall resiliency.

Let’s implement this ourselves for better understanding and use of netflix-hystrix with a Java Springboot Application.

Here, we have created a sample Hystrix Java service that does the following:

  • Exposes a GET endpoint that provides information about the service.
  • The service internally calls another endpoint to retrieve this information. This is again a rest call.
  • When we hit the service endpoint, the controller will execute this method.

Now, we can see that the method makes a rest call to another service, so we will only be able to receive information if the external service returns List<ServiceInformation>

But, if this rest endpoint is unavailable, we won’t receive any data. This is where we can implement the circuit breaker pattern using the Netflix-hystrix.

The library provides us with a fallback method mechanism, which is a method that will be invoked in case the call to external service fails. The logic to the fallback method will depend on your use case; here, we are just going to log for demo purposes that the service failed and the application moved to a fallback method.

    @HystrixCommand(fallbackMethod = "defaultStatus")
    public List<ServiceInformation> showServiceInformation() {
        List<ServiceInformation> information = restTemplate.exchange(
                "http://localhost:8081", HttpMethod.GET, null, new
                        ParameterizedTypeReference<List<ServiceInformation>>(){}).getBody();
        for(ServiceInformation serviceInformation : information) {
            logger.trace(serviceInformation.getServiceName());
            logger.trace(serviceInformation.getMessage());
        }
        return information;
    }
    
      public List<ServiceInformation> defaultStatus() {
        logger.error("circuit-breaker-proxy is down, running fallback method");
        return Collections.emptyList();
    }

Here, the default status is the fallback method, and the name of this method is passed as a parameter in the @HystrixCommand annotation which will execute the fallback method if the call to external service fails. We can also have fallbacks for the fallback method.

The Annotation can have several more parameters depending on the property you want to provide. For now, we will just look at the fallback method. 

Checkout our other blogs on java and java on Knoldus blogs.

Checkout our templates here.

This image has an empty alt attribute; its file name is footer-2.jpg