Backend Development 5 min read

Implementing Spring Cloud CircuitBreaker in Gateway: Config & Fallback Guide

Learn how to enable Spring Cloud CircuitBreaker in Spring Cloud Gateway using Resilience4j, configure filters, define fallback URIs, customize timeout settings, handle exceptions, and control circuit breaking based on HTTP status codes, with both YAML and Java code examples.

Spring Full-Stack Practical Cases
Spring Full-Stack Practical Cases
Spring Full-Stack Practical Cases
Implementing Spring Cloud CircuitBreaker in Gateway: Config & Fallback Guide

Overview

Spring Cloud CircuitBreaker GatewayFilter wraps gateway routes with a circuit breaker using the Spring Cloud CircuitBreaker API. It supports multiple libraries, with Resilience4j available out‑of‑the‑box.

Enabling the filter

Include the dependency org.springframework.cloud:spring-cloud-starter-circuitbreaker-reactor-resilience4j:2.1.0 on the classpath.

<code>&lt;dependency&gt;
  &lt;groupId&gt;org.springframework.cloud&lt;/groupId&gt;
  &lt;artifactId&gt;spring-cloud-starter-circuitbreaker-reactor-resilience4j&lt;/artifactId&gt;
  &lt;version&gt;2.1.0&lt;/version&gt;
&lt;/dependency&gt;
</code>

Basic configuration

Define a route that uses the CircuitBreaker filter.

<code>spring:
  cloud:
    gateway:
      routes:
        - id: S001
          uri: http://localhost:9091
          filters:
            - CircuitBreaker=myCircuitBreaker
</code>

Fallback URI

The filter can accept an optional fallbackUri parameter. When a fallback is triggered, the request is forwarded to the specified controller.

<code>spring:
  cloud:
    gateway:
      routes:
        - id: S001
          uri: http://localhost:9091
          predicates:
            - Path=/api-1/**
          filters:
            - name: CircuitBreaker
              args:
                name: myCircuitBreaker
                fallbackUri: forward:/fallback
</code>

Fallback controller

<code>@RestController
@RequestMapping("/fallback")
public class FallbackController {
  @GetMapping("")
  public Object index() {
    return "fallback";
  }
}
</code>

Java‑based configuration

<code>@Bean
public RouteLocator routes(RouteLocatorBuilder builder) {
  return builder.routes()
    .route("S001", r -> r.path("/api-1/**")
      .filters(f -> f.circuitBreaker(c -> c.name("myCircuitBreaker")
        .fallbackUri("forward:/fallback")))
      .uri("http://localhost:9091"))
    .build();
}
</code>

Accessing the original exception

The filter adds the throwable that caused the fallback to the attribute ServerWebExchangeUtils.CIRCUITBREAKER_EXECUTION_EXCEPTION_ATTR on the ServerWebExchange , which can be read in a fallback handler.

<code>@RestController
public class FallbackController {
  @GetMapping("/fallback")
  public Mono<String> fallback(ServerWebExchange exchange) {
    Throwable t = exchange.getAttribute(ServerWebExchangeUtils.CIRCUITBREAKER_EXECUTION_EXCEPTION_ATTR);
    t.printStackTrace();
    return Mono.just(t.getMessage());
  }
}
</code>

Custom timeout

Customize the timeout of the Resilience4j circuit breaker.

<code>@Component
public class CustomCircuitBreakerConfig implements Customizer<ReactiveResilience4JCircuitBreakerFactory> {
  @Override
  public void customize(ReactiveResilience4JCircuitBreakerFactory factory) {
    factory.configure(builder -> {
      builder.timeLimiterConfig(
        TimeLimiterConfig.custom()
          .timeoutDuration(Duration.ofSeconds(5))
          .build());
    }, "orderCircuitBreaker");
  }
}
</code>

Triggering on specific status codes

Configure the circuit breaker to open when the wrapped route returns certain HTTP status codes.

<code>spring:
  cloud:
    gateway:
      routes:
        - id: ingredients
          uri: lb://order-service
          predicates:
            - Path=/api-a/**
          filters:
            - name: CircuitBreaker
              args:
                name: myCircuitBreaker
                fallbackUri: forward:/fallback
                statusCodes:
                  - 500
</code>

When the fallback is invoked, the request can be forwarded to another service or route as needed.

End of tutorial.

Spring BootcircuitbreakergatewaySpring CloudResilience4j
Spring Full-Stack Practical Cases
Written by

Spring Full-Stack Practical Cases

Full-stack Java development with Vue 2/3 front-end suite; hands-on examples and source code analysis for Spring, Spring Boot 2/3, and Spring Cloud.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.