Why a Gateway Is Essential in Microservices and What It Actually Does
The article explains that a gateway serves as the unified entry point of a microservice system, handling routing, authentication, rate limiting, logging and protocol conversion, compares architectures with and without a gateway, details Spring Cloud Gateway's core concepts, shows configuration and custom auth filter code, and contrasts it with Zuul, providing interview‑ready insights and sample questions.
Interview Focus Points
Architecture design thinking : interviewers want to see if you understand the gateway’s role as the "unified front door" of a microservice system.
Depth of functional knowledge : the gateway is more than a router; it also handles authentication, rate‑limiting, circuit‑breaking, logging, etc.
Technology selection ability : be able to explain the essential differences between Spring Cloud Gateway and Zuul and why Gateway is the mainstream choice.
Core Answer
Without a gateway, a microservice architecture is like a building without a front door – any visitor can knock on any room, leading to chaos and security risks.
The gateway’s core purpose is to provide a unified entry for all external requests, centralising non‑business logic so each microservice can focus on its own domain.
Five Core Functions of a Gateway
Routing : forward requests to the appropriate microservice based on the request path (Predicate + Route).
Authentication : uniformly validate tokens and permissions via a GlobalFilter, avoiding duplicate checks in each service.
Rate Limiting & Circuit Breaking : protect downstream services from traffic spikes (e.g., using Sentinel’s RequestRateLimiter).
Logging & Monitoring : record request logs, response times and status codes centrally.
Protocol Conversion : translate external HTTP to internal RPC calls or vice‑versa, often via custom Filter s.
Deep Analysis
1. Why a Gateway Is Necessary
When there is no gateway, clients call each microservice directly, forcing every service to implement authentication, CORS, rate limiting, etc., which leads to duplicated code and exposed service addresses.
With a gateway, all requests first pass through the gateway, which handles these cross‑cutting concerns before routing to the target service, keeping service addresses hidden and allowing services to focus on business logic.
2. Spring Cloud Gateway Core Concepts
Spring Cloud Gateway is built around three concepts:
Route : a rule containing an ID, target URI, a set of predicates and a set of filters – essentially a forwarding rule.
Predicate : matching conditions such as Path=/order/**, Method=GET,POST, Header, Query, etc.
Filter : can be Pre (executed before routing) or Post (executed after the response), used for tasks like authentication, adding headers, logging, etc.
The full request flow is: request → iterate all routes → match predicates → execute Pre filters → forward to target service → execute Post filters → return response.
3. Route Configuration in Practice
# application.yml — Gateway route configuration
spring:
cloud:
gateway:
routes:
# Order service route
- id: order-service
uri: lb://order-service # load‑balanced service name from Nacos
predicates:
- Path=/api/order/**
- Method=GET,POST
filters:
- StripPrefix=1 # remove the first path segment (/api)
- AddRequestHeader=X-Source,gateway
# User service route
- id: user-service
uri: lb://user-service
predicates:
- Path=/api/user/**
filters:
- StripPrefix=1Key points: id uniquely identifies the route. uri with the lb:// prefix enables load‑balancing; the suffix is the service name registered in the discovery centre. predicates must satisfy all listed conditions for the route to be selected. filters apply transformations; StripPrefix=1 turns /api/order/xxx into /order/xxx.
4. Custom Global Authentication Filter (Typical Interview Code)
@Component
public class AuthGlobalFilter implements GlobalFilter, Ordered {
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
// 1. Get token from request header
String token = exchange.getRequest().getHeaders().getFirst("Authorization");
// 2. If token is missing, return 401
if (StringUtils.isBlank(token)) {
exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
return exchange.getResponse().setComplete();
}
// 3. Validate token (e.g., JWT parsing)
try {
Claims claims = JwtUtil.parseToken(token);
// Pass user info downstream via header
ServerHttpRequest request = exchange.getRequest().mutate()
.header("X-User-Id", claims.getSubject())
.build();
return chain.filter(exchange.mutate().request(request).build());
} catch (Exception e) {
exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
return exchange.getResponse().setComplete();
}
}
@Override
public int getOrder() {
return 0; // smaller number = higher priority
}
}Core takeaways:
Implement GlobalFilter so every request passes through the filter.
Implement Ordered to control execution order; lower numbers run earlier.
After successful validation, user information is added to the request header for downstream services to consume without re‑authenticating.
5. Gateway vs. Zuul Comparison
Programming model : Zuul 1.x uses synchronous blocking (Servlet); Spring Cloud Gateway uses asynchronous non‑blocking (WebFlux + Netty).
Performance : Zuul relies on a thread‑pool model and is generally average; Gateway achieves high throughput with few threads.
Filter types : Zuul supports pre/route/post/error; Gateway only needs pre/post, making it simpler.
Implementation : Zuul is built on ZuulFilter; Gateway uses GlobalFilter + GatewayFilter.
Rate‑limiting support : Zuul requires external integration; Gateway has built‑in RequestRateLimiter.
Official support : Zuul 1.x is deprecated; Spring Cloud officially recommends Gateway.
Community activity : Zuul’s community is low; Gateway’s community is high.
In a sentence: Gateway is based on reactive programming (Reactor + Netty), asynchronous and non‑blocking, delivering performance far beyond Zuul’s synchronous model, and Zuul is no longer on the Spring Cloud roadmap.
High‑Frequency Interview Follow‑Ups
What types of filters does Gateway provide? GlobalFilter: applies to all routes (e.g., authentication, logging). GatewayFilter: route‑level filter for specific business logic.
How does Gateway implement rate limiting?
Built‑in RequestRateLimiter based on Redis token‑bucket; production often combines with Sentinel for richer strategies.
Can Gateway become a performance bottleneck?
Theoretically yes, as the entry point, but its Netty‑based async model yields very high single‑node throughput; scaling is achieved by multiple instances behind Nginx.
What’s the difference between Gateway and Nginx?
Nginx is a generic reverse proxy with extremely high performance but limited to low‑level functions.
Gateway is a microservice‑oriented gateway with built‑in service discovery, dynamic routing, etc.; they are often used together (Nginx outside, Gateway inside).
Common Interview Variants
"What are the core components of Spring Cloud Gateway?"
"What is the difference between Gateway and Zuul?"
"How to implement unified authentication in Gateway?"
"Explain the purpose of Predicate and Filter in Gateway routing."
Memory Mnemonics
Gateway five functions : Routing, Authentication, Rate‑Limiting, Logging, Protocol Conversion.
Gateway three core concepts : Route, Predicate, Filter.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Java Architect Handbook
Focused on Java interview questions and practical article sharing, covering algorithms, databases, Spring Boot, microservices, high concurrency, JVM, Docker containers, and ELK-related knowledge. Looking forward to progressing together with you.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
