npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@fastify/circuit-breaker

v3.2.0

Published

A low overhead circuit breaker for your routes

Downloads

2,242

Readme

@fastify/circuit-breaker

CI NPM version js-standard-style

A low overhead circuit breaker for your routes.

Install

npm i @fastify/circuit-breaker

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, in 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: is the maximum number of failures accepted before opening the circuit.
  • timeout: is the maximum number of milliseconds you can wait before return 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.

Acknowledgements

Image curtesy of Martin Fowler.

License

MIT

Copyright © 2018 Tomas Della Vedova