API Gateway vs Reverse Proxy
Every API gateway is built on a reverse proxy, but not every reverse proxy is an API gateway. A reverse proxy moves traffic to the right server. An API gateway also understands that traffic as API calls from consumers, and applies rules to each one: who is calling, how often, and which version of which service should answer.
This tutorial shows exactly what the gateway adds, with Nginx and Spring Cloud Gateway configurations side by side. For the pattern itself, see the API Gateway pattern.
1. What Are an API Gateway and a Reverse Proxy?
A reverse proxy is a server that forwards client requests to backend servers and returns their responses, commonly handling TLS, caching, compression and path-based routing.
An API gateway is a reverse proxy specialised for APIs. It is the single entry point for API clients and applies cross-cutting policies to each call: authentication and authorisation, rate limiting and quotas, request and response transformation, API versioning, aggregation of several service calls, and API analytics.
A useful way to put it in an interview: a reverse proxy knows where a request should go; an API gateway also knows who sent it and what they are allowed to do.
2. Architecture Comparison
3. How an API Call Flows Through a Gateway
A mobile app calls GET /api/orders/42 with an access token:
- Authenticate: the gateway validates the JWT signature, expiry and issuer. An invalid token gets
401 Unauthorizedimmediately. - Rate limit: it checks the caller's token bucket. Too many calls get
429 Too Many Requests. - Route: it matches
/api/orders/**to the orders service and rewrites the path to/orders/42. - Balance: it picks a healthy orders instance.
- Respond: it returns the response and records metrics per API and per consumer.
A plain reverse proxy would perform only the routing and balancing steps; it does not know who the caller is.
Request and response transformation
Gateways also adapt traffic between clients and services. A gateway can add a correlation ID header to every request, remove internal headers such as server versions from responses, rename a path when a service is reorganised, or translate a public REST call into an internal gRPC call. These changes keep clients stable while the services behind the gateway evolve.
4. Features an API Gateway Adds
- Identity: OAuth 2.0 and JWT validation, API keys, and mutual TLS for partners.
- Traffic policies: per-consumer rate limits, quotas and spike arrest; see the Rate Limiting pattern.
- Transformation: header and path rewriting, protocol translation such as REST to gRPC, and response shaping.
- Aggregation: one client call fans out to several services, which is useful for mobile clients.
- Resilience: per-route timeouts, retries and circuit breakers.
- API management: versioning, developer portals and usage analytics in managed gateways.
Kinds of API gateways
Gateways come in three forms. Libraries and frameworks such as Spring Cloud Gateway run as your own Java service and are configured in YAML or code. Self-hosted products such as Kong or Envoy-based gateways run as separate infrastructure. Managed cloud gateways such as AWS API Gateway, Azure API Management and Google Apigee are operated by the provider and add developer portals, billing and analytics. Choose by how much control, customisation and operational work your team wants.
5. Practical Implementation
Reverse proxy: Nginx path routing
server {
listen 443 ssl;
server_name api.shop.example;
ssl_certificate /etc/nginx/certs/api.crt;
ssl_certificate_key /etc/nginx/certs/api.key;
location /api/orders/ { proxy_pass http://10.0.2.11:8080/orders/; }
location /api/users/ { proxy_pass http://10.0.2.21:8080/users/; }
}
This routes and terminates TLS, but every caller is treated the same.
API gateway: Spring Cloud Gateway
The same routes, plus JWT validation, per-user rate limiting and load-balanced service discovery:
spring:
cloud:
gateway:
server:
webflux:
routes:
- id: orders
uri: lb://orders-service # load-balanced across registered instances
predicates:
- Path=/api/orders/**
filters:
- StripPrefix=1 # /api/orders/42 -> /orders/42
- name: RequestRateLimiter
args:
redis-rate-limiter.replenishRate: 10
redis-rate-limiter.burstCapacity: 20
key-resolver: "#{@userKeyResolver}"
- id: users
uri: lb://users-service
predicates:
- Path=/api/users/**
filters:
- StripPrefix=1
security:
oauth2:
resourceserver:
jwt:
issuer-uri: https://auth.example.com/realms/shop # validate JWT access tokens
package com.example.gateway;
import java.security.Principal;
import org.springframework.cloud.gateway.filter.ratelimit.KeyResolver;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class GatewayConfig {
/**
* Rate-limit per authenticated user. The principal comes from the validated JWT,
* so a client cannot pick its own key by sending a header.
*/
@Bean
KeyResolver userKeyResolver() {
return exchange -> exchange.getPrincipal().map(Principal::getName);
}
}
spring-cloud-starter-gateway-server-webflux starter. Older releases use spring.cloud.gateway.routes without server.webflux. The rate limiter also needs the reactive Redis starter, and JWT validation needs the OAuth2 resource server starter.6. Advantages and Disadvantages
| Reverse proxy | API gateway | |
|---|---|---|
| Strength | Fast, simple, general purpose | Central API security and policies |
| Knows the caller | No | Yes (token, key or certificate) |
| Complexity | Low | Higher; more configuration and code |
| Risk | Little API protection | Can become a bottleneck or a "god service" if it holds business logic |
7. API Gateway vs Reverse Proxy Comparison
| Aspect | Reverse proxy | API gateway |
|---|---|---|
| Focus | Any HTTP traffic | API calls from consumers |
| Authentication | Basic, if any | OAuth 2.0, JWT, API keys, mTLS |
| Rate limiting | Per IP, simple | Per consumer, plan or API |
| Transformation | Headers and paths | Payloads, protocols, aggregation |
| Observability | Access logs | Per-API and per-consumer analytics |
| Examples | Nginx, HAProxy, Caddy | Spring Cloud Gateway, Kong, AWS API Gateway, Apigee |
8. Real-World Use Cases
- Reverse proxy: serving a website, a single application, or static assets with TLS and caching.
- API gateway: a public API with partner keys and quotas; a microservices backend for mobile apps; a backend-for-frontend layer.
- Both: an Nginx or cloud reverse proxy at the edge for TLS and static content, forwarding
/apitraffic to a Spring Cloud Gateway cluster.
- Backend for frontend (BFF): a small gateway per client type, such as one for the mobile app and one for the web app, shapes responses for each screen.
Many teams start with a reverse proxy and add a gateway only when the number of APIs, consumers or security rules grows. That is a sensible order: the gateway brings real value, but also more configuration to own.
9. Best Practices
- Keep business logic out of the gateway: limit it to cross-cutting concerns.
- Validate tokens at the gateway, authorise in services: the services still check what the user may do.
- Scale the gateway horizontally and keep it stateless; store rate-limit counters in Redis.
- Set per-route timeouts and circuit breakers so one slow service cannot exhaust gateway resources.
- Follow API security guidelines: see API Security Best Practices.
- Return consistent error bodies for
401,403and429so clients can handle them in one place.
Migrating from a reverse proxy to a gateway
- Keep the existing reverse proxy for TLS and static content.
- Point the
/apipaths to the new gateway one route at a time. - Move authentication to the gateway and remove duplicated checks from the proxy.
- Add per-consumer rate limits and monitoring once traffic flows through the gateway.
This incremental path avoids a risky big-bang switch and lets you compare latency and error rates after each step.
10. Summary
- An API gateway is a reverse proxy specialised for APIs.
- A reverse proxy routes traffic; a gateway also knows the caller and applies policies.
- Gateway features: authentication, rate limits, transformation, aggregation and analytics.
- Spring Cloud Gateway configures routes, predicates and filters in YAML or Java.
- Use a reverse proxy for websites and simple routing, and a gateway for managed APIs.
Next, see how a gateway relates to load balancing in API Gateway vs Load Balancer.
API Gateway vs Reverse Proxy: Top Interview Questions
These are the API gateway and reverse proxy questions most often asked in system design interviews, with short answers you can explain in your own words.
Q1. What is the difference between an API gateway and a reverse proxy?
A reverse proxy forwards traffic to backend servers and handles TLS, caching and routing. An API gateway is a reverse proxy that also understands API consumers and applies per-call policies such as authentication, rate limiting, transformation and analytics.
Q2. Can Nginx be used as an API gateway?
Partly. Nginx can route, limit by IP and validate some credentials with extra modules or scripting. Full API gateway features, such as per-consumer quotas, JWT handling and developer portals, usually come from dedicated gateways or Nginx-based products.
Q3. Should authorisation happen in the API gateway?
The gateway should authenticate, meaning it checks the token and rejects bad callers early. Fine-grained authorisation, such as "can this user see order 42", belongs in the service that owns the data. The service must still verify identity rather than blindly trust the network.
Q4. What are the risks of an API gateway?
It can become a single point of failure, a performance bottleneck, or a place where business logic accumulates. Mitigate this with horizontal scaling, timeouts, circuit breakers and keeping the gateway limited to cross-cutting concerns.
Q5. What does the lb:// prefix mean in Spring Cloud Gateway?
It tells the gateway to resolve the service name through Spring Cloud LoadBalancer, using a discovery client such as Eureka, Consul or Kubernetes, and to pick one instance for each request.