How @fastify/circuit-breaker works
mainThe plugin implements a circuit breaker pattern for Fastify routes to prevent cascading failures.
To use it:
- Register the plugin: Use
fastify.register(require('@fastify/circuit-breaker'), [options]). This adds anonSendhook and exposes thecircuitBreakerutility. - Apply to routes: Call
instance.circuitBreaker()within thepreHandleroption of a specific route. This places that specific route under the circuit breaking check.
Important Caveat: The timeout mechanism in this plugin measures the time the route takes to execute and checks it after the route has finished. If the execution time exceeds the timeout, it returns an error even if the route produced a successful response. For wrapping external API calls with a classic timeout, consider using easy-breaker instead.
const fastify = require('fastify')()
fastify.register(require('@fastify/circuit-breaker'))
fastify.register(function (instance, opts, next) {
instance.route({
method: 'GET',
url: '/',
preHandler: instance.circuitBreaker(),
handler: function (req, reply) {
// Your route logic here
}
})
next()
})