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

IP Hits $11.75, HYPE Climbs to $55, BlockDAG Surpasses Both with $407M Presale Surge!

IP Hits $11.75, HYPE Climbs to $55, BlockDAG Surpasses Both with $407M Presale Surge!

The post IP Hits $11.75, HYPE Climbs to $55, BlockDAG Surpasses Both with $407M Presale Surge! appeared on BitcoinEthereumNews.com. Crypto News 17 September 2025 | 18:00 Discover why BlockDAG’s upcoming Awakening Testnet launch makes it the best crypto to buy today as Story (IP) price jumps to $11.75 and Hyperliquid hits new highs. Recent crypto market numbers show strength but also some limits. The Story (IP) price jump has been sharp, fueled by big buybacks and speculation, yet critics point out that revenue still lags far behind its valuation. The Hyperliquid (HYPE) price looks solid around the mid-$50s after a new all-time high, but questions remain about sustainability once the hype around USDH proposals cools down. So the obvious question is: why chase coins that are either stretched thin or at risk of retracing when you could back a network that’s already proving itself on the ground? That’s where BlockDAG comes in. While other chains are stuck dealing with validator congestion or outages, BlockDAG’s upcoming Awakening Testnet will be stress-testing its EVM-compatible smart chain with real miners before listing. For anyone looking for the best crypto coin to buy, the choice between waiting on fixes or joining live progress feels like an easy one. BlockDAG: Smart Chain Running Before Launch Ethereum continues to wrestle with gas congestion, and Solana is still known for network freezes, yet BlockDAG is already showing a different picture. Its upcoming Awakening Testnet, set to launch on September 25, isn’t just a demo; it’s a live rollout where the chain’s base protocols are being stress-tested with miners connected globally. EVM compatibility is active, account abstraction is built in, and tools like updated vesting contracts and Stratum integration are already functional. Instead of waiting for fixes like other networks, BlockDAG is proving its infrastructure in real time. What makes this even more important is that the technology is operational before the coin even hits exchanges. That…
Share
BitcoinEthereumNews2025/09/18 00:32
Breaking: CME Group Unveils Solana and XRP Options

Breaking: CME Group Unveils Solana and XRP Options

CME Group launches Solana and XRP options, expanding crypto offerings. SEC delays Solana and XRP ETF approvals, market awaits clarity. Strong institutional demand drives CME’s launch of crypto options contracts. In a bold move to broaden its cryptocurrency offerings, CME Group has officially launched options on Solana (SOL) and XRP futures. Available since October 13, 2025, these options will allow traders to hedge and manage exposure to two of the most widely traded digital assets in the market. The new contracts come in both full-size and micro-size formats, with expiration options available daily, monthly, and quarterly, providing flexibility for a diverse range of market participants. This expansion aligns with the rising demand for innovative products in the crypto space. Giovanni Vicioso, CME Group’s Global Head of Cryptocurrency Products, noted that the new options offer increased flexibility for traders, from institutions to active individual investors. The growing liquidity in Solana and XRP futures has made the introduction of these options a timely move to meet the needs of an expanding market. Also Read: Vitalik Buterin Reveals Ethereum’s Bold Plan to Stay Quantum-Secure and Simple! Rapid Growth in Solana and XRP Futures Trading CME Group’s decision to roll out options on Solana and XRP futures follows the substantial growth in these futures products. Since the launch of Solana futures in March 2025, more than 540,000 contracts, totaling $22.3 billion in notional value, have been traded. In August 2025, Solana futures set new records, with an average daily volume (ADV) of 9,000 contracts valued at $437.4 million. The average daily open interest (ADOI) hit 12,500 contracts, worth $895 million. Similarly, XRP futures, which launched in May 2025, have seen significant adoption, with over 370,000 contracts traded, totaling $16.2 billion. XRP futures also set records in August 2025, with an ADV of 6,600 contracts valued at $385 million and a record ADOI of 9,300 contracts, worth $942 million. Institutional Demand for Advanced Hedging Tools CME Group’s expansion into options is a direct response to growing institutional interest in sophisticated cryptocurrency products. Roman Makarov from Cumberland Options Trading at DRW highlighted the market demand for more varied crypto products, enabling more advanced risk management strategies. Joshua Lim from FalconX also noted that the new options products meet the increasing need for institutional hedging tools for assets like Solana and XRP, further cementing their role in the digital asset space. The launch of options on Solana and XRP futures marks another step toward the maturation of the cryptocurrency market, providing a broader range of tools for managing digital asset exposure. SEC’s Delay on Solana and XRP ETF Approvals While CME Group expands its offerings, the broader market is also watching the progress of Solana and XRP exchange-traded funds (ETFs). The U.S. Securities and Exchange Commission (SEC) has delayed its decisions on multiple crypto-related ETF filings, including those for Solana and XRP. Despite the delay, analysts anticipate approval may be on the horizon. This week, REX Shares and Osprey Funds are expected to launch an XRP ETF that will hold XRP directly and allocate at least 40% of its assets to other XRP-related ETFs. Despite the delays, some analysts believe that approval could come soon, fueling further interest in these assets. The delay by the SEC has left many crypto investors awaiting clarity, but approval of these ETFs could fuel further momentum in the Solana and XRP futures markets. Also Read: Tether CEO Breaks Silence on $117,000 Bitcoin Price – Market Reacts! The post Breaking: CME Group Unveils Solana and XRP Options appeared first on 36Crypto.
Share
Coinstats2025/09/18 02:35