Chapter 3. Example application using the circuit breaker add-on
You can use the circuit breaker add-on to implement a circuit breaker pattern in your Node.js applications. This example shows how to use the circuit breaker add-on to report the failure of a remote service and to limit access to the failed service until it becomes available to handle requests.
3.1. Overview of the example application Copy linkLink copied to clipboard!
This example application consists of two microservices:
- greeting-service
-
This is the entry point to the application. A web client calls
greeting-serviceto request a greeting.greeting-servicethen sends a request that is wrapped in a circuit breaker object to the remotename-service. - name-service
-
name-servicereceives the request fromgreeting-service. The web client interface contains a toggle button that you can click to simulate the availability or failure of the remotename-service. If the toggle button is currently set toon,name-servicesends a response to complete the greeting. However, if the toggle button is currently set tooff,name-servicesends an error to indicate that the service is currently unavailable.
3.2. Example greeting-service Copy linkLink copied to clipboard!
greeting-service imports the circuit breaker add-on. greeting-service protects calls to the remote name-service by wrapping these calls in a circuit breaker object.
greeting-service exposes the following endpoints:
-
The
/api/greetingendpoint receives a call from the web client that requests a greeting. The/api/greetingendpoint sends a call to the/api/nameendpoint in the remotename-serviceas part of processing the client request. The call to the/api/nameendpoint is wrapped in a circuit breaker object. If the remotename-serviceis currently available, the/api/greetingendpoint sends a greeting to the client. However, if the remotename-serviceis currently unavailable, the/api/greetingendpoint sends an error response to the client. -
The
/api/cb-stateendpoint returns the current state of the circuit breaker. If this is set toopen, the circuit breaker is currently preventing requests from reaching the failed service. If this is set toclosed, the circuit breaker is currently allowing requests to reach the service.
The following code example shows how to develop greeting-service:
3.3. Example name-service Copy linkLink copied to clipboard!
name-service exposes the following endpoints:
-
The
/api/nameendpoint receives a call fromgreeting-service. Ifname-serviceis currently available, the/api/nameendpoint sends aWorld!response to complete the greeting. However, ifname-serviceis currently unavailable, the/api/nameendpoint sends aName service downerror with an HTTP status code of500. -
The
/api/stateendpoint controls the current behavior of the/api/nameendpoint. It determines whether the service sends a response or fails with an error message.
The following code example shows how to develop name-service: