Spring Boot Tutorial 0/110 lessons ~6 min read Lesson 71

    Circuit Breaker

    When inventory or pricing is failing, endless retries from Orders make outages worse.

    Course progress0%
    Focus
    12 guided sections
    Practice signal
    Examples included
    Career prep
    Interview Q&A included

    Introduction

    When inventory or pricing is failing, endless retries from Orders make outages worse. A circuit breaker tracks failures, opens after a threshold, fails fast for a cool-down, then probes half-open — protecting both sides.

    On Boot 3, use Resilience4j (resilience4j-spring-boot3). Netflix Hystrix is retired. Pair circuit breakers with timeouts, bulkheads, and careful retries (idempotent operations only).

    Fallbacks must be safe: cached quotes, degraded UX, or clear errors — never silently charge the wrong price.

    This lesson hardens TechLearningPRO Orders against cascading failure.

    Purpose of this lesson

    Apply Resilience4j circuit breakers, timeouts, and fallbacks on Orders outbound calls.

    Understanding the topic

    Closed → Open → Half-open — stop calling a sick dependency.

    • Closed: calls flow; failures counted in a sliding window.
    • Open: fail fast; run fallback; cool down.
    • Half-open: allow trial calls; succeed → close, fail → open.
    • Resilience4j: annotations or operators; Boot 3 starter.
    • Compose: TimeLimiter + CircuitBreaker + Retry (order matters).

    Step-by-step explanation

    1. Add resilience4j-spring-boot3 and configure an instance for pricing.
    2. Annotate the pricing facade with @CircuitBreaker and a fallback method.
    3. Add a time limiter so calls cannot hang forever.
    4. Chaos-test by pausing pricing and confirming Orders stays responsive.

    Informative example

    Resilience4j on an Orders pricing facade.

    java
    # application.yml
    resilience4j:
    circuitbreaker:
    instances:
    pricing:
    slidingWindowSize: 20
    failureRateThreshold: 50
    waitDurationInOpenState: 30s
    permittedNumberOfCallsInHalfOpenState: 5
    timelimiter:
    instances:
    pricing:
    timeoutDuration: 2s
    @Service
    public class PricingFacade {
    private final PricingClient client;
    public PricingFacade(PricingClient client) {
    this.client = client;
    }
    @CircuitBreaker(name = "pricing", fallbackMethod = "fallback")
    @TimeLimiter(name = "pricing")
    public CompletableFuture<Quote> quote(List<LineItem> items) {
    return client.quote(items);
    }
    CompletableFuture<Quote> fallback(List<LineItem> items, Throwable t) {
    return CompletableFuture.completedFuture(Quote.degraded(items));
    }
    }

    Real-world use

    A pricing dependency blip once saturated Orders Tomcat threads waiting on HTTP. After Resilience4j time limiters and circuit breakers, checkout returned degraded 'price unavailable — retry' within 2s instead of queueing the whole site. TechLearningPRO also moved non-critical pricing enrichment off the critical path.

    Security implications

    Degraded modes must not bypass authz.

    • Fallbacks still enforce who may see cached data.
    • Do not log downstream credentials when breakers trip.
    • Keep client secrets in env placeholders, not in resilience config samples.

    Best practices

    • Timeouts on every remote call — breakers need failure signals.
    • Metrics for state transitions (open/half-open) in Grafana.
    • Prefer async/messaging for work that need not block checkout.

    Common mistakes

    • Retrying non-idempotent POSTs and duplicating orders.
    • Fallbacks that return stale authoritative prices without labelling degradation.
    • Copying Hystrix samples that no longer apply on Boot 3.

    Advanced interview questions

    Interview Prep

    Practice concise answers, then expand each card for the explanation.

    3 questions
    1BeginnerQuestionWhat does a circuit breaker prevent?+

    Answer

    Cascading failure by failing fast when a dependency is unhealthy instead of exhausting threads/connections.
    2IntermediateQuestionWhat replaced Hystrix in Spring Cloud?+

    Answer

    Resilience4j is the standard for Boot 2.x/3.x; Hystrix is in maintenance/retired for new work.
    3IntermediateQuestionWhy pair TimeLimiter with CircuitBreaker?+

    Answer

    Hung calls may not count as failures quickly; timeouts create clear failure signals and free threads.

    Hands-on exercise

    Lab. Wire the pricing facade above. Force pricing to sleep 5s; confirm timeout + open circuit. Verify fallback responses and that Orders threads remain available for health checks.

    Summary

    Breakers keep Orders responsive when dependencies fail. Next: follow a request across services with distributed tracing.

    Ready to mark this lesson complete?Track your journey across the entire course.