Spring Cloud Gateway

An API gateway is the single entry point in front of a set of services: it chooses a service for each request, and applies the rules every request needs, such as authentication, rate limits and timeouts. This page explains how Spring Cloud Gateway matches and forwards requests, runs the route matching and rate-limiting rules it is built on, and shows the configuration for Spring Boot 4.

Contents

What an API gateway does

Without a gateway, every client must know the address of every service, and every service must implement authentication, rate limiting, CORS and request logging itself. A gateway sits in front of all of them. It receives each request, decides which service should handle it, forwards it, and returns the response, applying shared rules on the way in and on the way out.

Spring Cloud Gateway builds this from three concepts:

  • Route: an ID, a destination URI, a list of predicates and a list of filters.
  • Predicate: a condition on the request, such as its path, host, method, a header or the time. A route applies when all its predicates match; routes are tried in order and the first match wins.
  • Filter: code that changes the request before it is forwarded or the response after it returns, such as removing a path prefix, adding a header, limiting the rate or retrying.

The gateway comes in two forms, which share these concepts:

The two forms of Spring Cloud Gateway 5
FormStarterRuns onBest for
Server WebFlux, the originalspring-cloud-starter-gateway-server-webfluxSpring WebFlux and NettyHigh numbers of concurrent connections, streaming, the full set of filters
Server Web MVCspring-cloud-starter-gateway-server-webmvcSpring MVC (WebMvc.fn) on Tomcat or JettyTeams that prefer the servlet stack and blocking code, especially with virtual threads

Spring Cloud Gateway 5.0 belongs to Spring Cloud 2025.1, the release train for Spring Boot 4; the programs here use version 5.0.3. Its starters have the server-webflux and server-webmvc names shown above. The WebFlux form reads its routes from spring.cloud.gateway.server.webflux.routes, and the Web MVC form from spring.cloud.gateway.server.webmvc.routes; guides written for older versions use spring-cloud-starter-gateway and spring.cloud.gateway.routes. Two programs run the Web MVC gateway against backend services in the same JVM. The WebFlux form could not run next to them: with Spring MVC on the classpath, a WebFlux gateway application fails at start-up with "Spring MVC found on classpath, which is incompatible with Spring Cloud Gateway", so its YAML examples are marked as not run. The other three programs show the path matcher the gateway uses, a forwarding route written by hand, and a model of the rate-limiting algorithm. The page's classpath holds spring-boot-starter-webmvc, spring-boot-starter-restclient, spring-cloud-starter-gateway-server-webmvc and spring-cloud-starter-circuitbreaker-resilience4j.

Defining routes

This program starts an orders service, an inventory service and a Web MVC gateway in front of them. The orders route is written in Java, and the stock route in configuration properties, the same keys an application.yml would hold. Three requests go to the gateway:

Java
package demo.gateway.routes;

import static org.springframework.cloud.gateway.server.mvc.filter.BeforeFilterFunctions.stripPrefix;
import static org.springframework.cloud.gateway.server.mvc.filter.BeforeFilterFunctions.uri;
import static org.springframework.cloud.gateway.server.mvc.handler.GatewayRouterFunctions.route;
import static org.springframework.cloud.gateway.server.mvc.handler.HandlerFunctions.http;

import java.util.stream.Stream;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.cloud.gateway.server.mvc.filter.BeforeFilterFunctions;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Import;
import org.springframework.core.env.Environment;
import org.springframework.http.HttpHeaders;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestClient;
import org.springframework.web.servlet.function.RouterFunction;
import org.springframework.web.servlet.function.ServerResponse;

public class GatewayRoutes {

    // ---- two backend services ----

    @RestController
    static class OrdersController {
        @GetMapping("/orders/{id}")
        String order(@PathVariable("id") String id, @RequestHeader HttpHeaders headers) {
            return "orders got /orders/" + id + describe(headers);
        }
    }

    @RestController
    static class InventoryController {
        @GetMapping("/stock/{sku}")
        String stock(@PathVariable("sku") String sku, @RequestHeader HttpHeaders headers) {
            return "inventory got /stock/" + sku + describe(headers);
        }
    }

