How to Implement an API Gateway
Build an API gateway: route to the services, handle the cross-cutting concerns, authenticate at the edge, and keep it from becoming a bottleneck.
On this page
Introduction
A client that talks to many services needs to know each service’s address, handle each one’s errors, and repeat the authentication and the policy at each call. An API gateway gives the client one entry point: it routes the request to the service that owns it, applies the cross-cutting concerns once, and returns the response. The client sees one API, and the internal services stay focused on their domain.
This tutorial implements an API gateway: route by path or host, handle the cross-cutting concerns, keep the gateway thin, and test the routing and the failure. The examples use a reverse proxy, and the design applies to any gateway, whether written or a product such as Envoy.
Route the request to the owning service
The gateway maps an incoming request to the service that owns it, by path prefix or by host. A request to /orders/… goes to the order service and /users/… to the user service. The client sees one host, and the routing table maps the paths to the services, so the client does not need to know the internal topology.
Keep the routing table declarative and in one place, so the mapping is visible and a new service is added by a configuration entry. A path-based route is simple and readable; a host-based route suits an API where each service has a subdomain. Choose the one that matches the API’s shape, and keep the routes non-overlapping so a request maps to exactly one service.
# a declarative routing table: path prefix -> upstream service
/orders/* -> order-service:8080
/users/* -> user-service:8081
/payments/* -> payment-service:8082
/metrics -> gateway-local (not forwarded)
Handle the cross-cutting concerns once
The gateway is the place for the concerns that apply to every request: authentication, the correlation id, CORS, rate limiting, and the request logging. Doing them at the gateway means each service does not repeat them, and a change to the policy is one change. The gateway validates the token, attaches the identity, and forwards the request with the identity in a trusted header or a context.
The authentication at the gateway is a policy check, not the whole authorization: the gateway verifies the token and identifies the caller, and the service does the object-level authorization, because only the service knows its resources. The gateway can also rate limit per client and add the CORS headers, which are edge concerns that belong at the entry point rather than in each service.
async function gateway(req, res) {
const identity = verifyToken(req.headers.authorization); // auth once at the edge
if (!identity) { res.writeHead(401).end(); return; }
if (!rateLimiter.allow(identity.id)) { res.writeHead(429).end(); return; }
const target = route(req.url); // path -> service
proxy(target, req, res, { 'x-identity-id': identity.id, 'x-request-id': req.id });
}
Keep the gateway thin
The gateway should route and apply policy, not implement business logic. A gateway that transforms responses, applies domain rules, and holds state becomes a new monolith that every team depends on and that is hard to change. Keep it a routing and policy layer, so it stays simple, fast, and independently deployable.
The transformation the gateway does should be limited to the cross-cutting kind: adding the identity header, the CORS headers, the correlation id, and maybe a request size limit. Anything that encodes a domain rule belongs in a service, where it is owned and tested. This boundary keeps the gateway from becoming the coupling point it was meant to remove.
Avoid the gateway becoming a bottleneck
Every request passes through the gateway, so it must not become a single point of failure or a latency source. Scale it horizontally behind a load balancer, keep its state minimal, and make the policy checks fast or cached. A rate limiter that calls a slow store on every request adds the latency to every request; cache the counter or use a fast store.
Set timeouts on the upstream calls so a slow service fails at the gateway rather than hanging the request, and return a gateway-level error, such as a 502 or a 504, when an upstream is unavailable or times out. This keeps the gateway responsive and gives the client a clear error. The gateway is a proxy, and a proxy that hangs on a slow upstream is a bottleneck.
function proxy(target, req, res) {
const upstream = http.request({ host: target.host, port: target.port, path: req.url, timeout: 5000 });
upstream.on('timeout', () => { upstream.destroy(); res.writeHead(504).end('gateway timeout'); });
upstream.on('error', () => { res.writeHead(502).end('bad gateway'); });
upstream.on('response', (uRes) => { res.writeHead(uRes.statusCode, uRes.headers); uRes.pipe(res); });
req.pipe(upstream);
}
Test the routing and the upstream failure
Test that a request routes to the service that owns its path, by asserting the upstream the gateway called. Test that a request to an unknown path returns a 404 from the gateway. Test that a request reaching an unavailable upstream returns a 502 and a slow upstream a 504, rather than hanging. Test that the identity header is attached after the auth and that an unauthorized request is rejected before the upstream is called.
# routing: the request reaches the owning service
curl -s http://gateway/orders/1 # reaches order-service; assert the upstream log
curl -s -o /dev/null -w '%{http_code}\n' http://gateway/unknown # 404 from the gateway
# upstream down: the gateway returns a clear error, not a hang
curl -s -o /dev/null -w '%{http_code}\n' http://gateway/orders/1 # 502 or 504
Common pitfalls
Putting business logic in the gateway so it becomes a monolith, doing the object-level authorization at the gateway when only the service knows the resources, a rate limiter that calls a slow store on every request, no timeout on the upstream so a slow service hangs the gateway, and a single gateway instance as a point of failure are the recurring mistakes. A thin routing and policy layer, the authorization in the service, a fast policy check, upstream timeouts, and a horizontally scaled gateway address them.
Conclusion
An API gateway gives the client one entry point and applies the cross-cutting concerns once. Route by path or host, handle the auth, the rate limiting, and the correlation at the edge, keep the gateway thin and free of business logic, and set upstream timeouts so a slow service fails cleanly. Self-check by asserting a request reaches the owning service and that an unavailable upstream returns a clear gateway error, not a hang. Then the client sees one API and the services stay focused.
Sources: Microservices.io: API gateway pattern, MDN: HTTP proxy and gateway concepts, Envoy: Architecture.
FAQ
- Gateway versus load balancer?
- A load balancer distributes traffic within a service; a gateway routes across services and applies cross-cutting policy such as auth and rate limiting. A gateway also load balances, but its job is the routing and the policy for the whole API surface, not one service.
- Does the gateway become a bottleneck?
- It can, because every request passes through it. Keep it thin, scale it horizontally, and avoid putting slow or blocking work in it. Its state should be minimal, and its policy checks should be fast or cached, so it adds little latency and no single point of failure.
Report a problem with this articleOpens a pre-filled issue on GitHub.