Learn how to make your microservice calls resilient using the Circuit Breaker pattern with Resilience4j and Spring Boot. The pattern: Detects a failing dependency, stops sending requests to it, returns a graceful fallback response, periodically tests the dependency, and restores normal operation.Learn how to make your microservice calls resilient using the Circuit Breaker pattern with Resilience4j and Spring Boot. The pattern: Detects a failing dependency, stops sending requests to it, returns a graceful fallback response, periodically tests the dependency, and restores normal operation.

How to Build Resilient APIs With Resilience4j Circuit Breaker in Spring Boot

2025/12/05 23:00

Overview

Learn how to make your microservice calls resilient using the Circuit Breaker pattern with Resilience4j and Spring Boot — complete demo, step-by-step commands, class-by-class explanations, sample outputs, real-world use cases, and production tips.

Why This Matters

In distributed systems, a failing downstream service can cascade and cause overall system outages. The Circuit Breaker pattern:

  • Detects a failing dependency,
  • Stops sending requests to it (to avoid wasting resources),
  • Returns a graceful fallback response,
  • Periodically tests the dependency and restores normal operation when healthy.

\ This reduces downtime, protects thread pools, keeps user experience reasonable, and prevents retry storms.

Demo Summary (What You Have)

A two-service Maven demo:

  • hello-service (port 8081) — simple REST provider that intentionally fails intermittently.

    \

End point

GET /api/hello

  • client-service (port 8080) — calls hello-service using RestTemplate and is protected by Resilience4j @CircuitBreaker with a fallback.

    \

End point

GET /api/get-message

\ Run both (hello-service and client-service)

\ Then test

GET http://localhost:8080/api/get-message

Architecture Diagram

This is a small, focused flow suitable for drawing a diagram

Files & Code: Class-By-Class Explanation

hello-service

HelloServiceApplication.java

  • Standard @SpringBootApplication bootstrap class.

    \

