Home/Learn/Spring Boot/API Gateway

API Gateway

Advanced
Production & Advanced

Spring Cloud Gateway is a reactive API gateway — it routes external traffic to microservices, applies cross-cutting filters (auth, rate limiting, logging), and is configured either in YAML or via Java DSL.

Overview

An API gateway sits in front of all microservices and handles concerns that would otherwise be duplicated in each service: authentication, rate limiting, SSL termination, request routing, and observability. Spring Cloud Gateway is built on Spring WebFlux (reactive, non-blocking). Each Route has a predicate (when to match) and a list of filters (what to do). Filters can modify the request before forwarding and the response before returning.

Route Configuration

Routes are configured in application.yml or programmatically with RouteLocatorBuilder. A route = Predicate (match condition) + Filters (transformations) + URI (backend).

YAML — Spring Cloud Gateway route configuration
<!-- pom.xml -->
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>

# application.yml — declarative route configuration
spring:
  cloud:
    gateway:
      routes:
        - id: auth-service
          uri: http://auth-service:8080
          predicates:
            - Path=/api/v1/auth/**
          filters:
            - StripPrefix=0   # keep the path as-is

        - id: course-service
          uri: http://course-service:8080
          predicates:
            - Path=/api/v1/courses/**
            - Method=GET,POST
          filters:
            - AddRequestHeader=X-Gateway, spring-cloud-gateway
            - RewritePath=/api/v1/courses/(?<segment>.*), /courses/${segment}
            - CircuitBreaker=name=course-cb,fallbackUri=forward:/fallback

        - id: user-service
          uri: lb://user-service    # lb:// = Spring Cloud LoadBalancer
          predicates:
            - Path=/api/v1/users/**
          filters:
            - name: Retry
              args:
                retries: 3
                methods: GET
                statuses: BAD_GATEWAY

Custom Filter — JWT Validation at the Gateway

A global filter runs on every request. Validate the JWT at the gateway and forward the user ID as a header to downstream services, eliminating per-service JWT parsing.

Java — GlobalFilter for JWT validation and header forwarding
// Global pre-filter — runs on every route
@Component
public class JwtGatewayFilter implements GlobalFilter, Ordered {

    private final JwtService jwtService;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();

        // Skip auth for public paths
        String path = request.getPath().toString();
        if (path.startsWith("/api/v1/auth/")) {
            return chain.filter(exchange);
        }

        String authHeader = request.getHeaders().getFirst("Authorization");
        if (authHeader == null || !authHeader.startsWith("Bearer ")) {
            exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
            return exchange.getResponse().setComplete();
        }

        String token = authHeader.substring(7);
        if (!jwtService.isValid(token)) {
            exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
            return exchange.getResponse().setComplete();
        }

        // Forward user ID to downstream service as header
        String userId = jwtService.extractUserId(token);
        ServerHttpRequest mutated = request.mutate()
            .header("X-User-Id", userId)
            .build();

        return chain.filter(exchange.mutate().request(mutated).build());
    }

    @Override public int getOrder() { return -100; } // run early
}

Key Points to Remember

  • 1Spring Cloud Gateway is reactive (WebFlux) — do not mix it with Spring MVC/Tomcat blocking code.
  • 2Routes = Predicates (when to match) + Filters (what to transform) + URI (where to forward).
  • 3Use lb://service-name URIs with Spring Cloud LoadBalancer for client-side load balancing.
  • 4GlobalFilter applies to all routes; GatewayFilter applies to specific routes.
  • 5Validate JWTs at the gateway and forward the user ID as a trusted header to downstream services.
  • 6Circuit breaker + retry filters in the gateway protect against downstream service failures.

Interview Questions

Sign in to ask Aria
1

What is an API gateway and what concerns does it handle?

EasyAmazon
2

How does Spring Cloud Gateway differ from Zuul?

MediumThoughtWorks
3

What is the difference between a GlobalFilter and a GatewayFilter?

MediumAtlassian
4

How would you implement rate limiting at the API gateway level?

HardNetflix
5

How do you pass the authenticated user's ID from the gateway to downstream services securely?

MediumGoldman Sachs

Ask Aria about API Gateway

Your personal AI tutor — ask anything about this concept

Revision Status

Personal Notes

Sign in to save personal notes for this topic.

Discussion

Sign in to join the discussion.

Loading discussion…