Introduction
Welcome back! In our last session, we successfully refactored our monolith into two distinct microservices: auth-service and blog-service, running on ports 8081 and 8082, respectively. This was a crucial step towards building a scalable, distributed system.
However, this refactoring introduced a new challenge: a client application (like our Next.js frontend) now needs to know the address of every single microservice. This is brittle, complex to manage, and poses a security risk.
Today, we will solve this by introducing an API Gateway. This gateway will act as a single, unified entry point—a front door—for all incoming requests. Its job is to inspect each request and intelligently route it to the correct downstream service. We will use Spring Cloud Gateway to build this component, a modern, non-blocking gateway designed for exactly this purpose.
MERN Stack Comparison
In the Node.js world, you might achieve this using a reverse proxy like Nginx or by creating a dedicated "Backend for Frontend" (BFF) Express application. The BFF would receive all client requests and then make server-to-server calls to the appropriate microservices. Spring Cloud Gateway fulfills this same role, providing a robust, configurable, and highly-performant solution right within the Spring ecosystem.
Why Do We Need an API Gateway?
An API Gateway is a standard pattern in microservice architectures. It sits between your clients and your backend services, providing a single point of entry and control.

The primary benefits are:
- Single Entry Point: Clients only need to know one address—the gateway's. This simplifies client-side configuration and deployment.
- Routing: The gateway acts as a smart traffic controller, directing requests based on paths, headers, or other attributes.
- Centralized Cross-Cutting Concerns: Functionality like authentication, rate limiting, logging, and caching can be handled at the gateway level instead of being duplicated in every microservice. We'll explore these features in later lessons.
To get a solid conceptual overview, let's start with a short video.
Building an API Gateway in Java with Spring Cloud Gateway
This video, 'Building an API Gateway in Java with Spring Cloud Gateway' by Dan Vega, provides an excellent explanation of what an API Gateway is and what problems it solves in a distributed system.
Watch the first 6 minutes and 39 seconds (00:00:00 - 06:39). Pay close attention to the explanation of cross-cutting concerns and the diagram illustrating the request lifecycle within the gateway.
Core Concepts of Spring Cloud Gateway
Spring Cloud Gateway's functionality is built on three key concepts that you'll define in your configuration. Let's use the clear definitions from the "Spring Cloud Gateway Routing for Microservices" article.
Spring Cloud Gateway Routing for Microservices
To understand how we'll configure our gateway, let's read the 'Anatomy of a Gateway Route' section from this article on labs64.io. It clearly breaks down the components we'll be using.
Read the section titled 'Anatomy of a Gateway Route'. Focus on the definitions of id, uri, predicates, and filters.
In short:
- Route: The main building block. It contains a destination (
uri) and the conditions to get there. - Predicate: The condition itself. It's a rule that evaluates an incoming request (e.g., "does the path start with
/api/auth/?"). If the predicate is true, the route is matched. - Filter: An action to modify the request or response. We'll explore these more in the next lesson.
Here's how they work together internally:

