search
HomeWeb Front-endJS TutorialAn 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!

An in-depth analysis of the circuit breaker mechanism in Node.js

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"]

An in-depth analysis of the circuit breaker mechanism in Node.js

An in-depth analysis of the circuit breaker mechanism in Node.js

##Several ways to solve problems

  • 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.
The mechanism and implementation of the circuit breaker

The existence of the circuit breaker is equivalent to giving us a layer of protection. When the call stability is poor, or the call is likely to fail, For services and resources, circuit breakers can monitor these errors and fail requests after reaching a certain threshold to prevent excessive consumption of resources. In addition, the circuit breaker also has the function of automatically identifying the service status and restoring it. When the upstream service returns to normal, the circuit breaker can automatically determine and resume normal requests.

Let us take a look at a request process without a circuit breaker: The user relies on ServiceA to provide services, and ServiceA relies on the services provided by ServiceB. Assume that ServiceB fails at this time. Within 10 minutes, for each request There will be a 10 second delay in response.

An in-depth analysis of the circuit breaker mechanism in Node.js

So suppose we have N Users requesting the service of ServiceA. Within a few seconds, the resources of ServiceA will be consumed because the request to ServiceB is suspended. Empty, thereby rejecting any subsequent requests from the User. For users, this means that both ServiceA and ServiceB failed at the same time, causing the entire service link to collapse.

And what happens when we install a circuit breaker on ServiceA?

  • 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.

An in-depth analysis of the circuit breaker mechanism in Node.js

The status diagram of the circuit breaker is as follows:

An in-depth analysis of the circuit breaker mechanism in Node.js

It can be seen that the circuit breaker Several core points are as follows:

  • 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!

Statement
This article is reproduced at:掘金社区. If there is any infringement, please contact admin@php.cn delete
Vercel是什么?怎么部署Node服务?Vercel是什么?怎么部署Node服务?May 07, 2022 pm 09:34 PM

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

node.js gm是什么node.js gm是什么Jul 12, 2022 pm 06:28 PM

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

一文解析package.json和package-lock.json一文解析package.json和package-lock.jsonSep 01, 2022 pm 08:02 PM

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

怎么使用pkg将Node.js项目打包为可执行文件?怎么使用pkg将Node.js项目打包为可执行文件?Jul 26, 2022 pm 07:33 PM

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

分享一个Nodejs web框架:Fastify分享一个Nodejs web框架:FastifyAug 04, 2022 pm 09:23 PM

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

node爬取数据实例:聊聊怎么抓取小说章节node爬取数据实例:聊聊怎么抓取小说章节May 02, 2022 am 10:00 AM

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

手把手带你使用Node.js和adb开发一个手机备份小工具手把手带你使用Node.js和adb开发一个手机备份小工具Apr 14, 2022 pm 09:06 PM

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

图文详解node.js如何构建web服务器图文详解node.js如何构建web服务器Aug 08, 2022 am 10:27 AM

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

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

mPDF

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

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools