Menu

1 / 2

Circuit Breaker Pattern: Fail Fast, Recover Gracefully

DEV Community·Tosh·6 months ago
#2mVlniUH
#patterns#resilience#api#software#circuit
Reading 0:00
15s threshold

Your app calls an external API. The API is down.

Your code: "I'll keep retrying forever."

User: "Your app is frozen."

Circuit breaker prevents this.

The Pattern

Imagine a circuit breaker in your house. When too much current flows, the breaker trips. Cuts the circuit. Prevents fire.

Same idea for APIs.

States:

CLOSED: API works, requests go through

OPEN: API is down, requests fail fast (no retry)

HALF_OPEN: API might be back, try a test request

Flow:

Request → API works → CLOSED (pass through) Request → API fails → count failures Failures > threshold → OPEN (fail fast, no retry) Wait 30 seconds → HALF_OPEN (test request) Test succeeds → CLOSED (back to normal) Test fails → OPEN (not ready yet)

Enter fullscreen mode

Exit fullscreen mode

Why This Matters

Without circuit breaker:

API is down. Code: "Try again" Code: "Try again" Code: "Try again" (30 seconds of retries) User: "Your app is broken"

Enter fullscreen mode

Exit fullscreen mode

With circuit breaker:

API is down.…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.