ArchitectMind
  1. Home
  2. Java Ecosystem
  3. Book 6 · Databases, APIs & Integration
  4. Volume VI
  5. Gateway Responsibilities
Book 6 · Volume VI — API Management, GraphQL & Distributed API Design · Topic 1.1

Gateway Responsibilities

Routing, authentication, TLS termination and rate limiting

14 min readStage 3 · Systems8 interview questions
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. 1. Concept / Definition
  2. 2. Why It Exists
  3. 3. Core Concepts
  4. 4. How It Works Internally — The Filter Chain
  5. 4A. Deep Dive — What Must Not Be in the Gateway
  6. 5. APIs / Features / Syntax
  7. 6. Practical Examples
  8. 7. Common Problems & Mistakes
  9. 8. Performance & Production Considerations
  10. 9. Architecture & Design Considerations
  11. 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.

What an API gateway does
Figure 1 — What an API gateway does
TOC responsibilityWhat the gateway does
RoutingMaps incoming requests (path, host, headers, weights) to backend services and instances
AuthenticationValidates credentials (JWT, OAuth2 tokens, API keys, mTLS) and rejects unauthenticated calls
TLS terminationTerminates client TLS connections, manages certificates, optionally re-encrypts to backends
Rate limitingLimits requests per client/plan/route to protect capacity and enforce agreements
Table 1 — Core gateway responsibilities

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 gatewayWith gateway
Clients call 30 service hostnamesOne API host, stable paths
Each team implements auth and limitsConsistent policies at the edge
Topology changes break clientsRoutes change, clients don't
No single view of API trafficCentral metrics and access logs
Table 2 — Why a gateway

3Core Concepts

3.1 Routing

Routing predicates
Figure 2 — Routing predicates
YAML
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 concernMechanism
Service discoverylb:// with Spring Cloud LoadBalancer, Kubernetes services
Load balancingRound robin / weighted / zone-aware
HealthRemove unhealthy instances (readiness probes, outlier detection)
Timeouts per routespring.cloud.gateway…httpclient.response-timeout, route metadata
Table 3 — Routing mechanics

3.2 Authentication

Authentication at the gateway
Figure 3 — Authentication at the gateway
JAVA
@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 responsibilityStays in services
Token signature, expiry, issuer, audienceResource-level permissions (is this your order?)
Coarse scopes per routeBusiness authorization rules
API key → application identityTenant data isolation
Table 4 — Split of authentication duties

3.3 TLS termination

TLS termination options
Figure 4 — TLS termination options
TLS concernGateway practice
ProtocolTLS 1.2 minimum, TLS 1.3 preferred; HTTP/2 via ALPN
CertificatesAutomated renewal (ACME/cert-manager, cloud certificate managers)
HSTSStrict-Transport-Security for browser clients
Backend hopmTLS (mesh) or re-encryption in zero-trust networks
Client certificatesmTLS for partners (verify at gateway, forward identity)
Table 5 — TLS practices

3.4 Rate limiting

Rate limiting at the gateway
Figure 5 — Rate limiting at the gateway
YAML
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
JAVA
@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

Gateway filter chain (Spring Cloud Gateway)
Figure 6 — Gateway filter chain (Spring Cloud Gateway)
StageExamplesWhy this order
ConnectionTLS handshake, HTTP/2Before anything else
SecurityWAF rules, JWT validationReject bad traffic cheaply
LimitsRate limit, quotaBefore consuming backend capacity
Pre-routing transformsAdd trace/tenant headers, strip internal headersPrepare the backend request
RoutingLoad-balanced call with timeoutsCore function
Post-processingResponse headers, metrics, access logObservability
Table 6 — Order of processing

4ADeep Dive — What Must Not Be in the Gateway

Tempting gateway featureWhy notWhere instead
"Is this order owned by the caller?"Needs domain dataService authorization
Order validation rulesDomain logic, versioningService
Response composition for one appClient-specificBFF (Chapter 4)
Data enrichment from databasesCoupling, latencyService / BFF
Long-running orchestrationStateful, fragileWorkflow/saga services
Table 7 — Keeping the gateway thin
Gateway options
Figure 7 — Gateway options

5APIs / Features / Syntax