HelloController.java @RestController public class HelloController { private static int counter = 0; @GetMapping("/api/hello") public String sayHello() { counter++; // simulate intermittent failure: fail on every 3rd request if (counter % 3 == 0) { throw new RuntimeException("Simulated failure from Hello-Service!"); } return "Hello from Hello-Service! (count=" + counter + ")"; } }

\ Explanation: This controller intentionally throws a RuntimeException on periodic calls to simulate transient failures you’d see in real systems (DB outage, bad data, timeouts).

client-service

ClientServiceApplication.java

  • Standard Spring Boot main class. No special config required.

AppConfig.java @Configuration public class AppConfig { @Bean public RestTemplate restTemplate() { return new RestTemplate(); } }

\ Explanation: Provides a single RestTemplate bean. Ensure RestTemplate is a Spring bean so AOP/resilience proxies can work properly.

HelloClientService.java @Service public class HelloClientService { private final RestTemplate restTemplate; @Value("${hello.service.url}") private String helloServiceUrl; public HelloClientService(RestTemplate restTemplate) { this.restTemplate = restTemplate; } @CircuitBreaker(name = "helloService", fallbackMethod = "fallbackHello") public String getHelloMessage() { System.out.println("Calling hello service: " + helloServiceUrl); return restTemplate.getForObject(helloServiceUrl, String.class); } public String fallbackHello(Throwable t) { System.out.println("Fallback triggered: " + t); return "Hello Service is currently unavailable. Please try again later."; } }

Explanation (crucial bits)

  • @CircuitBreaker(name = "helloService", fallbackMethod = "fallbackHello") wraps the getHelloMessage() call in a circuit breaker. The name links to configuration properties.

    \

  • fallbackHello(Throwable t) is called when the call fails according to the breaker rules.

    The fallback must:

o    Be in the same class o    Have the same return type o Accept the original method parameters (none here) and a final Throwable parameter (or Exception/Throwable compatible with thrown exceptions)

\

  • Important: The method must be public, and the class must be a Spring bean (@Service), so proxy-based AOP works.

    \

ClientController.java @RestController public class ClientController { private final HelloClientService helloClientService; public ClientController(HelloClientService helloClientService) { this.helloClientService = helloClientService; } @GetMapping("/api/get-message") public String getMessage() { return helloClientService.getHelloMessage(); } }

\ Explanation: Simple controller delegating to HelloClientService. This ensures the call goes through the proxy where the circuit breaker is applied.

Configuration Used (client-service application.properties)

Key configuration used in the demo

\

server.port=8080 spring.application.name=client-service hello.service.url=http://localhost:8081/api/hello resilience4j.circuitbreaker.instances.helloService.registerHealthIndicator=true resilience4j.circuitbreaker.instances.helloService.slidingWindowSize=5 resilience4j.circuitbreaker.instances.helloService.minimumNumberOfCalls=2 resilience4j.circuitbreaker.instances.helloService.failureRateThreshold=50 resilience4j.circuitbreaker.instances.helloService.waitDurationInOpenState=10s logging.level.io.github.resilience4j.circuitbreaker=DEBUG

\ Meaning of important properties

  • slidingWindowSize: number of calls the breaker monitors for failure percentage.
  • minimumNumberOfCalls: minimum calls before failure rate is evaluated.
  • failureRateThreshold: percent failures (e.g., 50) to open the circuit.
  • waitDurationInOpenState: how long the circuit stays open before moving to half-open.
  • registerHealthIndicator: exposes breaker state via actuator.

Step-By-Step Run & Expected Outputs

Start Services

  1. Start hello-service

Visit: http://localhost:8081/api/hello

\ Returns → "Hello from Hello-Service!" (or throws simulated failure)

  1. Start client-service

Visit: http://localhost:8080/api/get-message

Test Scenarios & Outputs

Scenario A — Hello-Service Healthy

Make a request

GET http://localhost:8080/api/get-message

\ Client logs

Calling hello service: http://localhost:8081/api/hello 2025-11-13T11:58:23.366+05:30 DEBUG 32692 --- [client-service] [nio-8080-exec-8] i.g.r.c.i.CircuitBreakerStateMachine : CircuitBreaker 'helloService' succeeded: 2025-11-13T11:58:23.366+05:30 DEBUG 32692 --- [client-service] [nio-8080-exec-8] i.g.r.c.i.CircuitBreakerStateMachine : Event SUCCESS published: 2025-11-13T11:58:23.366634+05:30[Asia/Calcutta]: CircuitBreaker 'helloService' recorded a successful call. Elapsed time: 15 ms

\ Response

Hello from Hello-Service! (count=4)

Scenario B — Hello-Service Intermittent Failures

If you call repeatedly and hello-service throws RuntimeException on some requests:

● Successful calls: client returns the hello message.

●  When a downstream call returns HTTP 500/exception:

o    Resilience4j records the failure. o    If failure rate exceeds threshold (e.g., 50% over sliding window), the Circuit becomes **OPEN**. o    While OPEN, calls are short-circuited; **fallbackHello**() is immediately executed — no network call. \n **Client response while fallback active**

\ Client Response while active

Response

Hello Service is currently unavailable. Please try again later.

\ POSTMAN

Sample client log sequence

Calling hello service: http://localhost:8081/api/hello 2025-11-13T12:00:55.842+05:30 DEBUG 32692 --- [client-service] [nio-8080-exec-1] i.g.r.c.i.CircuitBreakerStateMachine : CircuitBreaker 'helloService' recorded an exception as failure:

Scenario C — Recovery

After waitDurationInOpenState (10s):

  • Circuit goes to HALF_OPEN: a few test calls are allowed.
  • If test calls succeed, breaker CLOSES and normal traffic resumes.
  • If tests fail, the breaker goes back to OPEN.

Real-World Use Cases

  1. Payment Integration - A checkout service calling an external bank API: if the bank’s API becomes slow/fails, the circuit breaker returns a user-friendly message and prevents retry storms.
  2. Third-party rate-limited APIs - APIs with limited calls per second — when limits are reached, the circuit opens to avoid hitting quotas further; fallback returns cached data.
  3. Microservice chains inside an enterprise - Service A calls B, which calls C. If C is unstable, open breakers protect B and A, preventing system-wide slowdown.
  4. Feature toggles and graceful degradation - When a non-critical feature service fails, return a simpler result to keep core functionality available (e.g., return product list without recommendations).

Advantages & Business Value

  • Fault isolation — prevents one bad dependency from cascading.
  • Faster failure response — fails fast instead of waiting on timeouts.
  • Graceful degradation — offers fallback responses instead of full outages.
  • Resource protection — avoids wasting CPU, threads, and network.
  • Auto recovery — automatically returns to normal when the dependency is healthy.
  • Observability — breaker states and metrics can be exposed via the Actuator and monitored.

\ Sample logs you’ll see (realistic)

Calling hello service: http://localhost:8081/api/hello 2025-11-13T12:00:55.842+05:30 DEBUG 32692 --- [client-service] [nio-8080-exec-1] i.g.r.c.i.CircuitBreakerStateMachine : CircuitBreaker 'helloService' recorded an exception as failure 2025-11-13T12:00:55.847+05:30 DEBUG 32692 --- [client-service] [nio-8080-exec-1] i.g.r.c.i.CircuitBreakerStateMachine : Event ERROR published: 2025-11-13T12:00:55.847908200+05:30[Asia/Calcutta]: CircuitBreaker 'helloService' recorded an error: 'org.springframework.web.client.HttpServerErrorException$InternalServerError: 500 : "{"timestamp":"2025-11-13T06:30:55.842+00:00","status":500,"error":"Internal Server Error","path":"/api/hello"}"'. Elapsed time: 8 ms Fallback triggered: org.springframework.web.client.HttpServerErrorException$InternalServerError: 500 : "{"timestamp":"2025-11-13T06:30:55.842+00:00","status":500,"error":"Internal Server Error","path":"/api/hello"}"

\

Disclaimer: The articles reposted on this site are sourced from public platforms and are provided for informational purposes only. They do not necessarily reflect the views of MEXC. All rights remain with the original authors. If you believe any content infringes on third-party rights, please contact service@support.mexc.com for removal. MEXC makes no guarantees regarding the accuracy, completeness, or timeliness of the content and is not responsible for any actions taken based on the information provided. The content does not constitute financial, legal, or other professional advice, nor should it be considered a recommendation or endorsement by MEXC.

You May Also Like

Stijgt XRP koers boven $2,28 door buy zone indicator en groeiende whale activiteit?

Stijgt XRP koers boven $2,28 door buy zone indicator en groeiende whale activiteit?

XRP laat in de laatste 24 uur een koersdaling zien van bijna 4%. Hierdoor staat de markt opnieuw stil bij de manier waarop Ripple zijn infrastructuur voor wereldwijde liquiditeit uitbreidt. De afronding van de GTreasury overname zorgt immers voor een nieuwe fase in de integratie van blockchain in traditionele financiële processen. De vraag is hoe de XRP koers hier in de komende periode op kan reageren. Check onze Discord Connect met "like-minded" crypto enthousiastelingen Leer gratis de basis van Bitcoin & trading - stap voor stap, zonder voorkennis. Krijg duidelijke uitleg & charts van ervaren analisten. Sluit je aan bij een community die samen groeit. Nu naar Discord GTreasury integratie brengt nieuw liquiditeitsmodel voor ondernemingen Ripple heeft GTreasury voor ongeveer $1 miljard gekocht. GTreasury levert al veertig jaar software voor treasury management en werkt wereldwijd voor meer dan 800 bedrijven. Het bedrijf is verbonden met naar schatting 13.000 financiële instellingen en verwerkt jaarlijks een groot volume aan betalingen. Al deze transactiestromen worden nu gekoppeld aan Ripple technologie zodat ondernemingen realtime betalingen kunnen uitvoeren met blockchain liquidity zonder een crypto wallet nodig te hebben. In de praktijk betekent dit dat bedrijven hun bestaande betaalsoftware blijven gebruiken. De afhandeling vindt nu op de achtergrond plaats via Ripple infrastructuur. Deze toegankelijkheid lost een veelvoorkomend probleem op in traditionele bedrijfsprocessen. Grote ondernemingen willen wel profiteren van snelle settlement, maar ze willen geen interne wijziging doorvoeren in hun systemen of compliance structuren. Door de GTreasury integratie ontstaat er een laag die beide werelden verbindt. Deze overname maakt deel uit van het bredere institutionele plan voor 2025. Ripple nam eerder Rail, Palisade en Ripple Prime over. Daarmee ontstaat één platform voor bedrijven die sneller willen afrekenen en hun liquiditeitsrisico lager willen houden. Volgens Reece Merrick van Ripple richten deze overnames zich op concrete knelpunten waar CFO’s wereldwijd mee te maken hebben. Bedrijven werken vaak met versnipperde systemen die traag zijn en veel handmatige controle vereisen. Ripple wil dit proces graag moderniseren met asset backed liquidity en een uniform settlement netwerk. Here’s Ripple’s one-stop shop visualized! Huge day now that GTreasury acquisition is closed! As you can see GTreasury is connected to 13 thousand banks with an annual volume of $12.5 Trillion. Remember that Ripple has a pending bank license and has applied for a FED master… https://t.co/EWqVYGku2p pic.twitter.com/onoSdjuuYv — Anders (@X__Anderson) December 5, 2025 Welke crypto nu kopen?Lees onze uitgebreide gids en leer welke crypto nu kopen verstandig kan zijn! Welke crypto nu kopen? De langste government shutdown in de geschiedenis van de VS is eindelijk achter de rug. Dat zorgt ervoor dat er eindelijk weer vooruitgang geboekt kan worden. Dit is erg bullish voor crypto, en dus gaan wereldberoemde traders ineens all-in op altcoins als XRP. Eén vraag komt telkens terug: welke crypto moet… Continue reading Stijgt XRP koers boven $2,28 door buy zone indicator en groeiende whale activiteit? document.addEventListener('DOMContentLoaded', function() { var screenWidth = window.innerWidth; var excerpts = document.querySelectorAll('.lees-ook-description'); excerpts.forEach(function(description) { var excerpt = description.getAttribute('data-description'); var wordLimit = screenWidth wordLimit) { var trimmedDescription = excerpt.split(' ').slice(0, wordLimit).join(' ') + '...'; description.textContent = trimmedDescription; } }); }); XRP koers krijgt steun door groeiende institutionele vraag De institutionele belangstelling voor XRP neemt in meerdere regio’s toe. Verschillende rapporten tonen echter dat de verkoopdruk in de rest van de markt niet terugkomt bij XRP producten. Europese investeerders hebben in 2025 ongeveer $549 miljoen aan XRP producten toegevoegd. Dit ligt hoger dan de instroom in Ethereum producten en ruim boven het recente herstel van Solana. Buiten de Verenigde Staten kwam ongeveer $252 miljoen in XRP producten terecht. Deze instroom ligt dicht bij de instroom in Bitcoin producten, ondanks dat Bitcoin een veel grotere markt heeft. Relatief gezien kopen instellingen daarmee aanzienlijk meer XRP tokens dan Bitcoin. In de Verenigde Staten groeide de instroom in de synthetische XRP producten naar ongeveer $241 miljoen. Dit is de grootste instroom voor alle altcoins in de regio. Onderzoekers melden daarnaast dat de XRP ETF’s op één dag meer dan $50 miljoen aan nieuwe instroom kregen. Hierdoor komen de totale spot assets dicht bij de grens van $1 miljard. Volgens crypto-analisten houdt een deel van de whales XRP vast als langetermijn allocatie. Ook bedrijven kunnen XRP aan hun treasury toevoegen. Dit kan op termijn de circulerende voorraad beïnvloeden, omdat er dan minder XRP tokens actief op de markt komen. $XRP ETFs just added $50.27M IN ONE DAY. Total assets now $906M — about to cross $1B. Whales buying spot. Corporations stacking XRP as treasury allocations. ETFs scaling inflows. Price hasn’t moved yet, but the supply is thinning behind the scenes. The XRP supply shock is… pic.twitter.com/ICe4RDQimg — Ripple Bull Winkle | Crypto Researcher (@RipBullWinkle) December 5, 2025 Crypto-analisten houden XRP koers nauwlettend in de gaten rond cruciale prijszones Crypto-analist Ali meldt dat XRP zich momenteel in een buyzone bevindt op basis van de TD Sequential indicator. Deze indicator laat om de paar candles mogelijke omkeerpunten zien op basis van vaste tellingen. Volgens Ali is $2,28 een belangrijke weerstandszone. Wanneer de XRP koers deze zone overtuigend doorbreekt, ontstaat er volgens hem ruimte richting hogere prijsniveaus zoals $2,75. EGRAG CRYPTO zegt dat veel investeerders de structurele veranderingen rond Ripple technologie niet volledig in hun analyse meenemen. Volgens hem ontwikkelen de liquiditeitsoplossingen voor bedrijven zich sneller dan veel mensen zich beseffen. Daardoor verschuift het marktsentiment rond XRP met regelmaat zodra er nieuwe onderdelen van de infrastructuur worden uitgerold. $XRP is a buy, according to the TD Sequential. pic.twitter.com/uI9s9Qwu6Y — Ali (@ali_charts) December 5, 2025 Vooruitblik op de volgende fase voor XRP De koppeling tussen GTreasury en Ripple technologie maakt het eenvoudiger voor bedrijven om zonder technische aanpassingen blockchain liquidity te gebruiken. Dit versterkt het institutionele fundament onder XRP en breidt de rol van het crypto token verder uit in internationale betalingsstromen. Crypto-analisten volgen vooral de reactie rond de weerstandszone bij $2,28 en de instroom in XRP producten. Deze twee factoren bepalen voor een groot deel hoe de markt het nieuwe liquiditeitsmodel waardeert. Best wallet - betrouwbare en anonieme wallet Best wallet - betrouwbare en anonieme wallet Meer dan 60 chains beschikbaar voor alle crypto Vroege toegang tot nieuwe projecten Hoge staking belongingen Lage transactiekosten Best wallet review Koop nu via Best Wallet Let op: cryptocurrency is een zeer volatiele en ongereguleerde investering. Doe je eigen onderzoek. Het bericht Stijgt XRP koers boven $2,28 door buy zone indicator en groeiende whale activiteit? is geschreven door Dirk van Haaster en verscheen als eerst op Bitcoinmagazine.nl.
Share
Coinstats2025/12/06 16:16