Skip to content
AITroveRead. Build. Understand.
Make this comfortable

Spring Cloud Gateway filter order: pre and post phases reverse

Last updated: 1 Oct 20264 min read
tutorial
IntermediateBy AITrove Editorial

Gateway combines global and route filters into one ordered chain; the first pre-filter is the last post-filter.

Trace the same request twice

A global trace filter with higher precedence runs before a route filter on the inbound path. When the downstream response returns, that trace filter runs after the route filter's post phase. That nesting matters when adding a request ID, rewriting headers, timing the downstream call, or translating an error. A filter that logs only before chain.filter(exchange) does not measure the whole route.

Separate edge identity from forwarded data

A route may trust a user identity established at the gateway, but a downstream service must still have an authenticated contract for that identity. Remove client-supplied identity headers before setting gateway-owned values. Tenant routing and proxy headers have the same spoofing risk if the outer edge does not define which inputs it owns.

Verify execution order

Give a test filter an ordered pre marker and a post marker, then assert the observed sequence around a route filter. Include a failed downstream call; post handling may still be needed for metrics and cleanup. Keep routing, authentication and observability concerns in distinct filters so their ordering can be reasoned about. The sketch uses the reactive Gateway server API.

Implementation sketch

Java
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
    long startedAt = System.nanoTime();
    return chain.filter(exchange).doFinally(signal ->
        routeTimer.record(System.nanoTime() - startedAt));
}
public int getOrder() { return -47; }

Cost and verification

Each filter adds work to every routed request. Long-running or blocking work in a reactive filter occupies event-loop capacity; the timer itself should avoid blocking export.

Common Mistakes

  • Do not assume a low numeric order runs last in both phases.
  • Do not trust a client-supplied tenant header after adding a gateway filter.
  • Do not block inside a reactive Gateway filter to write logs or fetch policy.

Read next

Spring Cloud Gateway tenant routing: authenticate at the edge and enforce again at the service, Spring behind a proxy: trust forwarded headers only after the edge strips them, Spring Cloud Gateway rate limits: derive the key from authenticated identity, Spring Cloud Gateway retry: idempotency, buffered bodies and the byte budget.

spring
spring-boot
web-apis
gateway-filter-ordering
Storage details