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.

<dependency>
  <groupId>org.springframework.cloud</groupId>
  <artifactId>spring-cloud-starter-circuitbreaker-reactor-resilience4j</artifactId>
  <version>2.1.0</version>
</dependency>

Basic configuration

Define a route that uses the CircuitBreaker filter.

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

Fallback URI

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

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

Fallback controller

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

Java‑based configuration

@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();
}

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.

@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());
  }
}

Custom timeout

Customize the timeout of the Resilience4j circuit breaker.

@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");
  }
}

Triggering on specific status codes

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

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

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

End of tutorial.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

CircuitBreakergatewayspring-bootspring-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

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.