Fault Tolerance with Hystrix
Microservices must be extremely reliable because they depend on each other. The microservice architecture contains a large number of small microservices. These microservices communicate with each other in order to fulfill their requirements.
The instances of microservices may go up and down frequently. As the number of interactions between microservices increases, the chances of failure of the microservice also increases in the system.
Consider a scenario in which six microservices are communicating with each other. The microservice-5 becomes down at some point, and all the other microservices are directly or indirectly depend on it, so all other services also go down.
The solution to this problem is to use a fallback in case of failure of a microservice. This aspect of a microservice is called fault tolerance.
Fault tolerance can be achieved with the help of a circuit breaker. It is a pattern that wraps requests to external services and detects when they fail. If a failure is detected, the circuit breaker opens. All the subsequent requests immediately return an error instead of making requests to the unhealthy service. It monitors and detects the service which is down and misbehaves with other services. It rejects calls until it becomes healthy again.
Hystrix is a library that controls the interaction between microservices to provide latency and fault tolerance. Additionally, it makes sense to modify the UI to let the user know that something might not have worked as expected or would take more time.
Implementing Fault Tolerance with Hystrix
Step 1: Open the pom.xml file of limits-service and add the Hystrix dependency
Step 2: Open LimitsServicesApplication.java file and enable Hystrix by using the annotation @EnableHystrix.
Step 3: Open the LimitsConfigurationController.java file and create a Get method.
Let’s understand what is happening in the above method.
In the above method, we have created a Get mapping for fault tolerance. In the next line, we have used an annotation @HystrixCommand to configure the fallback method. We have defined a method with the name fallbackRetrieveConfigurations() that returns the default value if any fault occurs.
The fallback method is a method that invokes when a fault occurs. Hystrix allows us to define a fallback method for each service method. Here one question arises that if the method throws an exception, what should be returned to the consumer?
So answer is that if retrieveConfiguraions() fails, the method fallbackRetrieveConfigurations() is called. The fallback method returns the hardcoded LimitConfiguration instance.
Step 4: Open the browser and invoke the URL http://localhost:8080/fault-tolerance-example. It returns the values that we have returned in the fallbackRetrieveConfigurations() method.