What you'll learn: By the end of this lesson you will be able to describe an API gateway as an ordered pipeline in which any stage can answer a request, say what routing, authentication, rate limiting and a per-route timeout each decide, explain why the gateway sets the identity header itself and why 502 and 504 differ, and name what a gateway must not become. A Spring lab runs all four stages with captured output.
Think of the registration desk at a large conference. You are looked up on the list (routing: which hall is yours). Your badge is checked once (authentication). The desk counts your requests for free passes (rate limiting). Then you are sent to the hall, and if the hall does not answer in reasonable time, the desk says it is closed instead of letting you wait all day (timeout). At any step the desk can stop you.
An API gateway is that desk for HTTP. The API gateway and service mesh overview lists what a gateway does and compares it with a mesh, Backend for Frontend covers a gateway per client, and rate limiting covers the algorithms. This lesson is the dedicated treatment of the gateway itself: the request pipeline, the order of its stages and the decision inside each one.
The core idea
A gateway is an ordered pipeline. Each stage either answers the request itself or passes it on, so a service only sees requests that survived every stage. The pipeline is cheap-checks-first: finding a route costs a map lookup, authentication costs a key lookup or a signature check, rate limiting needs to know who the caller is, and proxying costs a network call and a held thread.
The Azure Architecture Center describes the two patterns that make up a gateway. Gateway Routing places a gateway in front of a set of services and uses layer 7 routing so clients need to know only one endpoint; services can be added, split or moved without changing clients. Gateway Offloading moves cross-cutting concerns (it lists authentication, TLS termination, monitoring, protocol translation and throttling) into the gateway so each service does not rebuild them.
Three illustrations run through the lesson: a minimal example (the Spring lab), a realistic example (ShopStream's gateway during a month-end report rush, in "In practice") and a failure example (a forged identity header, and a slow route that holds the gateway's threads).
Figure 1. The four stages
How to read this: the accent boxes are the gateway. Each can reject the request and answer the client directly; only a request that passes all four is forwarded.
Stage 1: routing
A route is a path pattern and a target. In Spring Cloud Gateway Server Web MVC a route is an id, a request predicate such as path(...), a handler (http()) and a target set with before(uri(...)). The lab keeps its route table in application.properties: an id, a path prefix, a timeout and whether authentication is required.
Two details decide whether routing is safe. A prefix must end at a slash or at the end of the path: /api/catalogue-old/items must not match the route /api/catalogue. And a path no route owns is answered by the gateway with a 404 before any other work runs. The lab also drops the public /api prefix, so /api/catalogue/items?limit=2 reaches the catalogue service as /catalogue/items?limit=2.
Stage 2: authentication and the identity header
The gateway checks who the caller is once, so services do not each repeat it. The lab accepts a bearer token from a small table (a stand-in for verifying a signed token; the JWT and OAuth details are separate lessons: JWT structure and pitfalls, OAuth 2 and OpenID Connect). A missing or unknown token on a protected route gets a 401. RFC 9110 says a 401 response must carry a WWW-Authenticate header, and RFC 6750 defines the Bearer challenge: with no credentials at all the server should not add an error code, and with a bad token it responds 401 with error="invalid_token".
The decision that matters is how identity travels inward. The lab's gateway removes any X-User-Id the client sent and sets its own from the verified token, and it does not pass the caller's Authorization header on. The Azure offloading page gives the reason: define whether each backend authorises the original caller or the gateway's identity, never treat unverified forwarded headers as proof of identity, and configure backends to accept requests only through the gateway, or clients can bypass it. Authentication belongs here; authorisation (what this caller may do) stays in the services.
Expected output, captured from a real run (Spring Boot 4.1.2, Java 25, the lab's golden file, 2026-12-01):
== 2. Authentication: who is calling, decided once at the edge ==
GET /api/orders/42, no Authorization header -> 401 from the gateway, at the authentication stage
WWW-Authenticate: Bearer realm="shopstream"; body {"error":"unauthenticated"}; no service was called
GET /api/orders/42, Bearer tok-wrong -> 401 from the gateway, at the authentication stage
WWW-Authenticate: Bearer realm="shopstream", error="invalid_token"; body {"error":"invalid_token"}; no service was called
GET /api/orders/42, Bearer tok-ana -> 200 from the orders service
orders saw GET /orders/42, X-User-Id ana, Authorization (none)
GET /api/orders/42, Bearer tok-ana and a forged X-User-Id: admin -> 200 from the orders service
orders saw GET /orders/42, X-User-Id ana, Authorization (none)
GET /api/catalogue/items (public), forged X-User-Id: admin -> 200 from the catalogue service
catalogue saw GET /catalogue/items, X-User-Id (none), Authorization (none)
The forged header never reaches the services: on the protected route the service saw ana, on the public route it saw none.
Stage 3: rate limiting
The limiter runs after authentication so its key is the caller, not a shared address. The lab keeps one token bucket per caller in memory, with illustrative settings (3 requests of burst, one token back per second) and a clock the test moves. Rate limiting explains the algorithms, the shared-store version and where else to enforce limits; none of that is repeated here.
What the gateway adds is the answer. RFC 6585 defines 429 Too Many Requests for a user who sent too many requests in a given time, says the response may include Retry-After, and notes that it does not define how the server identifies the user or counts requests. RFC 9110 allows Retry-After as a number of seconds. The lab returns the whole seconds until a token is back.
Order matters in both directions. Because limiting follows authentication, a flood of bad tokens never reaches the limiter (a test sends six and the next authenticated request still succeeds), so a coarse per-address limit belongs earlier or at the edge. And the buckets live in this process: with several gateway instances each would count separately.
Expected output, captured from a real run (the same run):
ana, request 4 in the same instant -> 429 from the gateway, at the rate-limit stage
Retry-After: 1; body {"error":"too_many_requests"}; no service was called
bo, request 1 (a different bucket) -> 200 from the orders service
orders saw GET /orders/42, X-User-Id bo, Authorization (none)
(the test clock moves forward 1 second)
ana, one second later -> 200 from the orders service
orders saw GET /orders/42, X-User-Id ana, Authorization (none)
ana, straight after -> 429 from the gateway, at the rate-limit stage
Retry-After: 1; body {"error":"too_many_requests"}; no service was called
The fourth request in the same instant got 429 and no service was called. A different caller was unaffected, and after one second a token was back.
Stage 4: proxy and timeout
The last stage forwards the request and copies the answer back. It drops hop-by-hop headers: RFC 9110 says an intermediary removes the fields named in Connection, the Connection field itself, and fields known to be connection-specific such as Keep-Alive, TE, Transfer-Encoding and Upgrade. It uses Spring's RestClient with exchange(), which applies no status handlers, so a 4xx or 5xx from a service passes through unchanged (retrieve() would throw).
Each route has its own timeout, because routes differ: a catalogue read and a report export do not deserve the same patience. Java's HttpClient reports an expired request timeout as an HttpTimeoutException; the lab turns that into 504, and a refused connection into 502. RFC 9110 describes 502 as a gateway receiving an invalid response from an inbound server and 504 as not receiving a timely response, so the 502 for a refused connection is this lab's choice; real gateways differ, and what matters is that the client gets a fast, distinct answer instead of a hang. See timeouts, retries, backoff and jitter for how callers should react.
Expected output, captured from a real run (the same run):
== 4. Timeout and unreachable upstream ==
GET /api/reports/q3, Bearer tok-ana (service answers after 1000 ms, budget 200 ms) -> 504 from the gateway, at the proxy stage
body {"error":"upstream_timeout","route":"reports"}; reports saw GET /reports/q3, X-User-Id ana, Authorization (none)
GET /api/legacy/x (nothing listens on that port) -> 502 from the gateway, at the proxy stage
body {"error":"upstream_unreachable","route":"legacy"}; no service was called
GET /api/orders/42, Bearer tok-bo (other routes are unaffected) -> 200 from the orders service
orders saw GET /orders/42, X-User-Id bo, Authorization (none)
The reports service needs 1000 ms and its route allows 200 ms, so the gateway answered 504 itself while the other routes stayed healthy.
Figure 2. Four ways a request ends
How to read this: the first two branches never touch the service. Only the allowed branch costs a service call, and even that is bounded by the route's budget.
Why this order
Figure 3. Which stage answers
How to read this: each diamond is a stage and each exit is a response the gateway makes itself. The check that costs least comes first.
What a gateway must not become
- A place for business rules. The Azure offloading page says plainly: never offload business logic to the gateway. A gateway full of pricing or validation rules is edited by every team.
- An unnoticed single point of failure or bottleneck. The routing page warns that a gateway can be both, and says to load test it so it does not cause cascading failures. Run several instances, and remember each adds a network hop (the offloading and microservices.io pages both list added latency).
- A coupling point. When service changes force gateway releases, the gateway team becomes a queue.
Product or stand-in. Spring Cloud Gateway describes itself as an API gateway built on Spring Framework 7, Spring Boot 4 and Project Reactor, in two flavours (WebFlux and Web MVC). Its documentation lists filters including rate limiting, circuit breaking, retry and token relay. This lab does not run it: it is a plain Spring MVC stand-in so each stage is a few readable lines. Use a product (or a managed API gateway, for example Apigee) when you need what the stand-in lacks.
Trade-offs
| Choice | Gain | Cost | Pick when |
|---|---|---|---|
| One gateway for all clients | One entry point, one place for policy | Bottleneck and release queue | Few clients with similar needs |
| Authenticate at the gateway | Verified once, services stay simple | Services must trust only the gateway | Many services, one identity system |
| Per-route timeouts | One slow route cannot hold the rest | More configuration to keep right | Routes with different latency |
| Per-process rate limits | No shared store | Each instance counts separately | Instances are few and limits are soft |
| Product instead of custom code | Maintained filters and features | Another system to learn and run | Beyond the four stages |
Build it
The lab is examples/spring-labs/labs/api-gateway-pattern. It is a stand-in gateway (three servlet filters in @Order and one proxy controller) tested through MockMvc against three fake services and one closed port, all JDK HttpServers on loopback; there is no Docker and no external network. The numbers are illustrative.
cd examples/spring-labs
./gradlew :labs:api-gateway-pattern:test
It runs 11 tests (10 behaviour tests and one that compares the report with examples/spring-labs/golden/api-gateway-pattern.txt) on Spring Boot 4.1.2 and Java 25, and the compare run passed. The test clock is moved by hand; the timeout test waits for a real 200 ms limit. The code is RouteFilter, AuthenticationFilter, RateLimitFilter and ProxyController, with TokenBucketLimiter and a route table bound from application.properties.
Break it (a suggested experiment, not part of the captured run). In ProxyController, remove "x-user-id" from GATEWAY_OWNED: the identity test should fail because a forged header now reaches a public route. Restore the line and re-run.
What it cannot show: Spring Cloud Gateway itself, a shared rate-limit store, TLS, token verification, retries or load.
In practice: ShopStream's gateway during a month-end report rush
This is a realistic scenario, not a case history. It is a composite on the course's running example, ShopStream, an educational reference design. Every number is an illustrative assumption.
The situation
ShopStream's seven services sit behind one gateway. At month end a partner accounting tool requests store sales reports, which the Reports service builds slowly. During the rush, checkout slows down too, though Checkout itself is healthy.
Starting architecture
Figure 4. One timeout for every route
How to read this: the warning boxes share one gateway and one patience limit. A gateway that holds a thread per request runs out of threads when slow requests pile up, and then every route waits.
Options considered
| Option | What it fixes | What it costs | Risk |
|---|---|---|---|
| Lower the global timeout | Frees threads sooner | Hurts routes that are legitimately slow | Breaks report exports |
| Per-route timeouts and a per-partner limit on reports | Slow route fails fast; partner cannot flood | More configuration | A missing route setting falls back to the default |
| A separate gateway instance for reports | Isolates the blast radius | Another deployable | Operational overhead |
| Make reports asynchronous | Removes the slow call | A service change | Partner must poll |
The decision
| Field | Decision record |
|---|---|
| Context | One slow route shares the gateway's capacity with checkout. |
| Decision | Give every route its own timeout from measured latency, add a per-partner rate limit on the reports route, and route reports through a separate gateway instance. Plan asynchronous reports as follow-up. |
| Consequences, good | A slow reports service produces fast 504s for reports only; checkout is unaffected. |
| Consequences, bad | More route configuration; clients of reports must handle 504 and 429. |
| Revisit when | Reports become asynchronous, or more routes need their own capacity (a bulkhead, covered in the circuit breaker and bulkhead lesson). |
Rollout and verification
- Measure each route's latency and set timeouts above their normal range, not at a guess.
- Ship the limit in log-only mode and count how many requests it would reject.
- Watch per route: requests in flight, 504 rate, 429 rate and upstream latency.
- Test the configuration: a test that fails if any route has no timeout.
The 2 a.m. failure
Checkout slows again during the next rush. A configuration change renamed the reports route and the new entry had no timeout, so the default applied and the gateway's capacity filled with waiting report requests. First three checks: (1) requests in flight per route; (2) the effective configuration of the reports route; (3) upstream latency of Reports. Mitigation: restore the route's timeout and rate limit the partner key. Follow-up: the configuration test above, and a default timeout short enough that a missing setting is annoying, not an outage.
Architect's notes
- Make every stage able to say no quickly, and say which stage did it (a header or a log field) so an incident can tell the gateway from the service.
- Give every route a timeout, and fail the build if one is missing.
- Keep identity one-way: the gateway sets it, services trust only the gateway, and the network enforces that.
Common mistakes
- Trusting a client-supplied identity header because the gateway "usually" overwrites it.
- One global timeout for routes with very different latency.
- Rate limiting before authentication with a per-address key, so one office or carrier shares a bucket.
Key takeaways
- A gateway is an ordered pipeline; each stage can answer the request itself.
- Routing needs a prefix that ends at a slash and a 404 for paths no route owns.
- Authenticate once at the edge, set the identity header yourself and keep authorisation in the services.
- A rate limit after authentication keys on the caller and answers 429 with
Retry-After. - Each route needs its own timeout; 504 means no timely answer, and a refused connection is a lab-chosen 502.
- The gateway can become a bottleneck, a single point of failure and a place for business logic: guard against all three.
Practice exercises
Exercise 1 (20 min). Draw the pipeline for a request with no token to /api/orders/42 and say which stage answers and what it returns.
Exercise 2 (1 hour). Run the lab. Add a route for /api/inventory with its own 100 ms timeout and a test that a 150 ms service gets a 504.
Exercise 3 (half day). Move the rate limit ahead of authentication with a per-address key. List what improves, what breaks for users behind one address, and which test fails.
Related reading
- API gateway and service mesh: an overview: what gateways and meshes do and when you need neither.
- Backend for Frontend (BFF): one gateway layer per client.
- Rate limiting: the algorithms and the shared-store version.
- Forward and reverse proxies: the proxy a gateway builds on.
- Timeouts, retries, backoff and jitter: how callers react to a 504.
- Why Apigee is the missing layer in every microservices architecture: a managed API gateway in practice.
Official documentation
- Microsoft Learn, Gateway Routing pattern and Gateway Offloading pattern.
- Spring Cloud Gateway, reference documentation.
- IETF, RFC 9110: HTTP Semantics, RFC 6750: Bearer Token Usage and RFC 6585: Additional HTTP Status Codes.
- Spring Framework, REST clients.
- microservices.io, API Gateway pattern.