Spring Cloud Gateway featureUse
Route predicates (Path, Host, Header, Method, Weight, Query)Routing
Filters (StripPrefix, RewritePath, AddRequestHeader, RemoveRequestHeader)Transformations
RequestRateLimiter + KeyResolverRate limiting (Redis)
CircuitBreaker filter (Resilience4j)Protect backends
TokenRelay filterForward OAuth2 tokens
Actuator /actuator/gateway/routesInspect routes
Table 8 — Gateway toolkit

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.

ConcernGatewayService
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 validationSize limits only✔ full validation
Access logs, metrics✔✔ (service-level)
Table 9 — Who does what

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.

OptionHowTrade-off
Forward original JWTServices validate againSimple, standard; token size
Token exchange (RFC 8693)Gateway exchanges for internal tokenLeast privilege; more moving parts
Signed identity headersGateway adds X-User-Id + signatureServices must trust gateway only
Table 10 — Never pass unsigned identity headers from clients

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.

YAML
default-filters:
  - RemoveRequestHeader=X-Internal-User        # clients must not spoof
  - RemoveResponseHeader=Server
  - AddResponseHeader=Strict-Transport-Security, max-age=31536000
  - SecureHeaders

What 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.

YAML
- id: reports
  uri: lb://reporting-service
  predicates: [ Path=/api/reports/** ]
  metadata:
    response-timeout: 10000      # ms — long-running exports
    connect-timeout: 500
RouteTimeoutReason
/api/catalog/**2 sInteractive
/api/reports/**10 sHeavier, async preferred
Table 11 — Timeouts reflect route characteristics

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.

StepDetail
Partner presents client certificateIssued by our partner CA
Gateway verifies chain and revocationRejects unknown certs
Gateway maps cert subject → partner idAdds signed identity header
Rate limits per partnerBased on mapped id
Table 12 — Strong partner authentication at the edge

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.

KeyProtects against
API key / client idSingle app overload, plan enforcement
User id (from JWT)Individual abuse
IP addressAnonymous abuse (careful with NAT/proxies)
Route + clientExpensive endpoints
Table 13 — Choose keys by threat

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.

MetricUse
spring.cloud.gateway.requests by route, statusTraffic and errors per API
Latency histogram by routeEdge SLOs
Rate-limited requests (429) by keyPlan/abuse analysis
Auth failures (401/403) by clientSecurity monitoring
Table 14 — The gateway as observability point

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.

CriterionAWS API Gateway / Azure APIMSpring Cloud Gateway on K8s
OperationsManagedYour team
CustomisationPolicies, limited codeFull Java code
Cost modelPer requestCompute
LatencyExtra hop outside clusterIn-cluster
Table 15 — Build vs buy

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.

RuleEffect
Only explicitly defined routes existUnknown paths → 404 at edge
Admin/actuator paths never routed publiclyNo accidental exposure
New routes via reviewed config PRsGovernance
Table 16 — Security posture at the edge

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.

SpanDuration
gateway: auth filter0.8 ms
gateway: rate limit (Redis)1.2 ms
gateway → orders-service38 ms
orders-service handler35 ms
Table 17 — Tracing shows the gateway's share of latency

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

AspectGuideline
LatencyCache JWKS, keep filters light
ScalingStateless instances, autoscaling
LimitsRedis-backed with fallback policy
SecurityDefault-deny, header hygiene, TLS 1.3
ObservabilityPer-route metrics, tracing
Table 18 — Operational guidelines

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

Q1L1 · BasicConcept

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.

Q2L1 · BasicConcept

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.

Q3L2 · IntermediateConcept

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.

Q4L2 · IntermediateInternals

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.

Q5L3 · Senior EngineerTricky

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.

Q6L3 · Senior EngineerDesign

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.

Q7L4 · Technical ArchitectDesign

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.

Q8L5 · Solution ArchitectTrade-off

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.

Free question pack

Get 100 free Core Java interview questions

Subscribe for the Book 1 question pack (PDF, every answer explained) and new tutorials once a week. No spam, unsubscribe anytime. What is in the pack?

Almost done! Check your inbox and click the confirmation link. Your download link arrives as soon as you confirm.