- Chapter
- Chapter 1 — API Gateway
- Prerequisites
- Volume V (HTTP, REST, errors)
- You will be able to
- Explain the role of an API gateway in a service architecture, configure routing with predicates and load balancing, validate tokens at the edge and propagate identity, choose TLS termination strategies, apply distributed rate limiting, and decide which responsibilities belong in the gateway versus services
- Covers
- Routing; Authentication; TLS termination; Rate limiting
On this page
- 1. Concept / Definition
- 2. Why It Exists
- 3. Core Concepts
- 4. How It Works Internally — The Filter Chain
- 4A. Deep Dive — What Must Not Be in the Gateway
- 5. APIs / Features / Syntax
- 6. Practical Examples
- 7. Common Problems & Mistakes
- 8. Performance & Production Considerations
- 9. Architecture & Design Considerations
- 10. Interview Questions & Answers
1Concept / Definition
An API gateway is a reverse proxy that acts as the single entry point for API clients, applying cross-cutting policies before routing requests to backend services.

| TOC responsibility | What the gateway does |
|---|---|
| Routing | Maps incoming requests (path, host, headers, weights) to backend services and instances |
| Authentication | Validates credentials (JWT, OAuth2 tokens, API keys, mTLS) and rejects unauthenticated calls |
| TLS termination | Terminates client TLS connections, manages certificates, optionally re-encrypts to backends |
| Rate limiting | Limits requests per client/plan/route to protect capacity and enforce agreements |
2Why It Exists
Without a gateway, every client must know every service endpoint, every service must implement TLS, token validation, rate limiting and logging, and internal topology leaks to consumers. Gateways centralise these concerns, hide topology and give operations one place to observe and protect incoming traffic.
| Without gateway | With gateway |
|---|---|
| Clients call 30 service hostnames | One API host, stable paths |
| Each team implements auth and limits | Consistent policies at the edge |
| Topology changes break clients | Routes change, clients don't |
| No single view of API traffic | Central metrics and access logs |
3Core Concepts
3.1 Routing

