Skip to main content

Documentation Index

Fetch the complete documentation index at: https://resources.devweekends.com/llms.txt

Use this file to discover all available pages before exploring further.

API Gateway

If you have 10 microservices, you don’t want the frontend to know 10 different URLs. You need a single entry point. Spring Cloud Gateway is the standard, built on top of Spring WebFlux (Non-blocking I/O).

1. Why an API Gateway?

  • Routing: Single domain (api.myapp.com) routes to multiple services.
  • Security: Centralized Authentication/Authorization (OAuth2).
  • Rate Limiting: Protect your backend from DDoS.
  • Monitoring: Log every request entering the system.

2. Setup

  1. New Spring Boot Project.
  2. Dependencies: spring-cloud-starter-gateway, spring-cloud-starter-netflix-eureka-client.
Note: Do NOT include spring-boot-starter-web (Tomcat). Gateway uses Netty.

3. Configuration (Routing)

You can route requests based on paths. application.yml:
server:
  port: 8080

spring:
  application:
    name: API-GATEWAY
  cloud:
    gateway:
      discovery:
        locator:
          enabled: true # Automatically create routes for services in Eureka
          lower-case-service-id: true
      routes:
        - id: user-service
          uri: lb://USER-SERVICE # lb = Load Balanced
          predicates:
            - Path=/api/v1/users/**
          filters:
             - RewritePath=/api/v1/users/(?<segment>.*), /users/$\{segment}
Now, a request to localhost:8080/api/v1/users/1 is forwarded to USER-SERVICE/users/1.

4. Custom Filters

You can write Global Filters to intercept every request (e.g., logging).
@Component
public class LoggingFilter implements GlobalFilter {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        System.out.println("Request Path: " + exchange.getRequest().getPath());
        
        // Pre-processing
        return chain.filter(exchange)
            .then(Mono.fromRunnable(() -> {
                // Post-processing
                System.out.println("Response Status: " + exchange.getResponse().getStatusCode());
            }));
    }
}

5. Gateway Authentication

Using Spring Security at the gateway level.
@Bean
public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
    http
        .csrf(ServerHttpSecurity.CsrfSpec::disable)
        .authorizeExchange(exchanges -> exchanges
            .pathMatchers("/public/**").permitAll() // Public endpoints
            .anyExchange().authenticated() // Everything else requires auth
        )
        .oauth2ResourceServer(oauth2 -> oauth2.jwt(Customizer.withDefaults()));
    
    return http.build();
}
This verifies the JWT Token before the request even reaches your microservices.

6. How it Works (Internal Flow)

Spring Cloud Gateway is built on the Reactor Netty (Non-blocking) server.

7. Rate Limiting (Redis)

Spring Cloud Gateway has a built-in RequestRateLimiter usage Redis and the Token Bucket Algorithm. Dependency: spring-boot-starter-data-redis-reactive. Config:
spring:
  cloud:
    gateway:
      routes:
        - id: user_service
          uri: lb://USER-SERVICE
          filters:
            - name: RequestRateLimiter
              args:
                redis-rate-limiter.replenishRate: 10 # Tokens added per second
                redis-rate-limiter.burstCapacity: 20 # Max tokens in bucket
                key-resolver: "#{@userKeyResolver}"
This ensures no single user can overload your system.