Your Task: Build and Configure the Gateway
Let's put theory into practice. We will create a new Spring Boot service for our gateway and configure it to route requests to our auth-service and blog-service.
1. Create the Gateway Project
First, we need a new project.
- Go to Spring Initializr.
- Create a new project with the following details:
- Project: Maven
- Group:
com.blog(or your chosen group ID) - Artifact:
gateway-service - Dependencies: Search for and add
Gateway.
- Generate the project, download it, and open it in your IDE alongside your other two services.
2. Configure the Gateway
We'll use the declarative YAML configuration, which is the most common approach for defining static routes.
- Open the
src/main/resources/application.ymlfile in yourgateway-serviceproject. - First, let's set the port for the gateway itself. We'll use
8080, the default HTTP port.server: port: 8080 - Now, let's define the routes. We need to add a section for
spring.cloud.gateway. We will create two routes, one for each of our downstream services.
Add the following configuration to your application.yml:
spring:
application:
name: gateway-service
cloud:
gateway:
routes:
- id: auth_service_route
uri: http://localhost:8081
predicates:
- Path=/api/v1/auth/**
- id: blog_service_route
uri: http://localhost:8082
predicates:
- Path=/api/v1/posts/**
Let's break this down:
auth_service_route:id: A unique name for this rule.uri: The destination. We're pointing directly to ourauth-service.predicates: A list of conditions. Here, we use thePathpredicate. It will match any request whose path starts with/api/v1/auth/.
blog_service_route:- Similarly, this rule matches any path starting with
/api/v1/posts/and forwards the request to ourblog-servicerunning on port 8082.
- Similarly, this rule matches any path starting with
To see this configuration being built step-by-step, you can refer back to the Dan Vega video.
Building an API Gateway in Java with Spring Cloud Gateway
The following segment of the video demonstrates exactly what we just did: configuring routes in application.yml using id, uri, and Path predicates.
Watch from 09:23 to 15:30. The video creates a route for a 'posts' service. Notice how the structure matches what we've just implemented for our auth-service and blog-service.
Running and Verifying the Full System
Now for the moment of truth. Let's run all three of our services:
auth-service(on port 8081)blog-service(on port 8082)gateway-service(on port 8080)
Once all three are running, open Postman. All your requests should now be directed to the gateway on port 8080.
-
Test the Auth Route: Send a
POSTrequest tohttp://localhost:8080/api/v1/auth/registerwith a new user's JSON body.- Expected Result: You should get a
201 Createdresponse. The gateway should have forwarded your request to theauth-service, which processed it. You can verify this by checking theuserstable in yourblog_auth_db.
- Expected Result: You should get a
-
Test the Blog Route: Send a
POSTrequest tohttp://localhost:8080/api/v1/postswith a JSON body to create a new post (remember you'll need theauthorIdfield).- Expected Result: You should get a
201 Createdresponse. The gateway forwarded this request to theblog-service. Verify by checking thepoststable in yourblog_content_db.
- Expected Result: You should get a
If both requests succeed, your gateway is working perfectly!
Debugging Task
You are testing your new setup. A request to POST http://localhost:8080/api/v1/auth/login returns a 404 Not Found from the gateway. However, if you bypass the gateway and send the same request directly to POST http://localhost:8081/api/v1/auth/login, it works correctly and returns a JWT.
Question: Based on our configuration, what is the most likely cause of this 404 error at the gateway level? How would you diagnose and fix it?
Click for the answer
The most likely cause is a misconfiguration in the `Path` predicate for the `auth_service_route` in the gateway's `application.yml`.Diagnosis: The gateway returns 404 because no route predicate matched the incoming request path /api/v1/auth/login.
Common Mistakes:
- Typo in the pattern: The predicate might be
Path=/api/v1/authentication/**instead ofPath=/api/v1/auth/**. - Incorrect wildcard: Using a single asterisk (
*) instead of a double asterisk (**). A path like/api/v1/auth/*would match/api/v1/auth/loginbut not/api/v1/auth/some/other/path. The double asterisk**matches any number of path segments. - Missing a path segment: The predicate might be
Path=/api/auth/**, missing the/v1/segment.
Fix: You would carefully inspect the Path predicate for the auth_service_route in your application.yml and ensure it exactly matches the path pattern of your incoming requests, which is Path=/api/v1/auth/**.
Conclusion
Excellent work! You have now set up the front door to your entire microservices architecture. You created a Spring Cloud Gateway service and configured it with declarative routes that direct traffic to the correct downstream services based on URL paths. This abstracts the internal complexity of our system from the outside world.
Key Takeaways:
- An API Gateway is a crucial component in a microservices architecture that acts as a single entry point.
- Spring Cloud Gateway allows you to define routing rules declaratively in
application.yml. - A
Routeconsists of a destinationuriandpredicates(conditions) that must be met for the route to be activated. - The
Pathpredicate is a powerful tool for routing requests based on their URL.
Preview of the Next Lesson:
Our current routing is a direct 1-to-1 proxy, which means our client-facing URLs still contain internal details like /api/v1/. In the next lesson, we will make our gateway even smarter by using Gateway Filters. We'll learn to configure routing rules that not only match paths but also modify them, allowing us to create cleaner, more user-friendly public URLs (e.g., /auth/login) that map to our internal service endpoints.