spring:
cloud:
gateway:
server:
webflux:
routes:
- id: orders
uri: lb://orders-service # service discovery + client-side LB
predicates:
- Path=/api/orders/**
filters:
- StripPrefix=1
- id: catalog
uri: lb://catalog-service
predicates:
- Path=/api/catalog/**
- Method=GET| Routing concern | Mechanism |
|---|---|
| Service discovery | lb:// with Spring Cloud LoadBalancer, Kubernetes services |
| Load balancing | Round robin / weighted / zone-aware |
| Health | Remove unhealthy instances (readiness probes, outlier detection) |
| Timeouts per route | spring.cloud.gateway…httpclient.response-timeout, route metadata |
3.2 Authentication

@Bean
SecurityWebFilterChain edge(ServerHttpSecurity http) {
return http
.authorizeExchange(a -> a
.pathMatchers("/api/catalog/**").permitAll() // public read
.pathMatchers(HttpMethod.POST, "/api/orders/**")
.hasAuthority("SCOPE_orders:write")
.anyExchange().authenticated())
.oauth2ResourceServer(o -> o.jwt(Customizer.withDefaults())) // JWKS cached
.csrf(ServerHttpSecurity.CsrfSpec::disable)
.build();
}| Edge authentication responsibility | Stays in services |
|---|---|
| Token signature, expiry, issuer, audience | Resource-level permissions (is this your order?) |
| Coarse scopes per route | Business authorization rules |
| API key → application identity | Tenant data isolation |
3.3 TLS termination

| TLS concern | Gateway practice |
|---|---|
| Protocol | TLS 1.2 minimum, TLS 1.3 preferred; HTTP/2 via ALPN |
| Certificates | Automated renewal (ACME/cert-manager, cloud certificate managers) |
| HSTS | Strict-Transport-Security for browser clients |
| Backend hop | mTLS (mesh) or re-encryption in zero-trust networks |
| Client certificates | mTLS for partners (verify at gateway, forward identity) |
3.4 Rate limiting

filters:
- name: RequestRateLimiter
args:
redis-rate-limiter.replenishRate: 50 # tokens per second
redis-rate-limiter.burstCapacity: 100 # bucket size
redis-rate-limiter.requestedTokens: 1
key-resolver: "#{@apiKeyResolver}" # per client/app@Bean
KeyResolver apiKeyResolver() {
return exchange -> Mono
.justOrEmpty(exchange.getRequest().getHeaders().getFirst("X-Api-Key"))
.switchIfEmpty(Mono.just("anonymous"));
}4How It Works Internally — The Filter Chain

| Stage | Examples | Why this order |
|---|---|---|
| Connection | TLS handshake, HTTP/2 | Before anything else |
| Security | WAF rules, JWT validation | Reject bad traffic cheaply |
| Limits | Rate limit, quota | Before consuming backend capacity |
| Pre-routing transforms | Add trace/tenant headers, strip internal headers | Prepare the backend request |
| Routing | Load-balanced call with timeouts | Core function |
| Post-processing | Response headers, metrics, access log | Observability |
4ADeep Dive — What Must Not Be in the Gateway
| Tempting gateway feature | Why not | Where instead |
|---|---|---|
| "Is this order owned by the caller?" | Needs domain data | Service authorization |
| Order validation rules | Domain logic, versioning | Service |
| Response composition for one app | Client-specific | BFF (Chapter 4) |
| Data enrichment from databases | Coupling, latency | Service / BFF |
| Long-running orchestration | Stateful, fragile | Workflow/saga services |

5APIs / Features / Syntax
| Spring Cloud Gateway feature | Use |
|---|---|
Route predicates (Path, Host, Header, Method, Weight, Query) | Routing |
Filters (StripPrefix, RewritePath, AddRequestHeader, RemoveRequestHeader) | Transformations |
RequestRateLimiter + KeyResolver | Rate limiting (Redis) |
CircuitBreaker filter (Resilience4j) | Protect backends |
TokenRelay filter | Forward OAuth2 tokens |
Actuator /actuator/gateway/routes | Inspect routes |
6Practical Examples
6.1 Direct service exposure
Before introducing a gateway, a retailer exposed 14 services directly to its mobile app. Each had different auth behaviour and one forgot rate limiting; a scraper overloaded the catalog service. A gateway with uniform JWT validation, per-key limits and WAF rules stopped the incident class entirely.
6.2 Gateway did too much
A gateway accumulated 300 lines of Groovy scripts per route for field mappings and pricing checks. Every product change required the platform team; releases queued for weeks. Moving logic back to services and BFFs restored team autonomy (Topic 1.3).
6.3 Worked example — responsibilities split
Scenario. When ShopNow introduced an API gateway, two opposite proposals appeared: one team wanted the gateway to do all security so services could trust every request; another wanted the gateway to be a dumb router. Neither was right.
| Concern | Gateway | Service |
|---|---|---|
| TLS | ✔ | mTLS inside (mesh) |
| Token validation | ✔ | ✔ (defence in depth, cheap with cached keys) |
| Scope check per route | ✔ | — |
| Resource ownership | — | ✔ |
| Rate limits per client | ✔ | Local protection (bulkheads) |
| Input validation | Size limits only | ✔ full validation |
| Access logs, metrics | ✔ | ✔ (service-level) |
What it shows. The table assigns each concern to the layer that has the information to do it well. The gateway terminates TLS, validates tokens, checks route-level scopes, applies per-client rate limits and records access logs, because it sees every request. Services validate tokens again cheaply with cached keys for defence in depth, check resource ownership, which needs domain data such as who owns order 5001, apply full input validation, and protect themselves with local bulkheads. Logs and metrics exist at both levels.
Takeaway. Split responsibilities by knowledge, not by convenience. The gateway enforces uniform edge policies; services enforce anything that needs domain data. Write the split down so every team applies it the same way.
6.4 Worked example — identity propagation
Scenario. After authenticating a user, the gateway must tell downstream services who the caller is. An early design simply forwarded an X-User-Id header, until a penetration test showed that a client could set that header itself.
| Option | How | Trade-off |
|---|---|---|
| Forward original JWT | Services validate again | Simple, standard; token size |
| Token exchange (RFC 8693) | Gateway exchanges for internal token | Least privilege; more moving parts |
| Signed identity headers | Gateway adds X-User-Id + signature | Services must trust gateway only |
What it shows. There are three safe options. Forwarding the original JWT lets every service validate it again, which is simple and standard but repeats work and carries a large token. Token exchange, defined in RFC 8693, has the gateway swap the external token for a short-lived internal token with only the permissions needed, which gives least privilege at the cost of more moving parts. Signed identity headers let the gateway add identity headers plus a signature that services verify, which is efficient but means services must trust only the gateway. In every case, client-supplied identity headers must be stripped at the edge.
Takeaway. Never trust identity information that a client could have set. Choose one propagation method for the platform, document it, and strip any internal identity headers from incoming requests.
6.5 Worked example — header hygiene
Scenario. A security scan of ShopNow's public API flagged missing security headers and server version information in responses, and the team also wanted to make sure clients could not inject internal headers.
default-filters:
- RemoveRequestHeader=X-Internal-User # clients must not spoof
- RemoveResponseHeader=Server
- AddResponseHeader=Strict-Transport-Security, max-age=31536000
- SecureHeadersWhat it shows. Gateway default filters apply header rules to every route. RemoveRequestHeader drops X-Internal-User from incoming requests, so clients cannot spoof internal identity. RemoveResponseHeader removes the Server header, which otherwise reveals software and version details useful to attackers. AddResponseHeader sets Strict-Transport-Security so browsers use only HTTPS for the next year, and SecureHeaders adds a standard set of protective headers such as X-Content-Type-Options and X-Frame-Options. Because these are defaults, new routes inherit them automatically.
Takeaway. Apply header hygiene centrally at the gateway, as defaults rather than per-route settings. Then security posture does not depend on each team remembering the rules, and scans stay clean as APIs grow.
6.6 Worked example — per-route timeouts
Scenario. With a single global gateway timeout of 2 seconds, interactive catalogue calls were well protected, but the finance team's report exports, which legitimately take several seconds, failed constantly.
- id: reports
uri: lb://reporting-service
predicates: [ Path=/api/reports/** ]
metadata:
response-timeout: 10000 # ms — long-running exports
connect-timeout: 500| Route | Timeout | Reason |
|---|---|---|
/api/catalog/** | 2 s | Interactive |
/api/reports/** | 10 s | Heavier, async preferred |
What it shows. Per-route metadata in Spring Cloud Gateway sets timeouts that match each route's character. The catalogue route keeps a short 2-second response timeout because users are waiting and slow responses should fail fast. The reports route allows 10 seconds for heavier queries, with a short connect timeout of 500 ms so unreachable backends still fail quickly. For truly long-running exports, the better design is asynchronous: start a job, return 202 Accepted with a status URL, and let the client poll or receive a notification.
Takeaway. Timeouts should reflect each route's latency profile, not a single global value. Treat long timeouts as a signal to consider asynchronous designs.
6.7 Worked example — mTLS for partners
Scenario. Logistics partners call ShopNow's shipment API from their own servers. Passwords and shared API keys had been leaked twice, so the security team required stronger, certificate-based authentication for partners.
| Step | Detail |
|---|---|
| Partner presents client certificate | Issued by our partner CA |
| Gateway verifies chain and revocation | Rejects unknown certs |
| Gateway maps cert subject → partner id | Adds signed identity header |
| Rate limits per partner | Based on mapped id |
What it shows. With mutual TLS, each partner presents a client certificate issued by ShopNow's partner certificate authority. The gateway verifies the certificate chain and revocation status, rejecting unknown or revoked certificates before any request reaches a service. It maps the certificate subject to a partner ID, adds that ID as a signed identity header, and applies rate limits per partner. Services never handle certificates themselves; they receive a trusted partner identity.
Takeaway. Use mutual TLS at the edge for high-value machine-to-machine partners. Centralise certificate handling in the gateway, automate certificate issuance and rotation, and keep a fast revocation process for compromised certificates.
6.8 Worked example — rate limit keys
Scenario. A single misbehaving mobile app version flooded the search endpoint, and a global rate limit started rejecting requests from all clients, including well-behaved ones.
| Key | Protects against |
|---|---|
| API key / client id | Single app overload, plan enforcement |
| User id (from JWT) | Individual abuse |
| IP address | Anonymous abuse (careful with NAT/proxies) |
| Route + client | Expensive endpoints |
What it shows. The key used for rate limiting decides what is protected. Limiting by API key or client ID protects against one application overloading the system and enforces commercial plans. Limiting by user ID, taken from the validated JWT, stops individual abusive users. Limiting by IP address protects anonymous endpoints but can unfairly block many users behind one corporate NAT or proxy. Combining route and client limits protects expensive endpoints specifically. After the incident, ShopNow limited per client ID and per user on search, so the faulty app version was throttled without affecting others.
Takeaway. Choose rate-limit keys by the threat you are guarding against, and usually combine several. Return 429 with a Retry-After header so well-behaved clients can back off correctly.
6.9 Worked example — gateway metrics
Scenario. The product team wanted to know which partner APIs were most used, and the security team wanted early warning of credential-stuffing attempts. Both questions could be answered at the gateway.
| Metric | Use |
|---|---|
spring.cloud.gateway.requests by route, status | Traffic and errors per API |
| Latency histogram by route | Edge SLOs |
| Rate-limited requests (429) by key | Plan/abuse analysis |
| Auth failures (401/403) by client | Security monitoring |
What it shows. Because every request passes through the gateway, its metrics give an edge-wide view. Request counts by route and status show traffic and error rates per API; latency histograms by route support edge SLOs; counts of 429 responses by key show which clients hit limits, useful for plan and abuse analysis; and counts of 401 and 403 by client highlight authentication attacks or misconfigured clients. A spike of 401s from one IP range was ShopNow's first sign of a credential-stuffing attack.
Takeaway. Treat the gateway as a primary observability point. Build dashboards and alerts for traffic, errors, rate limiting and authentication failures, and share them with product and security teams, not just operations.
6.10 Worked example — managed vs self-hosted
Scenario. ShopNow had to choose between a managed gateway service from its cloud provider and running Spring Cloud Gateway inside its Kubernetes clusters.
| Criterion | AWS API Gateway / Azure APIM | Spring Cloud Gateway on K8s |
|---|---|---|
| Operations | Managed | Your team |
| Customisation | Policies, limited code | Full Java code |
| Cost model | Per request | Compute |
| Latency | Extra hop outside cluster | In-cluster |
What it shows. The comparison shows the trade-offs. A managed gateway, such as AWS API Gateway or Azure API Management, removes operational work and charges per request, but offers customisation mainly through configured policies, and adds a hop outside the cluster. A self-hosted Spring Cloud Gateway allows full Java customisation and runs inside the cluster with low latency, with costs based on compute, but the team must run, scale, patch and monitor it. ShopNow chose self-hosted for internal APIs needing custom logic and a managed gateway for partner-facing APIs with developer-portal needs.
Takeaway. Decide build versus buy from operational capacity, customisation needs, latency and cost at expected traffic. A mixed approach is often right, as long as policies are defined consistently across both.
6.11 Worked example — default-deny routing
Scenario. A developer exposed the Spring Boot Actuator endpoints of a service through a wildcard gateway route. Within days, an external scanner found the /actuator/env endpoint and its configuration details.
| Rule | Effect |
|---|---|
| Only explicitly defined routes exist | Unknown paths → 404 at edge |
| Admin/actuator paths never routed publicly | No accidental exposure |
| New routes via reviewed config PRs | Governance |
What it shows. A default-deny gateway posture prevents this class of mistake. Only routes explicitly defined in configuration exist; any unknown path returns 404 at the edge without reaching a service. Administrative and Actuator paths are never routed publicly. New routes are added only through reviewed pull requests to the gateway configuration, so every exposure is a visible, deliberate decision with a reviewer.
Takeaway. Make the edge deny by default and expose APIs explicitly. Review route changes like code, and scan your own public surface regularly so accidental exposure is caught by you, not by attackers.
6.12 Worked example — gateway in the request trace
Scenario. After the gateway was introduced, a product manager argued that it had "made everything slower" and asked for it to be removed from the path of the checkout API.
| Span | Duration |
|---|---|
| gateway: auth filter | 0.8 ms |
| gateway: rate limit (Redis) | 1.2 ms |
| gateway → orders-service | 38 ms |
| orders-service handler | 35 ms |
What it shows. A distributed trace of one checkout request answered the question with data. The gateway's authentication filter took 0.8 ms and its Redis-backed rate limiter 1.2 ms, while the call to the orders service took 38 ms, of which 35 ms was the service's own handler. The gateway's share was about 2 ms of 40, roughly 5%, and the real opportunity for improvement was inside the orders service.
Takeaway. Use tracing to measure the gateway's actual latency contribution before debating it. Keep gateway filters lightweight, monitor their timings as part of the edge SLOs, and focus optimisation where traces show the time is spent.
7Common Problems & Mistakes
- Business logic in the gateway.
- Relying only on gateway authorization.
- Trusting client-supplied identity headers.
- Plaintext internal hops in untrusted networks.
- Uniform timeouts for all routes.
- Exposing internal/admin routes accidentally.
8Performance & Production Considerations
| Aspect | Guideline |
|---|---|
| Latency | Cache JWKS, keep filters light |
| Scaling | Stateless instances, autoscaling |
| Limits | Redis-backed with fallback policy |
| Security | Default-deny, header hygiene, TLS 1.3 |
| Observability | Per-route metrics, tracing |
9Architecture & Design Considerations
- Define a clear responsibility boundary between gateway and services.
- Treat gateway configuration as code with reviews and tests.
- Use defence in depth: gateway checks plus service authorization.
- Combine edge gateway with a service mesh for east-west traffic.
10Interview Questions & Answers
What is an API gateway?
An API gateway is a reverse proxy that acts as the single entry point for clients calling a set of backend services. Instead of each client knowing every service's address and each service implementing edge concerns, the gateway receives all external requests, applies common policies such as TLS termination, authentication, rate limiting, header rules and logging, and routes each request to the right service. Examples include Spring Cloud Gateway, Kong, NGINX-based gateways and managed services such as AWS API Gateway. It simplifies clients and enforces consistent policies, but it is critical infrastructure that must be highly available and kept free of business logic.
Name four core gateway responsibilities.
Routing sends each request to the right backend service based on path, host, headers or other predicates, often with load balancing and path rewriting. Authentication verifies the caller, typically by validating OAuth 2.0 or OpenID Connect tokens, API keys or client certificates, before requests reach services. TLS termination handles certificates and encryption for external clients, so services do not each manage public certificates. Rate limiting caps how many requests a client, user or IP address may make in a period, protecting services from overload and abuse and enforcing commercial plans. Gateways also commonly add header hygiene, request size limits, logging, metrics and tracing.
What does TLS termination at the gateway mean?
TLS termination means the gateway is the endpoint of the client's encrypted TLS connection. It holds the public certificate and private key, performs the handshake, decrypts each request, applies its policies, and forwards the request to backend services. This centralises certificate management and lets the gateway inspect requests. Traffic behind the gateway should not simply travel in plain text, though: in a zero-trust approach it is re-encrypted to the services, often with mutual TLS provided by a service mesh. Services then need to trust forwarded headers from the gateway to know the original scheme, host and client address.
How does distributed rate limiting work across gateway instances?
A gateway usually runs as several instances behind a load balancer, so counting requests in each instance's memory would let a client multiply its limit by the number of instances. Distributed rate limiting keeps counters or token buckets in a shared store such as Redis. For each request, the gateway atomically updates the bucket for the relevant key, such as client ID and route, usually with a Lua script or atomic Redis command, and allows or rejects the request based on the result. Spring Cloud Gateway's RedisRateLimiter works this way. The shared store adds a little latency and must be highly available, with a decision about failing open or closed if it is down.
Why must services still authorise requests if the gateway authenticates them?
The gateway can verify who the caller is and coarse permissions such as scopes, but it does not know the domain data needed for most authorisation decisions, such as whether this customer owns order 5001 or whether this approver's limit covers the amount. Only the service that owns the data can decide that. Services can also be reached by paths that bypass the gateway, such as internal calls, message consumers or misconfigured routes. Validating the token again in each service, which is cheap with cached keys, and enforcing resource-level authorisation there provides defence in depth if the gateway is misconfigured or compromised.
How should identity be propagated from the gateway to services?
There are three common options. The gateway can forward the original, validated token, usually a JWT, so services validate it again and read claims directly; this is simple and standard but repeats work and passes broad tokens around. It can exchange the external token for a short-lived internal token with narrower permissions, using OAuth 2.0 token exchange, which supports least privilege. Or it can add signed identity headers that services verify. Whatever the choice, the gateway must strip any identity headers supplied by clients, and services must accept identity only from trusted sources.
What should not be implemented in a gateway?
A gateway should stay a thin, policy-enforcing edge component. Business rules, such as discount calculations or order validation, do not belong there, because they would be hidden from the owning teams, hard to test and duplicated. Fine-grained authorisation that depends on domain data belongs in services. Client-specific response composition, aggregating data from several services for one screen, belongs in a backend-for-frontend owned by that client's team. Orchestration of multi-step business processes belongs in services or workflow engines. Putting these in the gateway creates a central bottleneck owned by one team and couples every service to it.
How would you choose between a managed and self-hosted gateway?
Compare the options against your own constraints. Managed gateways reduce operational work, scale automatically and often include developer portals and API key management, but they charge per request, limit customisation to configured policies, add a network hop and can complicate multi-cloud or on-premises set-ups. Self-hosted gateways such as Spring Cloud Gateway or Kong offer full customisation and in-cluster latency, with compute-based cost, but require a team to operate, scale and patch them. Also consider integration with your identity provider, observability stack and deployment tooling. Many organisations use both, with consistent policies.
Test your knowledge on this topic →Flashcards from this topic's 8 questions, filtered by level and type.