@fastify/circuit-breaker

中文文档
4.0.4发布于 2026/10/09MITTypeScriptCommonJS构建来源已验证近 30 天下载 6.9万

A low overhead circuit breaker for your routes

原始使用文档
文档目录8 节
  1. Install
  2. Compatibility
  3. Usage
  4. Options
  5. Customize error messages
  6. Caveats
  7. Acknowledgments
  8. License

@fastify/circuit-breaker

CI NPM version neostandard javascript style

A low overhead circuit breaker for your routes.

Install

npm i @fastify/circuit-breaker

Compatibility

Plugin versionFastify version
>=4.x^5.x
^3.x^4.x
>=1.x <3.x^3.x
^0.x^2.x
^0.x^1.x

Please note that if a Fastify version is out of support, then so are the corresponding versions of this plugin in the table above. See Fastify's LTS policy for more details.

Usage

Register the plugin and, if needed, pass it custom options.
This plugin will add an onSend hook and expose a circuitBreaker utility.
Call fastify.circuitBreaker() when declaring the preHandler option of a route, in this way you will put that very specific route under the circuit breaking check.

const fastify = require('fastify')()

fastify.register(require('@fastify/circuit-breaker'))

fastify.register(function (instance, opts, next) {
  instance.route({
    method: 'GET',
    url: '/',
    schema: {
      querystring: {
        error: { type: 'boolean' },
        delay: { type: 'number' }
      }
    },
    preHandler: instance.circuitBreaker(),
    handler: function (req, reply) {
      setTimeout(() => {
        reply.send(
          req.query.error ? new Error('kaboom') : { hello: 'world' }
        )
      }, req.query.delay || 0)
    }
  })
  next()
})

fastify.listen({ port: 3000 }, err => {
  if (err) throw err
  console.log('Server listening at http://localhost:3000')
})

Options

You can pass the following options during the plugin registration, this way the values will be used in all routes.

fastify.register(require('@fastify/circuit-breaker'), {
  threshold: 3, // default 5
  timeout: 5000, // default 10000
  resetTimeout: 5000, // default 10000
  onCircuitOpen: async (req, reply) => {
    reply.statusCode = 500
    throw new Error('a custom error')
  },
  onTimeout: async (req, reply) => {
    reply.statusCode = 504
    return 'timed out'
  }
})
  • threshold: the maximum number of failures accepted before opening the circuit.
  • timeout: the maximum number of milliseconds you can wait before returning a TimeoutError.
  • resetTimeout: number of milliseconds before the circuit will move from open to half-open
  • onCircuitOpen: async function that gets called when the circuit is open due to errors. It can modify the reply and return a string | Buffer | Stream payload. If an Error is thrown it will be routed to your error handler.
  • onTimeout: async function that gets called when the circuit is open due to timeouts. It can modify the reply and return a string | Buffer | Stream | Error payload. If an Error is thrown it will be routed to your error handler.

Otherwise, you can customize every single route by passing the same options to the circuitBreaker utility:

fastify.circuitBreaker({
  threshold: 3, // default 5
  timeout: 5000, // default 10000
  resetTimeout: 5000 // default 10000
})

If you pass the options directly to the utility, it will take precedence over the global configuration.

Customize error messages

If needed you can change the default error message for the circuit open error and the timeout error:

fastify.register(require('@fastify/circuit-breaker'), {
  timeoutErrorMessage: 'Ronf...', // default 'Timeout'
  circuitOpenErrorMessage: 'Oh gosh!' // default 'Circuit open'
})

Caveats

Since it is not possible to apply the classic timeout feature of the pattern, in this case the timeout will measure the time that the route takes to execute and once the route has finished if the time taken is higher than the timeout it will return an error, even if the route has produced a successful response.

If you need a classic circuit breaker to wrap around an API call consider using easy-breaker.

Acknowledgments

Image courtesy of Martin Fowler.

License

Licensed under MIT.

版本与发布记录

@fastify/circuit-breaker 共发布 11 个版本,首次发布于 2022/04/27;过去 12 个月发布了 2 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
4.0.4latest2026/10/091 个月前
4.0.32026/08/083 个月前
4.0.22025/01/051.9 年前
4.0.12024/09/222 年前
4.0.0next2024/09/062 年前
4.0.0-pre.fv5.22024/08/072 年前

关于 @fastify/circuit-breaker 的常见问题

@fastify/circuit-breaker 是什么?

A low overhead circuit breaker for your routes

如何安装 @fastify/circuit-breaker?

在项目目录运行 npm install @fastify/circuit-breaker,或使用 pnpm add / yarn add / bun add。

@fastify/circuit-breaker 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@fastify/circuit-breaker 支持 ESM 还是 CommonJS?

以 CommonJS 形式发布,可以直接 require();在 ES Module 项目中也可以用 import 引入(Node.js 会把 module.exports 作为默认导出)。

@fastify/circuit-breaker 可以商用吗?

@fastify/circuit-breaker 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@fastify/circuit-breaker 的下载量有多少?

根据 npm 官方下载统计,@fastify/circuit-breaker 在 2026/10/15 – 2026/11/13 这 30 天内被下载 69,244 次,日均约 2,308 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@fastify/circuit-breaker 还在维护吗?

最新版本 4.0.4 发布于 2026/10/09(1 个月前);至今共发布 11 个版本,其中过去 12 个月发布了 2 个;首次发布于 2022/04/27。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。