This article will take you through the circuit breaker mechanism in Node.js, I hope it will be helpful to you!
Problems caused by architecture evolution
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"]
- Fuse mode: As the name suggests, just like household circuits, if the voltage of a line is too high, the fuse will blow to prevent fire. In a system using the circuit breaker mode, if it is found that the upstream service call is slow or there are a large number of timeouts, the call to the service will be directly terminated, information will be returned directly, and resources will be released quickly. The call will not be resumed until the upstream service improves. Isolation mode: Divide calls for different resources or services into several different request pools. Exhaustion of resources in one pool will not affect requests for other resources, preventing a single point. The failure consumes all resources. This is a very traditional disaster recovery design.
- Current limiting mode: Circuit breaker and isolation are both post-processing methods. Current limiting mode can reduce the probability of problems before they occur. The current limiting mode can set a maximum QPS threshold for requests for certain services. Requests that exceed the threshold are returned directly and no longer occupy resources for processing. However, the current limiting mode cannot solve the problem of service collapse, because the collapse is often caused not by the large number of requests, but by the amplification of multiple cascade layers.
- After the number of failures reaches a certain threshold, the circuit breaker will find that the request to ServiceB is invalid. At this time, ServiceA does not need to continue to request ServiceB, but directly returns failure, or Use backup data from other Fallbacks. At this time, the circuit breaker is in the
open circuit state.
- After a period of time, the circuit breaker will start to periodically query whether ServiceB has been restored. At this time, the circuit breaker is in the
half-open state.
- If ServiceB has recovered, the circuit breaker will be placed in the
closed state. At this time, ServiceA will call ServiceB normally and return the result.
- Timeout: how long the request reaches before it causes a failure
- Failure threshold: that is, the circuit breaker triggers an open circuit Before, the number of failures required
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');
Mature Node.js circuit breaker library
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!

Vercel是什么?本篇文章带大家了解一下Vercel,并介绍一下在Vercel中部署 Node 服务的方法,希望对大家有所帮助!

gm是基于node.js的图片处理插件,它封装了图片处理工具GraphicsMagick(GM)和ImageMagick(IM),可使用spawn的方式调用。gm插件不是node默认安装的,需执行“npm install gm -S”进行安装才可使用。

本篇文章带大家详解package.json和package-lock.json文件,希望对大家有所帮助!

如何用pkg打包nodejs可执行文件?下面本篇文章给大家介绍一下使用pkg将Node.js项目打包为可执行文件的方法,希望对大家有所帮助!

本篇文章给大家分享一个Nodejs web框架:Fastify,简单介绍一下Fastify支持的特性、Fastify支持的插件以及Fastify的使用方法,希望对大家有所帮助!

node怎么爬取数据?下面本篇文章给大家分享一个node爬虫实例,聊聊利用node抓取小说章节的方法,希望对大家有所帮助!

本篇文章给大家分享一个Node实战,介绍一下使用Node.js和adb怎么开发一个手机备份小工具,希望对大家有所帮助!

先介绍node.js的安装,再介绍使用node.js构建一个简单的web服务器,最后通过一个简单的示例,演示网页与服务器之间的数据交互的实现。


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Dreamweaver CS6
Visual web development tools

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

Dreamweaver Mac version
Visual web development tools