API Routing with Spring Cloud Gateway

Introduction

When building microservices, routing requests correctly is one of the most important pieces of the architecture. Instead of calling services directly, applications often rely on an API gateway to route traffic, apply rules, handle authentication, and enforce policies. Spring Cloud Gateway makes this process simple, fast, and reactive. In this post, you’ll learn how it works, how to define routes, and how to apply filters to control traffic flow.

What Is Spring Cloud Gateway?

Spring Cloud Gateway is a lightweight, reactive API gateway built on top of Spring WebFlux. It provides a simple way to route requests to downstream services while applying filters such as authentication, rate limiting, logging, and header manipulation. Because it uses a reactive engine, it offers strong performance even under heavy load.

Key Features

  • Efficient API routing
  • Reactive and non-blocking architecture
  • Support for custom filters
  • Built-in rate limiting and path rewriting
  • Easy integration with Spring Cloud Discovery (Eureka)

As a result, it’s a great choice for teams building microservice architectures with Spring.

How Routing Works

A route in Spring Cloud Gateway defines:

  • a predicate → when the route should match
  • a URI → where the gateway should send the request
  • optional filters → actions applied before or after the request

Here’s a simple route configuration using YAML:

spring:
  cloud:
    gateway:
      routes:
        - id: user-service
          uri: http://localhost:8081
          predicates:
            - Path=/users/**

With this setup, any request starting with /users/ is routed to the user service.

Adding Filters

Filters allow you to customize routing behavior. You can modify headers, rewrite paths, log requests, or apply authentication.

Example: Adding Headers

filters:
  - AddRequestHeader=App-Version, v1

Example: Path Rewriting

filters:
  - RewritePath=/api/(?<segment>.*), /$\\{segment}

This filter removes /api from the incoming route before forwarding the request.

Example: Rate Limiting

Rate limiting is built in through Redis:

filters:
  - name: RequestRateLimiter
    args:
      redis-rate-limiter.replenishRate: 10
      redis-rate-limiter.burstCapacity: 20

This setup limits traffic to protect downstream services.

Using Java to Configure Routes

If you prefer Java configuration, you can define routes using a RouteLocator:

@Bean
public RouteLocator customRoutes(RouteLocatorBuilder builder) {
    return builder.routes()
        .route("order-service", r -> r.path("/orders/**")
            .filters(f -> f.addRequestHeader("X-Service", "Order"))
            .uri("http://localhost:8082"))
        .build();
}

This approach gives you more flexibility and allows you to attach logic programmatically.

Integrating with Service Discovery

Spring Cloud Gateway works smoothly with Eureka or other discovery services. Instead of hardcoding URIs, you can route using service IDs:

uri: lb://order-service

Because of this, your gateway automatically routes traffic to available instances.

Gateway as a Security Layer

A gateway is often the first line of defense. You can apply:

  • JWT authentication
  • API keys
  • OAuth2 token validation
  • IP allow/deny lists
  • Role-based access rules

Spring Security integrates directly with WebFlux, so adding authentication filters is straightforward.

Example: Securing a Route

spring:
  cloud:
    gateway:
      routes:
        - id: secure-route
          uri: lb://secure-service
          predicates:
            - Path=/secure/**
          filters:
            - TokenRelay

When to Use Spring Cloud Gateway

Use it when you need:

  • A lightweight gateway for microservices
  • A reactive, high-performance router
  • Request filtering and transformation
  • Seamless integration with Spring Cloud
  • Easy service discovery routing

However, for extremely advanced traffic control, you might look at tools like Kong or Istio.

Final Thoughts

Spring Cloud Gateway is an excellent choice for microservice routing in Spring-based systems. It provides a simple, flexible, and reactive way to route traffic, apply filters, and secure your APIs. Start with basic routes, then enhance them with filters, service discovery, and rate limiting. To explore more Spring backend tools, read Building Reactive APIs with Spring WebFlux. For detailed configuration guides, visit the Spring Cloud Gateway documentation.

Leave a Comment

Scroll to Top