Şuayb's BlogŞuayb's Blog
Home
Categories
Games
MediumAboutContact
Language
Theme
    1. Blog
    2. Programming
    3. Spring Boot Circuit Breaker

Spring Boot Circuit Breaker

PublishedMarch 13, 2025
UpdatedMarch 14, 2025
Reading time3 min read
JavaKotlinSpring BootSpring CloudCircuit BreakerMicroservice
XLinkedInFacebook
Spring Boot Circuit Breaker

Loading likes...

Spring Boot Circuit Breaker is a fault-tolerance mechanism used to prevent cascading failures in a microservices architecture. It helps applications handle failures gracefully by detecting failures and stopping excessive requests to unhealthy services. This guide will walk you through implementing Circuit Breaker using Resilience4j in Spring Boot.


Last updatedMarch 14, 2025

Total viewsLoading hits...

Previous articleSpring Boot Eureka ServerNext articleSpring Boot Test-Driven Development
Şuayb Şimşek

Written by

Şuayb Şimşek

Backend-focused fullstack developer sharing practical notes on Spring Boot, security, microservices, and cloud-native architecture.

Expertise

  • Spring Boot
  • Go
  • Microservices
  • Next.js
  • Cloud Native

Connect

GitHubLinkedInMedium

Related posts

Spring Boot Eureka Server
Programming

Spring Boot Eureka Server

Learn how to set up and configure a Spring Boot Eureka Server for service discovery in microservices architecture.

February 23, 20253 min read
JavaKotlinSpring BootSpring CloudEureka ServerMicroservice
Spring Boot Config Server
Programming

Spring Boot Config Server

Learn how to use Spring Boot Config Server to centralize and manage application configurations efficiently.

February 22, 20253 min read
JavaKotlinSpring BootSpring CloudConfig ServerMicroservice
Spring Boot Kubernetes Integration
Programming

Spring Boot Kubernetes Integration

Learn how to deploy Spring Boot applications on Kubernetes for scalable, containerized microservices.

February 21, 20253 min read
JavaKotlinSpring BootKubernetesMicroserviceContainerization

About

Articles on Spring Boot, microservices, security, and more.

ContactStart here

Latest posts

  • Captain Tsubasa 2: World Fighters
  • Captain Tsubasa: Rise of New Champions
  • Spring Boot Configuration Properties
  • Spring Boot GraphQL JWE Authentication
  • Spring Boot JWE Authentication with JPA

Top topics

JavaKotlinSpring BootJWEJWTMicroservice

Subscribe

Get practical backend + fullstack notes when new articles are published.

Social

© 2024-2026 Şuayb's Blog. All rights reserved.

🌟 Why Use Circuit Breaker?

In this section, we clarify Why Use Circuit Breaker? and summarize the key points you will apply in implementation.

  • Prevents cascading failures in microservices.
  • Improves application resilience by stopping excessive failed requests.
  • Automatically recovers when services become healthy again.
  • Reduces latency by preventing unnecessary waits for failed services.
  • Configurable retry strategies to manage failures efficiently.

📋 Prerequisites

Ensure you have the following:

  • ☕ Java Development Kit (JDK) 17+
  • 📦 Maven or Gradle installed
  • 🌐 Spring Boot & Spring Cloud
  • 🛠 A REST API to demonstrate Circuit Breaker behavior

🛠️ Step 1: Add Dependencies

In this section, we clarify Step 1: Add Dependencies and summarize the key points you will apply in implementation.

Maven:

XMLpom.xml
<dependency>
  <groupId>org.springframework.cloud</groupId>
  <artifactId>spring-cloud-starter-circuitbreaker-resilience4j</artifactId>
</dependency>

Gradle:

GROOVYbuild.gradle
implementation 'org.springframework.cloud:spring-cloud-starter-circuitbreaker-resilience4j'

🛠️ Step 2: Configure Circuit Breaker Properties

Define Circuit Breaker settings in application.yml.

YAMLconfig.yml
resilience4j:
  circuitbreaker:
    instances:
      externalService:
        failure-rate-threshold: 50
        slow-call-rate-threshold: 50
        slow-call-duration-threshold: 2000ms
        permitted-number-of-calls-in-half-open-state: 3
        sliding-window-size: 10
        minimum-number-of-calls: 5
        wait-duration-in-open-state: 5s

🛠️ Step 3: Implement Circuit Breaker in a REST Service

In this section, we clarify Step 3: Implement Circuit Breaker in a REST Service and summarize the key points you will apply in implementation.

Create a Service to Call an External API

The following example gives practical context for Create a Service to Call an External API and can be applied directly.


🛠️ Step 4: Create a REST Controller


▶️ Running the Application

Start the application:

BASH
./mvnw spring-boot:run

or using Gradle:

BASH
gradle bootRun

🧪 Test the Circuit Breaker

Test the Circuit Breaker:

BASH
curl -X GET http://localhost:8080/api/data

🏁 Conclusion

You now have a practical Spring Boot Circuit Breaker implementation with a clear, production-friendly Spring Boot structure. As a next step, adapt configuration and tests to your own domain, then validate behavior under realistic traffic and failure scenarios.

JAVAExternalService.java
package com.example.circuitbreaker.service;

import io.github.resilience4j.circuitbreaker.annotation.CircuitBreaker;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

@Service
public class ExternalService {

    private final RestTemplate restTemplate = new RestTemplate();

    @CircuitBreaker(name = "externalService", fallbackMethod = "fallbackResponse")
    public String callExternalAPI() {
        return restTemplate.getForObject("http://unreliable-service/api/data", String.class);
    }

    public String fallbackResponse(Exception e) {
        return "Fallback response: Service is unavailable!";
    }
}
KOTLINExternalService.kt
package com.example.circuitbreaker.service

import io.github.resilience4j.circuitbreaker.annotation.CircuitBreaker
import org.springframework.stereotype.Service
import org.springframework.web.client.RestTemplate

@Service
class ExternalService {
    private val restTemplate = RestTemplate()

    @CircuitBreaker(name = "externalService", fallbackMethod = "fallbackResponse")
    fun callExternalAPI(): String {
        return restTemplate.getForObject("http://unreliable-service/api/data", String::class.java) ?: ""
    }

    fun fallbackResponse(e: Exception): String {
        return "Fallback response: Service is unavailable!"
    }
}
JAVACircuitBreakerController.java
package com.example.circuitbreaker.controller;

import com.example.circuitbreaker.service.ExternalService;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/api")
public class CircuitBreakerController {

    private final ExternalService externalService;

    public CircuitBreakerController(ExternalService externalService) {
        this.externalService = externalService;
    }

    @GetMapping("/data")
    public String fetchData() {
        return externalService.callExternalAPI();
    }
}
KOTLINCircuitBreakerController.kt
package com.example.circuitbreaker.controller

import com.example.circuitbreaker.service.ExternalService
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RestController

@RestController
@RequestMapping("/api")
class CircuitBreakerController(private val externalService: ExternalService) {

    @GetMapping("/data")
    fun fetchData(): String {
        return externalService.callExternalAPI()
    }
}