Gateway Filters
Custom GlobalFilter and GatewayFilter, pre/post logic, ordered filter chains
- Write a custom GlobalFilter for cross-cutting auth token validation
- Chain filters with Ordered to control execution order
- Apply route-scoped GatewayFilter factories
Series Context:
This is part of a Spring Boot Microservices series. Previous sessions covered routing and load balancing in API Gateway. This session covers Filters — including Global Filters, Route-Specific Filters, and how to implement authentication, circuit breaker, retry, and rate limiting.
Table of Contents
- What is a Filter in API Gateway?
- Types of Filters
- Complete Request Lifecycle in API Gateway
- Filter Ordering
- Pre-existing Global Filters
- Writing a Custom Global Filter — JWT Authentication
- Route-Specific Filters — Pre-existing Filters
- Retry Filter
- Circuit Breaker Filter
- Rate Limiter Filter
- Writing a Custom Route-Specific Filter
- Summary Decision Table
- Interview Notes
- Practice Questions
1. What is a Filter in API Gateway?
Overview
In Spring Cloud Gateway, a filter is a component that can intercept and modify HTTP requests and responses as they pass through the gateway. Filters sit between the client and your microservices, allowing you to apply cross-cutting concerns (authentication, logging, rate limiting, circuit breaking, header manipulation, etc.) in one centralized place — without modifying individual microservices.
Why This Concept Exists
In a microservices architecture, you might have dozens of services. If each service independently handles authentication, logging, retries, and circuit breaking, you get massive code duplication and inconsistency. An API Gateway with filters solves this by:
- Applying shared logic once, at the gateway level
- Keeping individual microservices focused on business logic
- Allowing centralized control over security, resilience, and observability
Real-world Analogy
Think of an API Gateway as a security checkpoint at an airport. Every passenger (request) must pass through the checkpoint (global filters) regardless of destination. Once cleared, passengers go to their specific gate (route-specific filters) where additional checks may apply (e.g., customs for international flights).
2. Types of Filters
Spring Cloud Gateway provides two categories of filters:
| Type | Scope | Applied To | Typical Use Cases |
|---|---|---|---|
| Global Filter | All requests | Every request passing through the gateway | Authentication, Logging, Tracing |
| Route-Specific Filter (Gateway Filter) | Selected requests | Only requests matching a specific route | Rate Limiting, Circuit Breaker, Retry, Header Manipulation |
Global Filters
Use cases:
- JWT authentication (you want to validate tokens for all incoming requests)
- Logging (you want to log every request/response)
- Request tracing / correlation ID injection
Route-Specific Filters
Use cases:
- Different circuit breaker configurations per microservice (Product Service vs Order Service may have different thresholds)
- Rate limiting on specific endpoints only
- Retry only on idempotent routes (GET/DELETE)
- Adding/removing headers specific to one service
3. Complete Request Lifecycle in API Gateway
This is the full flow of a request from client to microservice and back. Understanding this flow is essential for working effectively with filters.
Example Request
1Client → GET http://localhost:8083/products/1Here, 8083 is the API Gateway port.
Flow Diagram
Step-by-Step Breakdown
Step 1 — Dispatcher Handler The request hits the API Gateway and is first received by the DispatcherHandler. This is Spring's central dispatcher, similar to what DispatcherServlet does in Spring MVC.
Step 2 — Route Mapping Handler The Route Mapping Handler inspects the request path (/products/1) and matches it against the routes defined in application.properties.
1# application.properties — route definitions2spring.cloud.gateway.routes[0].id=route03spring.cloud.gateway.routes[0].uri=lb://PRODUCT-SERVICE4spring.cloud.gateway.routes[0].predicates[0]=Path=/products/**5
6spring.cloud.gateway.routes[1].id=route17spring.cloud.gateway.routes[1].uri=lb://ORDER-SERVICE8spring.cloud.gateway.routes[1].predicates[0]=Path=/orders/**Since the path is /products/1, it matches route0 → a Route Object is created.
Step 3 — Global Filter Pre Logic Every global filter runs its pre logic in order. Pre logic runs BEFORE the request is forwarded to the microservice.
Step 4 — Route-Specific Filter Pre Logic Filters specific to the matched route run their pre logic.
Step 5 — Route to Request URL Filter (Global, order=10,000) This special global filter resolves the actual microservice URL. Since the URI is lb://PRODUCT-SERVICE (load balancer), it:
- Contacts the Service Discovery (e.g., Eureka)
- Gets the list of available instances
- Picks one instance via load balancing
- Replaces the URI with the actual instance URL (e.g.,
http://192.168.1.10:8081)
Step 6 — Netty Routing Filter (Global, very high order) This filter actually invokes the microservice using the resolved URL. It is an HTTP client embedded in the gateway.
Step 7 — Microservice processes the request and returns a response
Step 8 — Response travels back through filters in REVERSE order
- Route-specific filters execute their post logic (innermost first)
- Global filters execute their post logic
Step 9 — Netty Write Response Filter (Global, order=-1) This special global filter sends the final response back to the client. Because its order is -1 (very high priority), it runs first during the pre phase (doing nothing there) but runs last during the post phase — exactly when we need to send the response.
Pre vs Post Logic Code Pattern
Understanding how pre and post logic works in a filter:
1@Override2public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {3
4 // ============ PRE FILTER LOGIC ============5 // Everything here runs BEFORE the request reaches the microservice6 System.out.println("PRE LOGIC: Validating token...");7
8 return chain.filter(exchange) // Pass request to next filter in chain9 .then(Mono.fromRunnable(() -> {10 // ============ POST FILTER LOGIC ============11 // Everything here runs AFTER the microservice responds12 System.out.println("POST LOGIC: Response received, logging...");13 }));14}chain.filter(exchange) is asynchronous — it does not block. The .then(Mono.fromRunnable(...)) ensures post logic runs only after the async chain completes and the response arrives. This is why we use Mono.fromRunnable() for post logic.4. Filter Ordering
Why Ordering Matters
Every filter — whether global or route-specific — is assigned an order value. This determines execution sequence.
| Order Value | Priority | Execution |
|---|---|---|
| Lower number (e.g., -1, 0) | Higher priority | Runs earlier in the chain |
| Higher number (e.g., 10000) | Lower priority | Runs later in the chain |
Built-in Filter Order Values
| Filter | Order Value | Purpose |
|---|---|---|
NettyWriteResponseFilter | -1 | Sends response to client — must run last in post phase |
| Custom Global Filters | You control it | Authentication, Logging etc. |
| Route-Specific Filters | 0, 1, 2... (by index) | Route-level concerns |
RouteToRequestUrlFilter | 10,000 | Resolves lb:// URI — must run late |
NettyRoutingFilter | Very high | Actually calls the microservice — must be last |
Why Global Filters Run Before Route-Specific Filters (Generally)
Most global filters (like authentication) intentionally get low order values so they run early. Route-specific filters get higher values (0, 1, 2 by index). This is why global filters generally precede route-specific filters.
However, RouteToRequestUrlFilter and NettyRoutingFilter are exceptions — they are global filters but have very high order values so they run late (after all other filters).
Default Ordering Behavior
1Global Filters (no order defined) → lowest precedence (run last)2
3Route-Specific Filters (no order defined) → assigned index: 0, 1, 2, 3...4 Filter 0 → order 05 Filter 1 → order 16 Filter 2 → order 2Sequence Diagram Filter Execution Order
5. Pre-existing Global Filters
Spring Cloud Gateway ships with several built-in global filters that run automatically:
| Filter | Description |
|---|---|
NettyWriteResponseFilter | Writes the final response back to the client |
RouteToRequestUrlFilter | Converts lb://SERVICE-NAME to a real URL via service discovery |
NettyRoutingFilter | Executes the actual HTTP call to the downstream microservice |
ReactiveLoadBalancerClientFilter | Handles client-side load balancing |
WebsocketRoutingFilter | Routes WebSocket connections |
These run transparently. You don't configure them — they're always active.
6. Writing a Custom Global Filter JWT Authentication
Use Case
You want to validate a JWT token on every request to the gateway (except the /auth endpoint, which is used to create tokens).
Why a Global Filter?
Since authentication must apply to all routes, a global filter is the right choice. You don't want to repeat this logic for each route.
Implementation
1package com.example.gateway.filter;2
3import org.springframework.cloud.gateway.filter.GatewayFilterChain;4import org.springframework.cloud.gateway.filter.GlobalFilter;5import org.springframework.core.Ordered;6import org.springframework.http.HttpStatus;7import org.springframework.stereotype.Component;8import org.springframework.web.server.ServerWebExchange;9import reactor.core.publisher.Mono;10
11@Component // ① Managed by Spring Boot (bean)12public class JwtAuthGlobalFilter implements GlobalFilter, Ordered { // ② Implements both interfaces13
14 @Override15 public int getOrder() {16 return -1; // ③ Low value = high priority = runs early in the filter chain17 }18
19 @Override20 public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {21
22 // ④ Extract the request path23 String path = exchange.getRequest().getURI().getPath();24
25 // ⑤ Skip authentication for /auth endpoint (token creation)26 if (path.equals("/auth")) {27 return chain.filter(exchange); // Pass through without checking token28 }29
30 // ⑥ Extract the Authorization header31 String authHeader = exchange.getRequest()32 .getHeaders()33 .getFirst("Authorization");34
35 // ⑦ If header is missing, reject the request36 if (authHeader == null) {37 exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);38 return exchange.getResponse().setComplete(); // Stop processing39 }40
41 // ⑧ Extract the token (typically "Bearer <token>")42 String token = authHeader.replace("Bearer ", "");43
44 try {45 // ⑨ Verify the JWT token (your custom verification logic)46 verifyJwtToken(token);47
48 // ⑩ Token is valid — pass to next filter (PRE LOGIC complete)49 return chain.filter(exchange)50 .then(Mono.fromRunnable(() -> {51 // ⑪ POST FILTER LOGIC — runs after microservice responds52 System.out.println("POST FILTER: Response returned for path: " + path);53 }));54
55 } catch (Exception e) {56 // ⑫ Token invalid — reject57 exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);58 return exchange.getResponse().setComplete();59 }60 }61
62 private void verifyJwtToken(String token) {63 // JWT verification logic (using jjwt or spring-security)64 // Refer to JWT Authentication video for full implementation65 // This will throw an exception if the token is invalid66 }67}Line-by-Line Explanation
| Line/Block | Explanation |
|---|---|
@Component | Registers this class as a Spring Bean — Spring Boot manages its lifecycle |
implements GlobalFilter | Marks this as a global filter; must override filter() method |
implements Ordered | Allows us to define execution priority via getOrder() |
getOrder() { return -1; } | Returns -1 (high priority) — this filter runs very early in the chain |
ServerWebExchange exchange | Represents the full HTTP request + response context in reactive Spring |
GatewayFilterChain chain | Represents the remaining filters; calling chain.filter(exchange) passes control forward |
path.equals("/auth") | Bypass check: if endpoint is /auth, don't require a token (it's the login/token-creation endpoint) |
getFirst("Authorization") | Reads the Authorization HTTP header |
setStatusCode(UNAUTHORIZED) | Sets HTTP 401 response status |
setComplete() | Terminates request processing — no further filters run |
chain.filter(exchange).then(Mono.fromRunnable(...)) | Asynchronously passes to next filter; the .then() block is the post-filter logic |
Mono.fromRunnable(...) | Wraps synchronous code (Runnable) into a reactive Mono so it executes in the reactive pipeline |
Flowchart JWT Auth Global Filter
verifyJwtToken() method is where you put that logic./auth endpoint must be excluded from JWT validation. This is the endpoint responsible for creating tokens. If you try to validate a token before the user has logged in and received a token, all authentication calls will fail with 401.7. Route-Specific Filters Pre-existing Filters
Spring Cloud Gateway ships with many built-in Gateway Filter Factories (route-specific filters). You configure them in application.properties without writing any Java code.
How the Naming Convention Works
When you write a filter name in configuration, the gateway automatically appends GatewayFilterFactory to find the implementation class:
1Config name: AddRequestHeader2Actual class: AddRequestHeaderGatewayFilterFactory3
4Config name: Retry5Actual class: RetryGatewayFilterFactory6
7Config name: CircuitBreaker8Actual class: CircuitBreakerGatewayFilterFactoryGatewayFilterFactory in the configuration. The framework adds it automatically during mapping.How Config Fields Are Mapped
Each GatewayFilterFactory class defines an inner Config class with fields. You populate those fields dynamically through application.properties:
1spring.cloud.gateway.routes[0].filters[0].args.<field-name>=<value>For example, RemoveRequestHeaderGatewayFilterFactory has a Config with one field: name. So:
1spring.cloud.gateway.routes[0].filters[0].name=RemoveRequestHeader2spring.cloud.gateway.routes[0].filters[0].args.name=X-My-HeaderPre-existing Route-Specific Filters Reference
| Filter Name | Class Suffix | Config Fields | Purpose |
|---|---|---|---|
AddRequestHeader | GatewayFilterFactory | name, value | Add a header to the request |
AddResponseHeader | GatewayFilterFactory | name, value | Add a header to the response |
RemoveRequestHeader | GatewayFilterFactory | name | Remove a header from the request |
RemoveResponseHeader | GatewayFilterFactory | name | Remove a header from the response |
Retry | GatewayFilterFactory | retries, methods, statuses | Retry on failure |
RequestRateLimiter | GatewayFilterFactory | various | Apply rate limiting |
CircuitBreaker | GatewayFilterFactory | name, fallbackUri | Circuit breaker pattern |
Configuration Example Multiple Filters for One Route
1# Route 0 — Product Service2spring.cloud.gateway.routes[0].id=route03spring.cloud.gateway.routes[0].uri=lb://PRODUCT-SERVICE4spring.cloud.gateway.routes[0].predicates[0]=Path=/products/**5
6# Filter 0 — Add a custom request header7spring.cloud.gateway.routes[0].filters[0].name=AddRequestHeader8spring.cloud.gateway.routes[0].filters[0].args.name=X-Request-Source9spring.cloud.gateway.routes[0].filters[0].args.value=API-Gateway10
11# Filter 1 — Add a custom response header12spring.cloud.gateway.routes[0].filters[1].name=AddResponseHeader13spring.cloud.gateway.routes[0].filters[1].args.name=X-Test-Response-Header14spring.cloud.gateway.routes[0].filters[1].args.value=API-Gateway-Response15
16# Filter 2 — Remove a request header17spring.cloud.gateway.routes[0].filters[2].name=RemoveRequestHeader18spring.cloud.gateway.routes[0].filters[2].args.name=X-Unwanted-HeaderAfter this configuration, the response from the Product Service will include:
1X-Test-Response-Header: API-Gateway-ResponseHow RemoveRequestHeaderGatewayFilterFactory Works Internally
1// Simplified view of RemoveRequestHeaderGatewayFilterFactory2public class RemoveRequestHeaderGatewayFilterFactory 3 extends AbstractGatewayFilterFactory<RemoveRequestHeaderGatewayFilterFactory.Config> {4
5 public static class Config {6 private String name; // dynamically set from application.properties7 // getter and setter8 }9
10 @Override11 public GatewayFilter apply(Config config) {12 return (exchange, chain) -> {13 // Remove the header with the configured name14 ServerHttpRequest request = exchange.getRequest()15 .mutate()16 .headers(headers -> headers.remove(config.getName()))17 .build();18
19 return chain.filter(exchange.mutate().request(request).build());20 };21 }22}8. Retry Filter
Overview
The Retry Filter automatically retries a failed request a configured number of times before returning an error to the client. This is useful when microservices experience transient failures.
Configuration
1# Product Service Route2spring.cloud.gateway.routes[0].id=route03spring.cloud.gateway.routes[0].uri=lb://PRODUCT-SERVICE4spring.cloud.gateway.routes[0].predicates[0]=Path=/products/**5
6# Retry Filter7spring.cloud.gateway.routes[0].filters[0].name=Retry8spring.cloud.gateway.routes[0].filters[0].args.retries=49spring.cloud.gateway.routes[0].filters[0].args.methods=GET,DELETEConfiguration Fields Explained
| Field | Value | Meaning |
|---|---|---|
retries | 4 | Total attempts = 4 (1 original + 3 retries) |
methods | GET,DELETE | Only retry for these HTTP methods (idempotent operations) |
statuses | e.g., 500,503 | Retry only on these HTTP response status codes |
retries value is the total number of attempts, not the number of retries after the first failure. So retries=4 means: 1 original call + 3 retries = 4 total calls.Why Only Retry GET and DELETE?
Retrying POST or PUT requests can cause duplicate data — e.g., creating an order twice. Only retry idempotent operations (where sending the same request multiple times has the same effect as sending it once).
Test Scenario
Microservice controller (for testing):
1@RestController2public class ProductController {3
4 private int callCount = 0;5
6 @GetMapping("/products/{id}")7 public String getProduct(@PathVariable int id) {8 callCount++;9 if (callCount <= 3) {10 throw new RuntimeException("Simulated failure on attempt " + callCount);11 }12 return "Fetched product details on attempt " + callCount; // succeeds on 4th call13 }14}Result with retries=4:
1GET http://localhost:8083/products/12
3Response: "Fetched product details on attempt 4"The gateway transparently retried 3 times after the initial failure, succeeding on the 4th attempt — no changes required in the client code.
Retry Flowchart
9. Circuit Breaker Filter
Overview
The Circuit Breaker pattern prevents cascading failures. When a microservice is down or slow, the circuit breaker "opens" and immediately returns a fallback response instead of waiting and failing repeatedly.
Circuit States
| State | Behavior |
|---|---|
| Closed | Normal operation; requests pass through |
| Open | All requests immediately go to fallback; microservice is not called |
| Half-Open | A limited number of test requests are sent; if they succeed, moves to Closed |
Dependency Required
Unlike the Retry filter, the Circuit Breaker filter requires the Resilience4j dependency:
1<!-- pom.xml -->2<dependency>3 <groupId>org.springframework.cloud</groupId>4 <artifactId>spring-cloud-starter-circuitbreaker-reactor-resilience4j</artifactId>5</dependency>Fallback Endpoint (in API Gateway)
You need a controller inside the API Gateway itself to handle fallback responses:
1// Inside API Gateway project2@RestController3public class FallbackController {4
5 @GetMapping("/fallback")6 public String fallback() {7 return "Service is temporarily unavailable. Please try again later.";8 }9}Configuration
1# Product Service Route2spring.cloud.gateway.routes[0].id=route03spring.cloud.gateway.routes[0].uri=lb://PRODUCT-SERVICE4spring.cloud.gateway.routes[0].predicates[0]=Path=/products/**5
6# Circuit Breaker Filter7spring.cloud.gateway.routes[0].filters[0].name=CircuitBreaker8spring.cloud.gateway.routes[0].filters[0].args.name=productServiceCB9spring.cloud.gateway.routes[0].filters[0].args.fallbackUri=forward:/fallback10
11# Resilience4j Circuit Breaker Config for 'productServiceCB'12resilience4j.circuitbreaker.instances.productServiceCB.sliding-window-size=1013resilience4j.circuitbreaker.instances.productServiceCB.failure-rate-threshold=5014resilience4j.circuitbreaker.instances.productServiceCB.wait-duration-in-open-state=10s15resilience4j.circuitbreaker.instances.productServiceCB.sliding-window-type=COUNT_BASEDConfiguration Explained
| Property | Value | Meaning |
|---|---|---|
args.name | productServiceCB | Name of the Resilience4j circuit breaker instance to use |
args.fallbackUri | forward:/fallback | Internal redirect to gateway's own /fallback endpoint |
sliding-window-size | 10 | Consider the last 10 calls |
failure-rate-threshold | 50 | If 50% or more of calls fail, open the circuit |
wait-duration-in-open-state | 10s | Stay open for 10 seconds before transitioning to Half-Open |
forward:/fallback prefix tells the gateway this is an internal call — it does not go to any external microservice. It calls the /fallback endpoint defined within the gateway itself.Testing Circuit Breaker
- Stop the Product microservice (simulate it being down)
- Send more than 5 requests (crossing the 50% threshold over 10 calls)
- Observe: Circuit transitions from Closed → Open
- All subsequent requests immediately return:
"Service is temporarily unavailable" - Wait 10 seconds → Circuit moves to Half-Open
- Start the Product microservice → test call succeeds → Circuit moves back to Closed
Log output during circuit state transitions:
1INFO CircuitBreaker 'productServiceCB' changed state from CLOSED to OPEN2INFO CircuitBreaker 'productServiceCB' changed state from OPEN to HALF_OPEN3INFO CircuitBreaker 'productServiceCB' changed state from HALF_OPEN to CLOSED10. Rate Limiter Filter
Overview
The Rate Limiter filter restricts the number of requests a client can make within a time window, protecting microservices from being overwhelmed.
Dependency
1<!-- pom.xml — Rate Limiter requires Redis -->2<dependency>3 <groupId>org.springframework.boot</groupId>4 <artifactId>spring-boot-starter-data-redis-reactive</artifactId>5</dependency>Configuration
1# Rate Limiter Filter2spring.cloud.gateway.routes[0].filters[0].name=RequestRateLimiter3spring.cloud.gateway.routes[0].filters[0].args.redis-rate-limiter.replenishRate=104spring.cloud.gateway.routes[0].filters[0].args.redis-rate-limiter.burstCapacity=205spring.cloud.gateway.routes[0].filters[0].args.key-resolver=#{@userKeyResolver}The rate limiter filter, like Circuit Breaker and Retry, uses a pre-existing GatewayFilterFactory class. You configure it via properties and the framework handles the rest.
11. Writing a Custom Route-Specific Filter
Overview
While pre-existing filters cover most use cases, you may need to write your own route-specific filter with custom logic.
Naming Convention
The class name must follow the pattern:
1<YourName>GatewayFilterFactoryThe prefix (before GatewayFilterFactory) is what you use in application.properties:
1Class: CustomRouteGatewayFilterFactory2Config: spring.cloud.gateway.routes[0].filters[0].name=CustomRouteImplementation
1package com.example.gateway.filter;2
3import org.springframework.cloud.gateway.filter.GatewayFilter;4import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;5import org.springframework.stereotype.Component;6import reactor.core.publisher.Mono;7
8@Component // ① Register as Spring Bean9public class CustomRouteGatewayFilterFactory10 extends AbstractGatewayFilterFactory<CustomRouteGatewayFilterFactory.Config> { // ② Extend with your Config type11
12 public CustomRouteGatewayFilterFactory() {13 super(Config.class);14 }15
16 // ③ Custom Config class — fields here are dynamically configurable17 public static class Config {18 private String country; // configurable field19
20 public String getCountry() { return country; }21 public void setCountry(String country) { this.country = country; }22 }23
24 @Override25 public GatewayFilter apply(Config config) {26 return (exchange, chain) -> {27
28 // ④ PRE FILTER LOGIC29 System.out.println("PRE FILTER LOGIC — Country: " + config.getCountry());30
31 // ⑤ Pass to next filter in the chain32 return chain.filter(exchange)33 .then(Mono.fromRunnable(() -> {34 // ⑥ POST FILTER LOGIC35 System.out.println("POST FILTER LOGIC — Response returned");36 }));37 };38 }39}Configuration for Custom Filter
1# Applying the custom filter to route 0 (Product Service)2spring.cloud.gateway.routes[0].filters[4].name=CustomRoute3spring.cloud.gateway.routes[0].filters[4].args.country=IndiaOutput When Request Hits Product Service
1PRE FILTER LOGIC — Country: India2[... microservice processes the request ...]3POST FILTER LOGIC — Response returnedKey Points About Custom Route Filters
- Class must extend
AbstractGatewayFilterFactory - Class must be annotated with
@Component - Class name must end with
GatewayFilterFactory - Config class holds the fields you want to configure dynamically
apply()method returns aGatewayFilterlambda with your logic- Pre logic goes before
chain.filter(exchange) - Post logic goes inside
.then(Mono.fromRunnable(...))
Class Diagram
12. Summary Decision Table
When to Use Which Filter Type
| Scenario | Filter Type | Reason |
|---|---|---|
| JWT authentication for all APIs | Global Filter | Applies to every request |
| Logging every request/response | Global Filter | Universal concern |
| Request tracing / correlation IDs | Global Filter | All requests need tracing |
| Circuit breaker for Product Service only | Route-Specific Filter | Different config per service |
| Retry only GET/DELETE on Order Service | Route-Specific Filter | Service-specific configuration |
| Rate limiting on a public-facing route | Route-Specific Filter | Applied to specific traffic |
| Adding a debug header to responses | Route-Specific Filter | Route-specific need |
Complete Filter Ecosystem Mind Map
13. Interview Notes
Q1: What is the difference between Global Filter and Route-Specific (Gateway) Filter?
Global filters apply to every request passing through the gateway. Route-specific filters apply only to requests matching a specific route. Use global filters for cross-cutting concerns (auth, logging); use route-specific for service-level concerns (retry, circuit breaker with different configs per service).
Q2: Explain the request lifecycle in Spring Cloud Gateway.
Request → Dispatcher Handler → Route Mapping Handler → Global Filters (pre) → Route-Specific Filters (pre) → RouteToRequestUrlFilter → NettyRoutingFilter → Microservice → Route-Specific Filters (post) → Global Filters (post) → NettyWriteResponseFilter (sends response).
Q3: How does filter ordering work?
Every filter has an order value. Lower value = higher priority = runs earlier. Global filters typically have lower values than route-specific filters. NettyWriteResponseFilter has -1 (runs first in chain, but its post logic runs last). RouteToRequestUrlFilter has 10,000 (runs late, needs all filters to process first).
Q4: Why does NettyWriteResponseFilter have order -1?
It has no pre-logic (passes through immediately). Its important work is in the post phase — sending the response. Because it runs "first" in the chain (order -1), when the chain unwinds on the response, it runs last, ensuring it sends the client response after all other post-processing is done.
Q5: How do you implement a custom Global Filter?
Implement GlobalFilter and Ordered interfaces, annotate with @Component, override filter() for logic, override getOrder() for priority. Use chain.filter(exchange) to pass to next filter, and .then(Mono.fromRunnable(...)) for post-filter logic.
Q6: Why does the Retry filter not use Resilience4j?
Spring Cloud Gateway's Retry filter has its own built-in retry mechanism. Resilience4j is only needed for the Circuit Breaker filter, which uses Resilience4j's circuit breaker capabilities.
Q7: What does forward:/fallback mean in circuit breaker configuration?
It means the fallback is an internal call within the API gateway itself — not a call to another microservice. The gateway has its own controller at /fallback that returns a friendly error message.
Q8: How do you write a custom route-specific filter?
Create a class ending in GatewayFilterFactory, extend AbstractGatewayFilterFactory, annotate with @Component. Define a Config inner class with configurable fields. Override apply(Config config) to return a GatewayFilter with pre and post logic.
14. Practice Questions
Easy
- What are the two types of filters in Spring Cloud Gateway?
- Which filter is responsible for sending the HTTP response back to the client?
- What does a lower
ordervalue mean for a filter? - Name three use cases for global filters.
- What annotation is required on a custom filter class to make it a Spring-managed bean?
Medium
- Explain why the
/authendpoint should be excluded from JWT authentication in a global filter. - A developer configures
retries=3on the Retry filter but expects 3 retries after the first failure. What is wrong and what should the value be? - What dependency is required in
pom.xmlto use the Circuit Breaker filter? Why? - How does the naming convention for custom route-specific filters work? Give an example.
- Explain the difference between pre-filter logic and post-filter logic with a code example.
Hard
- Trace the full lifecycle of a request
GET /products/1through Spring Cloud Gateway, naming every filter that runs in order. - Explain why
Mono.fromRunnable()is used for post-filter logic instead of writing code directly afterchain.filter(exchange). - Design a production-ready Global Filter that: validates a JWT token, skips public endpoints, logs request duration, and adds a
X-Request-Idheader to every downstream call. - You have two microservices — Product Service (must allow max 100 req/s) and Order Service (max 10 req/s, circuit break if >30% fail). Design the complete
application.propertiesconfiguration. - Why would you intentionally give a Global Filter a very high order value? Name the built-in filters that do this and explain why.
Summary Key Revision Bullets
- Global Filters apply to every request; Route-Specific Filters apply to matched routes only
- Filter ordering: lower value = higher priority = runs earlier
NettyWriteResponseFilter(order=-1): no pre-logic; its post-logic sends the client response (runs last in post phase)RouteToRequestUrlFilter(order=10,000): resolveslb://URIs via service discoveryNettyRoutingFilter(very high order): actually invokes the microservice via HTTP- Pre-logic: code before
chain.filter(exchange)— runs before microservice call - Post-logic: code inside
.then(Mono.fromRunnable(...))— runs after microservice responds - Spring Cloud Gateway uses reactive programming (Project Reactor / WebFlux) internally
- Custom Global Filter: implement
GlobalFilter+Ordered, annotate@Component - Custom Route Filter: extend
AbstractGatewayFilterFactory, class name must end inGatewayFilterFactory - Pre-existing filter names in config auto-append
GatewayFilterFactoryfor class lookup Retryfilter: does NOT use Resilience4j; has its own built-in implementationCircuitBreakerfilter: DOES use Resilience4j; requiresspring-cloud-starter-circuitbreaker-reactor-resilience4jdependencyforward:/fallback= internal API gateway endpoint, not an external microservice- Decision rule: all requests → Global Filter; specific route → Route-Specific Filter
Study Guide generated from Spring Cloud Gateway — Filters, Authentication, Circuit Breaker, Retry & Rate Limiting lecture.
Mastery check
How well can you recall this?
Finished this lesson?