    static String describe(HttpHeaders headers) {
        return " | X-Request-Source=" + headers.getFirst("X-Request-Source")
                + " X-Forwarded-Prefix=" + headers.getFirst("X-Forwarded-Prefix")
                + " X-Forwarded-For=" + headers.getFirst("X-Forwarded-For");
    }

    @SpringBootConfiguration
    @EnableAutoConfiguration
    @Import(OrdersController.class)
    static class OrdersService {
    }

    @SpringBootConfiguration
    @EnableAutoConfiguration
    @Import(InventoryController.class)
    static class InventoryService {
    }

    // ---- the gateway: one route in Java, one in properties ----

    @SpringBootConfiguration
    @EnableAutoConfiguration
    static class Gateway {
        @Bean
        RouterFunction<ServerResponse> ordersRoute(Environment env) {
            return route("orders")
                    .GET("/api/orders/**", http())
                    .before(uri(env.getProperty("orders.url")))
                    .before(stripPrefix(1))                 // /api/orders/42 -> /orders/42
                    .before(BeforeFilterFunctions.addRequestHeader("X-Request-Source", "gateway"))
                    .build();
        }
    }

    public static void main(String[] args) {
        String[] quiet = {"--server.port=0", "--spring.main.banner-mode=off",
                "--logging.level.root=WARN"};
        try (var orders = start(OrdersService.class, quiet);
             var inventory = start(InventoryService.class, quiet);
             var gateway = start(Gateway.class, quiet,
                     "--orders.url=" + url(orders),
                     // the stock route, as it would be written in application.yml
                     "--spring.cloud.gateway.server.webmvc.routes[0].id=stock",
                     "--spring.cloud.gateway.server.webmvc.routes[0].uri=" + url(inventory),
                     "--spring.cloud.gateway.server.webmvc.routes[0].predicates[0]"
                             + "=Path=/api/stock/**",
                     "--spring.cloud.gateway.server.webmvc.routes[0].filters[0]=StripPrefix=1",
                     // trust the client so that X-Forwarded-* headers are added
                     "--spring.cloud.gateway.server.webmvc.trusted-proxies=127\\.0\\.0\\.1")) {
            RestClient client = RestClient.create(url(gateway));
            for (String path : new String[] {"/api/orders/42", "/api/stock/book", "/api/users/7"}) {
                String result = client.get().uri(path).exchange((request, response) ->
                        response.getStatusCode().value() + " " + (response.getStatusCode()
                                .is2xxSuccessful() ? response.bodyTo(String.class) : ""));
                System.out.println("GET " + path + " -> " + result);
            }
        }
    }

    static ConfigurableApplicationContext start(Class<?> app, String[] quiet, String... more) {
        return new SpringApplication(app).run(
                Stream.concat(Stream.of(quiet), Stream.of(more)).toArray(String[]::new));
    }

