skip to content

Routes & Predicates

A route is a predicate plus a destination plus filters, declared in YAML or with the Java DSL, matching on path, host, method, headers, query or time. Interviewers ask you to route by header or path prefix and to reason about which route matches first.

part ofSpring Frameworkoverview, primer and where to startread it →
on this pageshow

questions

5

What is a route in Spring Cloud Gateway, and what are its parts?

level: juniorimportance: must knowfreq 70%

answer

  1. id + uri + predicates + filters
  2. predicates = match, filters = transform
  3. all predicates AND-ed
  4. YAML routes or RouteLocator bean
  5. uri needs a scheme (http://, lb://)

basics

~20 s

A route is the basic building block: an id, a destination uri, a set of predicates that decide if a request matches, and optional filters. If all predicates match, the request is forwarded to the uri.

solid answer

~40 s

In Spring Cloud Gateway a route is the fundamental routing unit made of four things: an id (a unique name), a uri (where to forward the request), predicates, and filters. Predicates are conditions on the incoming request (path, host, method, headers, query params, time). When every predicate on a route matches the exchange, that route is selected and the request is proxied to its uri; filters can then modify the request or response (add headers, strip prefixes, rate-limit). You declare routes either in application.yml under spring.cloud.gateway.routes or programmatically with a RouteLocator bean built via RouteLocatorBuilder. Common predicate factories are Path, Host, Method, Header, Query, and the time-based After/Before/Between.

code

yaml · 10 lines
yaml
spring:
  cloud:
    gateway:
      routes:
        - id: user-service        # unique id
          uri: http://localhost:8081  # forward destination
          predicates:
            - Path=/users/**        # match condition
          filters:
            - StripPrefix=1         # optional transform

go deeper

for a junior

Must know the four parts (id/uri/predicates/filters) and that predicates decide matching.

for a middle

Should know both YAML and DSL declaration and that predicates AND together.

for a senior

Should discuss handler mapping selecting the first matching route by order.

for a principal

Frames routes as declarative match+transform pipeline and reasons about ordering/precedence at scale.

**Spring Cloud Gateway** is an API gateway built on Spring WebFlux and Project Reactor (there is also a newer Spring Cloud Gateway MVC/Server variant on the blocking stack, but the concepts are the same). Its job is to sit in front of your services and route each incoming HTTP request to the right downstream service, optionally transforming it. The central concept is the **Route**. A route has four parts: - **id** — a unique string identifying the route. If you don't set it, an auto-generated UUID is used. - **uri** — the destination the request is forwarded to, e.g. `http://localhost:8081` or, with service discovery, `lb://user-service` (the `lb://` scheme means load-balance across instances registered in discovery). - **predicates** — a list of conditions evaluated against the incoming `ServerWebExchange` (the request). Each condition is produced by a **RoutePredicateFactory** (e.g. `PathRoutePredicateFactory`). A route matches only when **all** of its predicates return true (they are combined with logical AND). - **filters** — optional transformations applied to the request going out or the response coming back (add/remove headers, `StripPrefix`, `RewritePath`, rate limiting, circuit breakers). **How a request flows:** the `RoutePredicateHandlerMapping` receives the exchange, asks each route's combined predicate whether it matches, and picks the first matching route (respecting the route `order`). The `FilteringWebHandler` then runs the route's filter chain and proxies to the `uri`. **Two ways to declare routes:** 1. **YAML** under `spring.cloud.gateway.routes` — each entry has `id`, `uri`, `predicates` (using shortcut syntax like `Path=/api/**`), and `filters`. 2. **Java/Kotlin DSL** — define a `RouteLocator` `@Bean` using `RouteLocatorBuilder`, calling `.route(...)` with a lambda that chains predicate methods like `.path("/api/**")` and ends with `.uri(...)`. **Common predicate factories** in this leaf: `Path` (URL path patterns), `Host` (Host header patterns), `Method` (HTTP verb), `Header` (header presence/regex), `Query` (query param presence/regex), and the temporal `After` / `Before` / `Between` (match relative to a `ZonedDateTime`). **Gotchas for beginners:** a route with no predicates matches nothing meaningful; the `uri` needs a scheme; and predicates are AND-combined, so adding more predicates narrows, never widens, what matches.

  • What is the difference between a predicate and a filter?
    A predicate decides whether a request matches the route (returns true/false, never modifies the request). A filter runs only on matched routes and modifies the request or response, e.g. adding headers or stripping a path prefix.
  • What does the lb:// scheme in a route uri mean?
    It tells the gateway to resolve the target via a load balancer / service discovery (e.g. lb://user-service picks a healthy instance registered under 'user-service') rather than a fixed host:port.

saying these in an interview costs you the question

  • Saying predicates can modify the request (they only test it)
  • Thinking multiple predicates are OR-ed by default
  • Confusing route uri with the incoming request path

context

open as a page

Walk through the Path, Host, Method, Header, and Query predicate factories — what each matches and how they combine.

level: middleimportance: must knowfreq 60%

basics

~20 s

Path matches the URL path (Ant-style / PathPattern). Host matches the Host header. Method matches the HTTP verb. Header matches a header's presence/regex. Query matches a query parameter's presence/regex. Multiple predicates on one route are AND-ed.

open as a page

How do you define the same route in YAML versus the Java RouteLocatorBuilder DSL?

level: middleimportance: should knowfreq 55%

basics

~10 s

In YAML you list routes under spring.cloud.gateway.routes with shortcut predicates like Path=/api/. In Java you declare a RouteLocator @Bean using RouteLocatorBuilder, chaining .route(id, r -> r.path("/api/").uri("...")). Both produce the same routes.

open as a page

Explain the After/Before/Between temporal predicates and how Path/Host capture variables for downstream use.

level: seniorimportance: should knowfreq 40%

basics

~20 s

After, Before, and Between compare the current time to a ZonedDateTime: After matches requests after it, Before matches before it, Between matches within a window. Path and Host patterns can capture named variables (like {segment}) that filters can reuse.

open as a page

When several routes could match a request, how does the gateway decide which one wins, and how is route order controlled?

level: principalimportance: should knowfreq 35%

basics

~20 s

The RoutePredicateHandlerMapping evaluates routes in order and picks the first whose combined predicate matches. Routes are sorted by their order field (lower = higher priority); if unset, they keep their declared order. First match wins — later routes aren't tried.

open as a page