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:
| Form | Starter | Runs on | Best for |
|---|---|---|---|
| Server WebFlux, the original | spring-cloud-starter-gateway-server-webflux | Spring WebFlux and Netty | High numbers of concurrent connections, streaming, the full set of filters |
| Server Web MVC | spring-cloud-starter-gateway-server-webmvc | Spring MVC (WebMvc.fn) on Tomcat or Jetty | Teams 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-webfluxserver-webmvcspring.cloud.gateway.server.webflux.routesspring.cloud.gateway.server.webmvc.routesspring-cloud-starter-gatewayspring.cloud.gateway.routesspring-boot-starter-webmvcspring-boot-starter-restclientspring-cloud-starter-gateway-server-webmvcspring-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
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");
}
}
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
matched the Java route./api/orders/42 removedstripPrefix(1) , so the orders service received/api , and/orders/42 addedaddRequestHeader .X-Request-Source: gateway matched the route from properties,/api/stock/book withPath=/api/stock/** . It reached the inventory service asStripPrefix=1 , without/stock/book , because that filter belongs to the other route.X-Request-Source- Both backends received
andX-Forwarded-Prefix: /api , so a service can still build links that point through the gateway. The gateway added these headers only becauseX-Forwarded-For: 127.0.0.1 matched the caller's address: in a trial run without that property, notrusted-proxies header reached the backend.X-Forwarded-* matched no route and got 404 from the gateway itself./api/users/7
The Java form uses three static helpers: routehttp()before(uri(...))beforeafterfilter
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
is the shortcut form: the predicate name,Path=/api/orders/** , and its arguments separated by commas. Every predicate and filter also has a fully expanded form with= andname , needed for filters with many arguments.args- A
starting withuri resolves the service name through Spring Cloud LoadBalancer and a registry such as Eureka, as on thelb://Eureka page. - Routes can also be defined in Java for the WebFlux form, with a
bean, which helps when routes are computed or need custom predicates.RouteLocatorBuilder
How a route is chosen
The PathPathPatternParserStripPrefix=1
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");
}
}
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
matched the specific route/api/orders/42 and captured/api/orders/{id} . Gateway filters can use such variables, for exampleid=42 .SetPath=/orders/{id} has one segment too many for/api/orders/42/lines , so it fell through to{id} , where/api/orders/** matches any number of segments.** matched only the catch-all/api/customers/7 and went to the legacy system./api/** matched nothing, and a gateway answers such a request with 404./health- In the second table, the catch-all route came first, and it took
away from the orders service. Order specific routes before general ones, or give them an explicit/api/orders/42 value; the first match wins, not the best one.order
StripPrefix=1/apiX-Forwarded-Prefix
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
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;
}
}
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
, with/orders/42 ; the orders service's answer came back with the edge's ownX-Forwarded-Prefix: /api header.X-Served-By - 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.
matched no route and got 404 from the edge itself./api/stock/book
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 ConnectionX-Forwarded-*ForwardedX-Forwarded-Prefix
Rate limiting with a token bucket
The gateway's RequestRateLimiterburstCapacityreplenishRate
// 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));
}
}
}
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.
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}"
@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-reactivespring.cloud.gateway.filter.request-rate-limiter.deny-empty-keyrequestedTokens
Resilience at the edge
The gateway is the natural place for retries and circuit breakers on calls into the system. This program puts a retrycircuitBreaker
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");
}
}
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
series, so the gateway retried; the client saw only the final success.SERVER_ERROR - 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".
tells the breaker to treat a 503 response as a failure.setStatusCodes("503") - 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
, a path the gateway handles itself. In a trial run, the stringsetFallbackPath("/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"."forward:/fallback/stock"
Retry only methods that are safe to repeat, as setMethods(Set.of(HttpMethod.GET))POSTcircuitBreakerERROR
The same rules in the WebFlux form, together with timeouts and token relay, were not run here:
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
, in milliseconds; the gateway also has global defaults,metadata andconnect-timeout under itsresponse-timeout properties. Without a response timeout, a hanging service holds gateway connections indefinitely.httpclient - The
filter forwards to the fallback endpoint while the breaker is open, as in the program above.CircuitBreaker works withTokenRelay : 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.spring-boot-starter-oauth2-client
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
| Situation | Choice |
|---|---|
| A new gateway for a Spring system | Spring Cloud Gateway Server WebFlux, or Server Web MVC for a servlet-based team |
| Routes known in advance | YAML routes with Path |
| Routes computed from data or custom conditions | Java routes with RouteLocatorBuilder |
| Limit each API client's request rate | RequestRateLimiterKeyResolver |
| Protect the system from a failing service | Per-route timeouts, RetryCircuitBreaker |
| User login with OAuth2 or OpenID Connect | OAuth2 client in the gateway, TokenRelay |
| Only TLS termination and simple routing on Kubernetes | An 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