@fastify/circuit-breaker

Fail Fast When Downstream Is Sick

@fastify/circuit-breaker

Wrap routes that call flaky downstream services with a circuit breaker. It opens after repeated failures and half-opens after a cool-down to test recovery.

4 min read Level 3/5 #fastify#resilience#circuit-breaker
What you'll learn
  • Install @fastify/circuit-breaker
  • Apply the breaker as an onRequest hook
  • Tune failureThreshold and resetTimeout

When a downstream dependency starts failing, the dumb-but-effective thing to do is stop calling it for a while. A circuit breaker tracks failures and “opens” — short-circuits — when the count crosses a threshold.

Install & Register

npm install @fastify/circuit-breaker
import circuitBreaker from '@fastify/circuit-breaker'

await app.register(circuitBreaker, {
  threshold: 5,
  timeout: 10000,
  resetTimeout: 10000,
})
  • threshold: failures (or timeouts) before the breaker opens.
  • timeout: per-request budget; exceeded calls count as failures.
  • resetTimeout: how long it stays open before allowing a test call (half-open).

Per-Route Breaker

Apply the breaker only to the routes that call the flaky service.

app.route({
  method: 'GET',
  url: '/quote',
  preHandler: app.circuitBreaker(),
  handler: async () => {
    const res = await fetch('https://flaky.example.com/quote')
    return res.json()
  },
})

When the breaker is open the handler is skipped and the request fails fast with 503 — protecting both you and the upstream from a thundering herd.

When to Use It

Use breakers on cross-boundary calls: third-party APIs, slow internal services, external databases when there’s a meaningful fallback. Combine with retries (with exponential backoff and jitter) and a sensible client timeout for a complete resilience stack.

@fastify/caching →