Home >Web Front-end >JS Tutorial >An in-depth analysis of the circuit breaker mechanism in Node.js
This article will take you through the circuit breaker mechanism in Node.js, I hope it will be helpful to you!
When we use the traditional CS architecture, the server blocks requests due to failures and other reasons, which may cause customers to The client's request loses response, resulting in a group of users being unable to obtain services after a period of time. The possible impact of this situation is limited and can be estimated.
However, in a microservice system, your server may depend on several other microservices, and these microservices depend on more other microservices. In this case, a certain service may cause downstream congestion. , which may cause catastrophic consequences on the entire link due to cascading resource consumption in an instant (within seconds), which we call "service collapse". [Recommended learning: "nodejs Tutorial"]
##Several ways to solve problemsopen circuit state.
half-open state.
closed state. At this time, ServiceA will call ServiceB normally and return the result.
Retry timeout: When the circuit breaker is in the open circuit state, how long does it take to retry the request, that is, enter the half-open state
With this knowledge, We can try to create a circuit breaker:
class CircuitBreaker { constructor(timeout, failureThreshold, retryTimePeriod) { // We start in a closed state hoping that everything is fine this.state = 'CLOSED'; // Number of failures we receive from the depended service before we change the state to 'OPEN' this.failureThreshold = failureThreshold; // Timeout for the API request. this.timeout = timeout; // Time period after which a fresh request be made to the dependent // service to check if service is up. this.retryTimePeriod = retryTimePeriod; this.lastFailureTime = null; this.failureCount = 0; } }
Construct the state machine of the circuit breaker:
async call(urlToCall) { // Determine the current state of the circuit. this.setState(); switch (this.state) { case 'OPEN': // return cached response if no the circuit is in OPEN state return { data: 'this is stale response' }; // Make the API request if the circuit is not OPEN case 'HALF-OPEN': case 'CLOSED': try { const response = await axios({ url: urlToCall, timeout: this.timeout, method: 'get', }); // Yay!! the API responded fine. Lets reset everything. this.reset(); return response; } catch (err) { // Uh-oh!! the call still failed. Lets update that in our records. this.recordFailure(); throw new Error(err); } default: console.log('This state should never be reached'); return 'unexpected state in the state machine'; } }
Supplement the remaining functions:
// reset all the parameters to the initial state when circuit is initialized reset() { this.failureCount = 0; this.lastFailureTime = null; this.state = 'CLOSED'; } // Set the current state of our circuit breaker. setState() { if (this.failureCount > this.failureThreshold) { if ((Date.now() - this.lastFailureTime) > this.retryTimePeriod) { this.state = 'HALF-OPEN'; } else { this.state = 'OPEN'; } } else { this.state = 'CLOSED'; } } recordFailure() { this.failureCount += 1; this.lastFailureTime = Date.now(); }
When using the circuit breaker, you only need to wrap the request Just call it in the Call method in the circuit breaker instance:
... const circuitBreaker = new CircuitBreaker(3000, 5, 2000); const response = await circuitBreaker.call('http://0.0.0.0:8000/flakycall');
Red Hat created a long time ago called Opossum Mature Node.js circuit breaker implementation, the link is here: Opossum. For distributed systems, using this library can greatly improve the fault tolerance of your service and fundamentally solve the problem of service failure.
Original address: https://juejin.cn/post/7019217344601948173
Author: ES2049 / Looking for Singularity
More programming related knowledge , please visit: programming video! !
The above is the detailed content of An in-depth analysis of the circuit breaker mechanism in Node.js. For more information, please follow other related articles on the PHP Chinese website!