API Gateway
AdvancedSpring 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).
<!-- 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_GATEWAYCustom 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.
// 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 AriaWhat is an API gateway and what concerns does it handle?
How does Spring Cloud Gateway differ from Zuul?
What is the difference between a GlobalFilter and a GatewayFilter?
How would you implement rate limiting at the API gateway level?
How do you pass the authenticated user's ID from the gateway to downstream services securely?
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.