Sub topic 12
From reverse proxy to API gateway
This chapter assumes you know how a reverse proxy forwards requests to backends, how it balances load, and how it terminates TLS. It also assumes you can read a basic nginx configuration. The goal is to show where a plain reverse proxy ends and an API gateway begins, and how to decide which one a design needs.
The gateway is a reverse proxy with extra jobs
An API gateway sits in front of a set of backend services and gives clients one entry point. Clients send every request to the gateway. The gateway decides which service handles it, and it applies shared rules on the way.
Mechanically, a gateway is a reverse proxy. It accepts a client connection, opens or reuses a connection to a backend, relays the request, and relays the response back. Everything from the earlier chapters still applies: forwarding headers, health checks, and TLS handling.
The difference is what the proxy knows about the traffic. A basic reverse proxy mostly treats requests as opaque. It balances them across identical servers. A gateway understands the API. It knows that /v1/users/* and /v1/orders/* belong to different services, that some callers may use an endpoint and others may not, and that each caller has a request budget.
The common gateway responsibilities are:
- Routing by API structure. Send requests to different services based on path, host, method, or header.
- Authentication and authorization. Check credentials once at the edge so each service does not have to.
- Rate limiting and quotas. Cap how many requests a client can make in a time window.
- Request and response transformation. Rewrite paths, add or remove headers, and sometimes change payload formats.
- Aggregation. Combine the results of several backend calls into one client response.
- Observability. Produce uniform access logs, metrics, and trace identifiers for every API call.
- Versioning and rollout control. Route a share of traffic to a new version of a service.
None of these is exotic. Each can be done in plain nginx with a few directives. The gateway label usually means that these concerns are the main purpose of the component, and that it is managed through an API or a control plane rather than hand-edited files.
Where the gateway fits
The diagram shows a typical layout. Clients talk only to the gateway. The gateway authenticates, limits, and routes. Services behind it are on a private network.
Order matters. Cheap checks run first, so a rejected request never reaches a backend. Authentication usually comes before rate limiting when limits are per user. When limits are per IP address, you can limit before authenticating, which also protects the authentication service from floods.
Reverse proxy and gateway compared
| Concern | Plain reverse proxy | API gateway |
|---|---|---|
| Main purpose | Spread load, terminate TLS, cache | Expose many services as one API |
| Backends | Often identical replicas of one app | Different services with different contracts |
| Routing basis | Mostly one upstream per host or path | Path, method, headers, version, caller identity |
| Authentication | Rare, often basic or none | Central, with tokens, API keys, or mutual TLS |
| Rate limiting | Optional, per IP | Per client, per key, per plan |
| Configuration | Static files, reloaded | Often an admin API or declarative config store |
| Typical products | nginx, HAProxy, Caddy | Kong, Envoy-based gateways, cloud-managed gateways, nginx with modules |
The two categories overlap heavily. nginx, HAProxy, and Envoy can all act as either. Choose by what you need to configure and who needs to configure it, not by the product name.
A minimal gateway in nginx
The following configuration shows three gateway jobs in one server block: routing by path, delegating authentication to a separate service, and per-client rate limiting.
# In the http {} context
limit_req_zone $binary_remote_addr zone=api_limit:10m rate=10r/s;
upstream users_service {
server 10.0.1.11:9000;
server 10.0.1.12:9000;
}
upstream orders_service {
server 10.0.2.11:9000;
}
upstream auth_service {
server 10.0.3.11:9000;
}
server {
listen 80;
server_name api.example.com;
# Internal subrequest target. Clients cannot call it directly.
location = /_auth {
internal;
proxy_pass http://auth_service/verify;
proxy_pass_request_body off;
proxy_set_header Content-Length "";
proxy_set_header X-Original-URI $request_uri;
}
location /v1/users/ {
auth_request /_auth;
limit_req zone=api_limit burst=20 nodelay;
limit_req_status 429;
proxy_pass http://users_service/;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
location /v1/orders/ {
auth_request /_auth;
limit_req zone=api_limit burst=20 nodelay;
limit_req_status 429;
proxy_pass http://orders_service/;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
}Several details in this configuration are worth understanding.
- Prefix stripping.
proxy_pass http://users_service/;ends with a slash, which is a URI part. nginx replaces the matched location prefix with that URI. A request for/v1/users/42reaches the service as/42. Without the trailing slash, the full original path is passed through. This is a frequent source of 404 errors behind gateways. - Authentication as a subrequest.
auth_requestmakes nginx send a separate request to/_authbefore handling the real one. If the auth service returns 2xx, the request continues. If it returns 401 or 403, nginx returns that status to the client. Any other result becomes a 500. The auth service sees the original path inX-Original-URIand receives the client's headers, such asAuthorization, by default. - Rate limiting.
limit_req_zonekeys on$binary_remote_addr, so the limit is per client IP address.rate=10r/ssets the steady rate.burst=20allows short spikes, andnodelayserves burst requests immediately rather than spacing them out. By default nginx rejects excess requests with 503, solimit_req_status 429switches to the more accurate "Too Many Requests". - Module requirement.
auth_requestneedsngx_http_auth_request_module. Most distribution packages include it. If you build nginx from source, you must enable it with--with-http_auth_request_module.
Rate limiting algorithms
Gateways differ in how they count requests. Knowing the algorithm explains behavior that otherwise looks odd.
- Leaky bucket. Requests enter a queue that drains at a fixed rate. nginx
limit_reqfollows this model. It produces a smooth output rate. - Token bucket. A bucket refills with tokens at a fixed rate, and each request spends one. It allows bursts up to the bucket size, then limits to the refill rate.
- Fixed window. Count requests per calendar interval, such as per minute. It is simple but allows double the limit across a window boundary: a full quota at the end of one minute and another at the start of the next.
- Sliding window. Count requests over the last N seconds. It avoids the boundary problem at the cost of more state.
With more than one gateway instance, the counters must be shared or each instance enforces its own limit. A limit of 100 requests per minute spread over four instances with local counters can let through up to 400. Shared state, usually in Redis, fixes this but adds a network call to every request and a new dependency. Many teams accept per-instance limits and divide the quota by the instance count.
Authentication at the gateway
Centralizing authentication has a clear benefit: services do not each implement token parsing, key lookups, and error responses. There are two common patterns.
- Validate locally. The gateway checks a signed token, such as a JWT, using a public key. No network call is needed, and checks stay fast. The cost is that revocation is hard until the token expires.
- Ask an auth service. The gateway calls an introspection or verification endpoint, as in the nginx example. Revocation is immediate, but every request pays an extra round trip, and the auth service becomes a critical dependency.
After authentication, the gateway often passes the verified identity to the service in a header, such as X-User-Id. This is only safe if the gateway strips any client-supplied copy of that header first and the services accept the header only from the gateway's network. Otherwise, a client can claim to be anyone.
Aggregation and transformation
Some gateways combine calls. A mobile client that needs a user's profile and recent orders might make one request to /v1/dashboard, and the gateway calls the users and orders services and merges the JSON. This reduces round trips over slow networks.
The cost is that business logic moves into the gateway. It then needs its own code, tests, and deployment, and it must handle partial failure: what to return when the orders service is down but the users service is not. Plain nginx cannot do this. It requires a scripting layer or a dedicated aggregation service. A common design keeps the gateway thin and puts aggregation in a separate "backend for frontend" service that the gateway routes to.
Failure modes and trade-offs
A gateway concentrates risk, as every reverse proxy does, but it concentrates more because it holds more logic.
- Single point of failure. All API traffic passes through it. Run several instances behind a load balancer or a virtual IP, as covered in the chapter on availability.
- Added latency. Each check adds time. An external auth call on every request can dominate response time. Cache positive auth results briefly where the risk allows.
- The gateway becomes a monolith. When teams add routing rules, transformations, and custom logic for every service, the gateway turns into a shared component that every team must change and deploy together. Keep it to cross-cutting concerns.
- Configuration drift and blast radius. One bad rule can break every route. Validate configuration before reloading (
nginx -t), keep it in version control, and roll out changes gradually. - Timeouts and retries. Retrying non-idempotent requests, such as a POST that creates an order, can create duplicates. Restrict automatic retries to safe methods unless the API supports idempotency keys.
Not every system needs a gateway. A single application with replicas needs only a reverse proxy. A gateway starts to pay off when several services are exposed to outside clients and you want authentication, limits, and logging implemented once.
Exercise
A gateway runs three instances, each enforcing rate=100r/m per client with local in-memory counters. A client sends requests evenly to all three. What is the maximum steady request rate the client can achieve, and what are two ways to enforce the intended limit of 100 per minute overall?
Show answer
The client can reach about 300 requests per minute, because each instance counts separately. To enforce 100 per minute overall, either keep the counters in shared storage such as Redis so all instances see one count, or set each instance to roughly one third of the target (about 33 per minute). The second approach is simpler but is only accurate if the load balancer spreads the client's requests evenly.
Exercise
In the nginx example, a request for /v1/orders/17 reaches the orders service as /17. Which part of the configuration causes this, and what single change would make the service receive /v1/orders/17 instead?
Show answer
The trailing slash in proxy_pass http://orders_service/; makes nginx replace the matched /v1/orders/ prefix with /. Removing the slash, so the directive reads proxy_pass http://orders_service;, passes the original request path unchanged.