    static String url(ConfigurableApplicationContext app) {
        return "http://localhost:" + app.getEnvironment().getProperty("local.server.port");
    }
}
Output
GET /api/orders/42 -> 200 orders got /orders/42 | X-Request-Source=gateway X-Forwarded-Prefix=/api X-Forwarded-For=127.0.0.1
GET /api/stock/book -> 200 inventory got /stock/book | X-Request-Source=null X-Forwarded-Prefix=/api X-Forwarded-For=127.0.0.1
GET /api/users/7 -> 404
  • /api/orders/42 matched the Java route. stripPrefix(1) removed /api, so the orders service received /orders/42, and addRequestHeader added X-Request-Source: gateway.
  • /api/stock/book matched the route from properties, Path=/api/stock/** with StripPrefix=1. It reached the inventory service as /stock/book, without X-Request-Source, because that filter belongs to the other route.
  • Both backends received X-Forwarded-Prefix: /api and X-Forwarded-For: 127.0.0.1, so a service can still build links that point through the gateway. The gateway added these headers only because trusted-proxies matched the caller's address: in a trial run without that property, no X-Forwarded-* header reached the backend.
  • /api/users/7 matched no route and got 404 from the gateway itself.

The Java form uses three static helpers: route starts a named route, http() is the handler that forwards the request, and before(uri(...)) sets the destination. Further filters chain with before, after and filter. The WebFlux form is configured mostly in YAML. This configuration, not run here, sends order and stock requests to two services in the same way:

YAML
spring:
  cloud:
    gateway:
      server:
        webflux:
          routes:
            - id: orders
              uri: http://orders:8080           # or lb://orders with a service registry
              predicates:
                - Path=/api/orders/**
                - Method=GET,POST
              filters:
                - StripPrefix=1                  # /api/orders/42 is sent as /orders/42
                - AddRequestHeader=X-Request-Source, gateway
            - id: stock
              uri: http://inventory:8080
              predicates:
                - Path=/api/stock/**
              filters:
                - StripPrefix=1
  • Path=/api/orders/** is the shortcut form: the predicate name, =, and its arguments separated by commas. Every predicate and filter also has a fully expanded form with name and args, needed for filters with many arguments.
  • A uri starting with lb:// resolves the service name through Spring Cloud LoadBalancer and a registry such as Eureka, as on the Eureka page.
  • Routes can also be defined in Java for the WebFlux form, with a RouteLocatorBuilder bean, which helps when routes are computed or need custom predicates.

How a route is chosen

The Path predicate matches with Spring's PathPatternParser, the same matcher Spring MVC and WebFlux use for request mappings. This program uses that matcher to look requests up in two route tables, applying the first match as the gateway does, and computes the forwarded path as StripPrefix=1 would:

Java
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import org.springframework.http.server.PathContainer;
import org.springframework.web.util.pattern.PathPattern;
import org.springframework.web.util.pattern.PathPatternParser;

// Route lookup as a gateway does it: routes are tried in order and the first match wins.
// The matching itself uses Spring's PathPatternParser, which the gateway's Path predicate uses.
public class RouteMatching {

    record Route(String id, PathPattern pattern, String target) {
    }

    static List<Route> routes(String... defs) {
        PathPatternParser parser = PathPatternParser.defaultInstance;
        return Arrays.stream(defs).map(d -> d.split(" "))
                .map(p -> new Route(p[0], parser.parse(p[1]), p[2])).toList();
    }

    static void lookup(List<Route> table, String path) {
        PathContainer container = PathContainer.parsePath(path);
        for (Route route : table) {
            PathPattern.PathMatchInfo match = route.pattern().matchAndExtract(container);
            if (match != null) {
                Map<String, String> vars = match.getUriVariables();
                // StripPrefix=1: drop the first path segment before forwarding
                String forwarded = path.substring(path.indexOf('/', 1));
                String line = String.format("  %-22s -> %-8s %s%s %s", path, route.id(),
                        route.target(), forwarded, vars.isEmpty() ? "" : vars);
                System.out.println(line.stripTrailing());
                return;
            }
        }
        System.out.printf("  %-22s -> no route: 404%n", path);
    }

    public static void main(String[] args) {
        List<Route> good = routes(
                "order /api/orders/{id} http://orders:8080",
                "orders /api/orders/** http://orders:8080",
                "stock /api/stock/** http://inventory:8080",
                "fallback /api/** http://legacy:8080");
        System.out.println("Specific routes first:");
        for (String path : List.of("/api/orders/42", "/api/orders/42/lines", "/api/stock/book",
                "/api/customers/7", "/health")) {
            lookup(good, path);
        }

        List<Route> bad = routes(
                "fallback /api/** http://legacy:8080",
                "order /api/orders/{id} http://orders:8080");
        System.out.println("Catch-all route first:");
        lookup(bad, "/api/orders/42");
    }
}
Output
Specific routes first:
  /api/orders/42         -> order    http://orders:8080/orders/42 {id=42}
  /api/orders/42/lines   -> orders   http://orders:8080/orders/42/lines
  /api/stock/book        -> stock    http://inventory:8080/stock/book
  /api/customers/7       -> fallback http://legacy:8080/customers/7
  /health                -> no route: 404
Catch-all route first:
  /api/orders/42         -> fallback http://legacy:8080/orders/42
  • /api/orders/42 matched the specific route /api/orders/{id} and captured id=42. Gateway filters can use such variables, for example SetPath=/orders/{id}.
  • /api/orders/42/lines has one segment too many for {id}, so it fell through to /api/orders/**, where ** matches any number of segments.
  • /api/customers/7 matched only the catch-all /api/** and went to the legacy system. /health matched nothing, and a gateway answers such a request with 404.
  • In the second table, the catch-all route came first, and it took /api/orders/42 away from the orders service. Order specific routes before general ones, or give them an explicit order value; the first match wins, not the best one.

StripPrefix=1 removed exactly one segment, /api, in every case. The service behind the gateway therefore sees paths without the prefix, which matters for links it generates: the gateway sends the removed prefix in X-Forwarded-Prefix, and Spring Boot applications that honour forwarded headers build correct links from it.

What forwarding involves

To see what the gateway does for every matched request, this program writes one route by hand, with the WebMvc.fn API that the Web MVC gateway is built on and a RestClient for the outgoing call. It runs an orders service and an edge service, and sends three requests to the edge:

Java
package demo.gateway.forwarding;

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.Arrays;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.web.server.context.WebServerApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Import;
import org.springframework.core.env.Environment;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestClient;
import org.springframework.web.servlet.function.RouterFunction;
import org.springframework.web.servlet.function.RouterFunctions;
import org.springframework.web.servlet.function.ServerResponse;

public class ForwardingRoute {

    // ---- a backend service ----

    @RestController
    static class OrderController {
        @GetMapping("/orders/{id}")
        String order(@PathVariable String id,
                @RequestHeader(name = "X-Forwarded-Prefix", required = false) String prefix) {
            return "order " + id + " (forwarded prefix: " + prefix + ")";
        }
    }

    @SpringBootConfiguration
    @EnableAutoConfiguration
    @Import(OrderController.class)
    static class OrderService {
    }

    // ---- an edge service: one route written with WebMvc.fn, the model Gateway MVC uses ----

    @SpringBootConfiguration
    @EnableAutoConfiguration
    static class Edge {
        @Bean
        RouterFunction<ServerResponse> ordersRoute(RestClient.Builder builder, Environment env) {
            RestClient backend = builder.baseUrl(env.getProperty("orders.url")).build();
            return RouterFunctions.route()
                    .GET("/api/orders/**", request -> {
                        // StripPrefix=1: /api/orders/42 becomes /orders/42
                        String path = request.path().substring("/api".length());
                        String body = backend.get().uri(path)
                                .header("X-Forwarded-Prefix", "/api")
                                .retrieve().body(String.class);
                        return ServerResponse.ok().header("X-Served-By", "edge").body(body);
                    })
                    // a "pre" filter: reject requests without an API key
                    .filter((request, next) -> request.headers().firstHeader("X-Api-Key") == null
                            ? ServerResponse.status(HttpStatus.UNAUTHORIZED).build()
                            : next.handle(request))
                    .build();
        }
    }

    public static void main(String[] args) throws Exception {
        String[] quiet = {"--spring.main.banner-mode=off", "--logging.level.root=WARN",
                "--server.port=0"};
        try (var orders = SpringApplication.run(OrderService.class, quiet);
             var edge = SpringApplication.run(Edge.class, concat(quiet,
                     "--orders.url=http://localhost:" + port(orders)))) {
            HttpClient http = HttpClient.newHttpClient();
            String base = "http://localhost:" + port(edge);
            send(http, HttpRequest.newBuilder(URI.create(base + "/api/orders/42"))
                    .header("X-Api-Key", "k-1").build());
            send(http, HttpRequest.newBuilder(URI.create(base + "/api/orders/42")).build());
            send(http, HttpRequest.newBuilder(URI.create(base + "/api/stock/book"))
                    .header("X-Api-Key", "k-1").build());
        }
    }

    static void send(HttpClient http, HttpRequest request) throws Exception {
        HttpResponse<String> r = http.send(request, HttpResponse.BodyHandlers.ofString());
        System.out.println("GET " + request.uri().getPath()
                + (request.headers().firstValue("X-Api-Key").isPresent() ? " with key" : "")
                + " -> " + r.statusCode() + ", X-Served-By="
                + r.headers().firstValue("X-Served-By").orElse("-")
                + (r.statusCode() == 200 ? ", body: " + r.body() : ""));
    }

    static int port(Object context) {
        return ((WebServerApplicationContext) context).getWebServer().getPort();
    }

    static String[] concat(String[] base, String... more) {
        String[] all = Arrays.copyOf(base, base.length + more.length);
        System.arraycopy(more, 0, all, base.length, more.length);
        return all;
    }
}
Output
GET /api/orders/42 with key -> 200, X-Served-By=edge, body: order 42 (forwarded prefix: /api)
GET /api/orders/42 -> 401, X-Served-By=-
GET /api/stock/book with key -> 404, X-Served-By=-
  • The request with an API key matched the route, passed the filter, and was forwarded as /orders/42, with X-Forwarded-Prefix: /api; the orders service's answer came back with the edge's own X-Served-By header.
  • The request without a key was stopped by the filter with 401 before any backend call. Rejecting requests at the edge saves every service from doing the same check.
  • /api/stock/book matched no route and got 404 from the edge itself.

The real gateway does much more on the same path: it copies the method, headers and body in both directions, streams large bodies instead of buffering them, removes hop-by-hop headers such as Connection, adds the X-Forwarded-* or Forwarded headers, applies timeouts, and maps connection failures to 502 or 504 responses. That is the reason to use it rather than hand-written forwarding. The X-Forwarded-Prefix header that this program sets by hand is the one the gateway added by itself in the previous program.

Rate limiting with a token bucket

The gateway's RequestRateLimiter filter uses the Redis rate limiter, an implementation of the token bucket algorithm. Each key, usually a user or an API client, has a bucket that holds at most burstCapacity tokens and is refilled at replenishRate tokens per second; each request takes one token, and a request that finds the bucket empty is rejected with HTTP 429. This model applies those rules second by second, to see what the two numbers allow:

Java
// A plain-Java model of the token bucket that the gateway's Redis rate limiter implements.
// It is NOT the gateway; it shows what replenishRate and burstCapacity allow, per second.
public class TokenBucket {

    private final int replenishRate;    // tokens added per second
    private final int burstCapacity;    // most tokens the bucket can hold
    private double tokens;

    TokenBucket(int replenishRate, int burstCapacity) {
        this.replenishRate = replenishRate;
        this.burstCapacity = burstCapacity;
        this.tokens = burstCapacity;     // a new key starts with a full bucket
    }

    // one second passes, then `requests` arrive at once, each costing one token
    String second(int requests) {
        tokens = Math.min(burstCapacity, tokens + replenishRate);
        int allowed = (int) Math.min(requests, Math.floor(tokens));
        tokens -= allowed;
        return String.format("%3d requests: %3d allowed, %3d rejected with 429, %2.0f left",
                requests, allowed, requests - allowed, tokens);
    }

    public static void main(String[] args) {
        System.out.println("replenishRate=10, burstCapacity=20:");
        TokenBucket bucket = new TokenBucket(10, 20);
        int[] traffic = {25, 25, 5, 5, 10, 30};
        for (int s = 0; s < traffic.length; s++) {
            System.out.println("  second " + s + ": " + bucket.second(traffic[s]));
        }

        System.out.println("replenishRate=10, burstCapacity=10 (a steady rate, no bursts):");
        TokenBucket steady = new TokenBucket(10, 10);
        for (int s = 0; s < 3; s++) {
            System.out.println("  second " + s + ": " + steady.second(15));
        }
    }
}
Output
replenishRate=10, burstCapacity=20:
  second 0:  25 requests:  20 allowed,   5 rejected with 429,  0 left
  second 1:  25 requests:  10 allowed,  15 rejected with 429,  0 left
  second 2:   5 requests:   5 allowed,   0 rejected with 429,  5 left
  second 3:   5 requests:   5 allowed,   0 rejected with 429, 10 left
  second 4:  10 requests:  10 allowed,   0 rejected with 429, 10 left
  second 5:  30 requests:  20 allowed,  10 rejected with 429,  0 left
replenishRate=10, burstCapacity=10 (a steady rate, no bursts):
  second 0:  15 requests:  10 allowed,   5 rejected with 429,  0 left
  second 1:  15 requests:  10 allowed,   5 rejected with 429,  0 left
  second 2:  15 requests:  10 allowed,   5 rejected with 429,  0 left
  • With a capacity of 20, the first burst of 25 requests got 20 through: the bucket started full. The rest got 429.
  • In the next second, only the 10 replenished tokens were available, so a second burst of 25 got 10 through. This is the documented behaviour: one burst above the rate is allowed, two bursts in a row are not.
  • Quiet seconds refilled the bucket, 5 tokens left after second 2 and 10 after second 3, and by second 5 it was full again, so a burst of 30 got 20 through.
  • With capacity equal to the rate, there was no burst allowance at all: exactly 10 requests per second, every second.
YAML
spring:
  cloud:
    gateway:
      server:
        webflux:
          routes:
            - id: orders
              uri: http://orders:8080
              predicates:
                - Path=/api/orders/**
              filters:
                - name: RequestRateLimiter
                  args:
                    redis-rate-limiter.replenishRate: 10
                    redis-rate-limiter.burstCapacity: 20
                    key-resolver: "#{@apiClientKeyResolver}"
Java
@Bean
KeyResolver apiClientKeyResolver() {
    // one bucket per API client; requests without the header have no key and are denied
    return exchange -> Mono.justOrEmpty(
            exchange.getRequest().getHeaders().getFirst("X-Api-Key"));
}

The Redis rate limiter needs spring-boot-starter-data-redis-reactive, and keeps the buckets in Redis so that all gateway instances share one limit per key. The default key resolver uses the authenticated principal's name; when the resolver finds no key, the request is denied, which spring.cloud.gateway.filter.request-rate-limiter.deny-empty-key can change. For limits below one request per second, the documentation uses requestedTokens: with a rate of 1, 60 tokens per request and a capacity of 60, a key gets one request a minute.

Resilience at the edge

The gateway is the natural place for retries and circuit breakers on calls into the system. This program puts a retry filter on the orders route, whose backend fails twice with 503 before it answers, and a circuitBreaker filter on the stock route, whose backend always fails. It configures a small breaker that judges the last 4 calls and opens at 50% failures, then sends one orders request and eight stock requests:

Java
package demo.gateway.resilience;

import static org.springframework.cloud.gateway.server.mvc.filter.BeforeFilterFunctions.stripPrefix;
import static org.springframework.cloud.gateway.server.mvc.filter.BeforeFilterFunctions.uri;
import static org.springframework.cloud.gateway.server.mvc.filter.RetryFilterFunctions.retry;
import static org.springframework.cloud.gateway.server.mvc.handler.GatewayRouterFunctions.route;
import static org.springframework.cloud.gateway.server.mvc.handler.HandlerFunctions.http;

import io.github.resilience4j.circuitbreaker.CircuitBreakerConfig;
import java.util.Set;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Stream;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.cloud.circuitbreaker.resilience4j.Resilience4JCircuitBreakerFactory;
import org.springframework.cloud.client.circuitbreaker.Customizer;
import org.springframework.cloud.gateway.server.mvc.filter.CircuitBreakerFilterFunctions;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Import;
import org.springframework.core.env.Environment;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestClient;
import org.springframework.web.servlet.function.RouterFunction;
import org.springframework.web.servlet.function.RouterFunctions;
import org.springframework.web.servlet.function.ServerResponse;

public class GatewayResilience {

    static final AtomicInteger ORDERS_CALLS = new AtomicInteger();
    static final AtomicInteger STOCK_CALLS = new AtomicInteger();

    @RestController
    static class Backend {
        // fails twice with 503, then answers
        @GetMapping("/orders/latest")
        ResponseEntity<String> latest() {
            int call = ORDERS_CALLS.incrementAndGet();
            return call <= 2 ? ResponseEntity.status(503).body("busy")
                    : ResponseEntity.ok("latest order, on backend call " + call);
        }

        // always fails
        @GetMapping("/stock/book")
        ResponseEntity<String> stock() {
            STOCK_CALLS.incrementAndGet();
            return ResponseEntity.status(503).body("database down");
        }
    }

    @SpringBootConfiguration
    @EnableAutoConfiguration
    @Import(Backend.class)
    static class BackendService {
    }

    @SpringBootConfiguration
    @EnableAutoConfiguration
    static class Gateway {
        @Bean
        RouterFunction<ServerResponse> ordersRoute(Environment env) {
            return route("orders")
                    .GET("/api/orders/**", http())
                    .before(uri(env.getProperty("backend.url")))
                    .before(stripPrefix(1))
                    .filter(retry(config -> config.setRetries(3)
                            .setMethods(Set.of(HttpMethod.GET))   // only idempotent calls
                            .setSeries(Set.of(HttpStatus.Series.SERVER_ERROR))))
                    .build();
        }

        @Bean
        RouterFunction<ServerResponse> stockRoute(Environment env) {
            return route("stock")
                    .GET("/api/stock/**", http())
                    .before(uri(env.getProperty("backend.url")))
                    .before(stripPrefix(1))
                    .filter(CircuitBreakerFilterFunctions.circuitBreaker(config -> config
                            .setId("stock")
                            .setStatusCodes("503")                 // count 503 as a failure
                            .setFallbackPath("/fallback/stock")))
                    .build();
        }

        @Bean
        RouterFunction<ServerResponse> fallback() {
            return RouterFunctions.route()
                    .GET("/fallback/stock", request -> ServerResponse.ok()
                            .body("stock unknown, try later"))
                    .build();
        }

        // a small breaker for the demo: judge the last 4 calls, open at 50% failures
        @Bean
        Customizer<Resilience4JCircuitBreakerFactory> breakerSettings() {
            return factory -> factory.configure(builder -> builder.circuitBreakerConfig(
                    CircuitBreakerConfig.custom().slidingWindowSize(4)
                            .minimumNumberOfCalls(4).failureRateThreshold(50).build()),
                    "stock");
        }
    }

    public static void main(String[] args) {
        String[] quiet = {"--server.port=0", "--spring.main.banner-mode=off",
                "--logging.level.root=WARN",
                // Tomcat warns at shutdown about the circuit breaker's pool thread
                "--logging.level.org.apache.catalina.loader=ERROR"};
        try (var backend = start(BackendService.class, quiet);
             var gateway = start(Gateway.class, quiet, "--backend.url=" + url(backend))) {
            RestClient client = RestClient.create(url(gateway));

            System.out.println("GET /api/orders/latest -> " + get(client, "/api/orders/latest")
                    + "  (backend calls: " + ORDERS_CALLS.get() + ")");

            for (int i = 1; i <= 8; i++) {
                System.out.println("GET /api/stock/book #" + i + " -> "
                        + get(client, "/api/stock/book")
                        + "  (backend calls so far: " + STOCK_CALLS.get() + ")");
            }
        }
    }

    static String get(RestClient client, String path) {
        return client.get().uri(path).exchange((request, response) ->
                response.getStatusCode().value() + " " + response.bodyTo(String.class));
    }

    static ConfigurableApplicationContext start(Class<?> app, String[] quiet, String... more) {
        return new SpringApplication(app).run(
                Stream.concat(Stream.of(quiet), Stream.of(more)).toArray(String[]::new));
    }

    static String url(ConfigurableApplicationContext app) {
        return "http://localhost:" + app.getEnvironment().getProperty("local.server.port");
    }
}
Output
GET /api/orders/latest -> 200 latest order, on backend call 3  (backend calls: 3)
GET /api/stock/book #1 -> 200 stock unknown, try later  (backend calls so far: 1)
GET /api/stock/book #2 -> 200 stock unknown, try later  (backend calls so far: 2)
GET /api/stock/book #3 -> 200 stock unknown, try later  (backend calls so far: 3)
GET /api/stock/book #4 -> 200 stock unknown, try later  (backend calls so far: 4)
GET /api/stock/book #5 -> 200 stock unknown, try later  (backend calls so far: 4)
GET /api/stock/book #6 -> 200 stock unknown, try later  (backend calls so far: 4)
GET /api/stock/book #7 -> 200 stock unknown, try later  (backend calls so far: 4)
GET /api/stock/book #8 -> 200 stock unknown, try later  (backend calls so far: 4)
  • The orders request returned 200, and the backend had been called 3 times. The first two calls got 503, which is in the SERVER_ERROR series, so the gateway retried; the client saw only the final success.
  • Stock requests 1 to 4 each reached the backend, got 503, and were answered by the fallback route with 200 and "stock unknown, try later". setStatusCodes("503") tells the breaker to treat a 503 response as a failure.
  • After 4 failures out of 4, the breaker opened. Requests 5 to 8 got the fallback at once, and the backend count stayed at 4: the gateway stopped sending traffic to a service that was failing anyway.
  • The fallback is set with setFallbackPath("/fallback/stock"), a path the gateway handles itself. In a trial run, the string "forward:/fallback/stock", the form the WebFlux YAML uses, failed in this Web MVC version with "Path [forward:/fallback/stock] does not start with a "/" character".

Retry only methods that are safe to repeat, as setMethods(Set.of(HttpMethod.GET)) does. Retrying a POST that timed out may create the order twice, as the resilience page explains. The circuitBreaker filter uses Spring Cloud CircuitBreaker with Resilience4j, which runs the call on a thread pool of its own; at shutdown Tomcat warns that the pool's thread is still alive, so the program sets Tomcat's class loader logger to ERROR.

The same rules in the WebFlux form, together with timeouts and token relay, were not run here:

YAML
spring:
  cloud:
    gateway:
      server:
        webflux:
          routes:
            - id: orders
              uri: http://orders:8080
              predicates:
                - Path=/api/orders/**
              metadata:
                connect-timeout: 1000          # milliseconds
                response-timeout: 3000
              filters:
                - StripPrefix=1
                - name: Retry
                  args:
                    retries: 2
                    methods: GET               # only idempotent requests
                    statuses: BAD_GATEWAY,SERVICE_UNAVAILABLE
                - name: CircuitBreaker
                  args:
                    name: orders
                    fallbackUri: forward:/fallback/orders
                - TokenRelay=                  # pass the user's OAuth2 token on
  • Per-route timeouts go in the route's metadata, in milliseconds; the gateway also has global defaults, connect-timeout and response-timeout under its httpclient properties. Without a response timeout, a hanging service holds gateway connections indefinitely.
  • The CircuitBreaker filter forwards to the fallback endpoint while the breaker is open, as in the program above.
  • TokenRelay works with spring-boot-starter-oauth2-client: the gateway handles the login, and forwards the user's access token to the services, which validate it as resource servers. It needs an identity provider and was not run.

Traps with gateways

  • Route order: as the second route table showed, a broad route defined first hides the specific ones after it.
  • Blocking code in the WebFlux gateway: a filter that calls a database or a blocking HTTP client stalls a Netty event-loop thread and, with it, many other requests. Use reactive clients in WebFlux filters, or the Web MVC gateway.
  • Lost client addresses: behind a load balancer, the gateway sees the balancer's address. Configure forwarded-header handling, or rate limits and audit logs keyed on the remote address all see one client.
  • Retries multiplied: a gateway that retries twice in front of services that also retry turns one failure into many calls. Retry in one layer.
  • The gateway as a monolith: business logic and data transformation in gateway filters couple every service to the gateway's release cycle. Keep filters to cross-cutting concerns.

Choosing a gateway setup

Gateway choices for common situations
SituationChoice
A new gateway for a Spring systemSpring Cloud Gateway Server WebFlux, or Server Web MVC for a servlet-based team
Routes known in advanceYAML routes with Path predicates, specific routes first
Routes computed from data or custom conditionsJava routes with RouteLocatorBuilder or router functions
Limit each API client's request rateRequestRateLimiter with Redis and a KeyResolver
Protect the system from a failing servicePer-route timeouts, Retry for idempotent methods, CircuitBreaker
User login with OAuth2 or OpenID ConnectOAuth2 client in the gateway, TokenRelay, resource servers behind it
Only TLS termination and simple routing on KubernetesAn ingress controller or the platform's gateway, without a Java gateway

A gateway pays for itself when several services share the same edge rules; for one or two services, an ingress or a load balancer is simpler. For the calls services make to each other behind the gateway, see declarative HTTP clients, and for following a request through the gateway and beyond, distributed tracing.