27.8. API Gateways
Table of Contents
Why API Gateways Exist
In a simple backend, a client talks directly to one server, for example a single REST API. In more complex systems, especially with microservices, there are many backend services, each with its own API.
Without an API gateway:
- The client must know the address of every service.
- The client must understand different authentication methods.
- The client must manage many network calls.
- Every client change may require changes in many services.
An API gateway sits between clients and backend services and acts as a single entry point.
Client → API Gateway → Many backend services
This lets you:
- Hide internal service details.
- Centralize cross‑cutting concerns like authentication, rate limiting, logging.
- Present a simpler, stable API to clients even if internals change.
Key idea: An API gateway is the single public front door to your backend, routing and shaping traffic to internal services.
Core Responsibilities of an API Gateway
Request Routing
The most basic job of an API gateway is to send each client request to the correct internal service.
Examples:
GET /users/123→ User serviceGET /orders/456→ Order servicePOST /payments→ Payment service
A typical routing table might look like this:
| Path prefix | HTTP method | Target service | Example URL |
|---|---|---|---|
/users | any | user-service | /users/42 |
/orders | any | order-service | /orders/1001 |
/products | any | product-service | /products?category=TV |
/auth | any | auth-service | /auth/login |
The gateway inspects:
- The path, for example
/users/42 - The HTTP method, for example
GET,POST - Optionally headers or query parameters
Then it forwards the request to the appropriate backend URL, for example http://user-service.internal/api/users/42.
From the client view, there is only one base URL, such as:
https://api.example.com
The gateway hides internal network details like:
http://user-service.internal:8000http://order-service.internal:9000
Aggregation (API Composition)
Sometimes the client needs data that lives in multiple services. Without a gateway, the client would have to call each service itself.
Example: A mobile app dashboard needs:
- User profile from
user-service - Recent orders from
order-service - Recommendations from
product-service
Instead of making 3 separate calls from the app, the gateway can:
- Receive
GET /me/dashboard. - Call:
GET /internal/users/meGET /internal/orders?user_id=123&limit=5GET /internal/recommendations?user_id=123- Combine results into one response and return it to the client.
Benefits:
- Fewer network calls for the client.
- The gateway can adjust how it aggregates data for different clients (web vs mobile) without changing internal services.
Centralized Authentication and Authorization
The gateway can sit in front of your auth logic and enforce security rules.
Typical tasks:
- Validate access tokens, for example JWTs:
- Verify signature.
- Check expiration (
exp). - Check issuer (
iss) and audience (aud). - Extract user information, for example user id, roles, permissions, and forward this to services through headers.
- Block unauthorized requests before they reach services.
Example flow:
- Client sends
Authorization: Bearer <token>toapi.example.com. - Gateway verifies token using a public key.
- If invalid, it returns
401 Unauthorized. - If valid, it sets headers like:
X-User-Id: 123X-User-Roles: admin,editor- Backend services trust the gateway and use these headers instead of parsing the token themselves.
Important: With a gateway, services can be simpler and safer by offloading authentication and many access checks to the gateway.
Rate Limiting and Throttling
To protect your backend from abuse and overload, the gateway can limit:
- How many requests a client can send per second or per minute.
- How many concurrent connections are allowed.
Examples:
- Limit each API key to
1000requests per hour. - Limit anonymous IP addresses to
10login attempts per minute. - Block IP addresses that exceed limits.
Typical strategies:
| Strategy | Description |
|---|---|
| Fixed window | Count per fixed period, for example per minute. |
| Sliding window | Count over a moving time window. |
| Token bucket / leaky | Allow bursts but maintain average rate. |
Instead of implementing this in every service, you configure it once in the gateway.
Request and Response Transformation
The gateway can modify:
- Paths and query strings.
- Headers.
- Request or response bodies.
Common transformations:
- Path rewriting
Client:/api/v1/users/123
Internal:/users/123 - Header normalization
AddX-Request-Idto every request for tracing. - Body adaptation
Convert fields for backward compatibility, for example: - Internal service returns
{ "given_name": "Alice" } - Gateway returns
{ "firstName": "Alice" }to old clients.
This makes it possible to evolve internal services without breaking public APIs.
API Gateway vs Reverse Proxy vs Load Balancer
These terms are related and sometimes overlap, but they are not identical.
| Component | Main purpose | Typical layer |
|---|---|---|
| Load balancer | Distribute traffic across identical servers | Network / transport level |
| Reverse proxy | Forward requests to backend servers | HTTP level |
| API gateway | Manage and expose APIs with rich features | Application / API level |
Reverse Proxy
A reverse proxy forwards incoming HTTP requests to one or more backend servers. It often:
- Handles TLS termination (HTTPS).
- Performs basic routing and load balancing.
- Caches static responses.
Example tools: Nginx, Apache HTTP Server, HAProxy.
Load Balancer
A load balancer spreads incoming traffic across many instances of the same service, for example:
Client → Load balancer → 3 instances of api-service
It aims to:
- Increase capacity.
- Improve availability.
Some reverse proxies also act as load balancers, for example Nginx.
API Gateway
An API gateway is usually built on top of reverse proxy capabilities and adds:
- API routing by path, method, or host.
- Authentication and authorization.
- Rate limiting and quota management.
- API keys and developer portal.
- Monitoring and analytics.
- Request and response transformations.
- API versioning support.
You can think of an API gateway as a smart reverse proxy specialized for APIs.
Rule of thumb: Every API gateway is a reverse proxy, but not every reverse proxy is a full API gateway.
Typical Features of API Gateways
Authentication and API Keys
Gateways often support:
- API keys for each client or application.
- Token based authentication, for example OAuth 2.0, JWT.
- Mutual TLS (client certificates) for secure internal communication.
Examples:
- A public API requires an
X-API-Keyheader. The gateway: - Validates the key.
- Checks if the plan, for example free or paid, allows this endpoint.
- A private REST API for your frontend uses JWT:
- Gateway validates JWT on each request.
- Denied if invalid or expired.
Rate Limiting and Quotas
Gateways often provide configurable policies, such as:
- Per IP, for example
10requests per second. - Per user or API key, for example
10000requests per day. - Per endpoint, for example stronger limits on
POST /login.
The configuration is usually declarative. For example, in pseudocode:
routes:
- path: /v1/*
rate_limit:
key: api_key
limit: 1000
window: 1hCaching
Gateways can cache responses to reduce load on services.
Examples:
- Cache
GET /productsfor60seconds. - Respect HTTP cache headers like
Cache-ControlandETag.
This is especially useful for:
- Data that does not change often, for example product catalogs.
- Heavy computations, for example search results.
Monitoring, Metrics, and Logging
Since all traffic goes through the gateway, it is a great place to collect:
- Request counts per endpoint.
- Latency (response time).
- Error rates, for example 5xx responses.
- Usage per client, team, or API key.
Many gateways provide dashboards to visualize:
- Traffic spikes.
- Slow endpoints.
- Most used APIs.
The gateway can also add correlation ids such as X-Request-Id to help trace requests across services.
Versioning and Routing by Host
Gateways make it easier to manage API versions and multiple APIs.
Examples:
- Version in the path:
/v1/users→ old services./v2/users→ new services.- Version in the host:
v1.api.example.com→ old services.v2.api.example.com→ new services.
You can perform canary releases, routing a small percentage of traffic to a new version.
Request Validation and Security Filters
Some gateways can:
- Validate request schema against OpenAPI definitions.
- Filter out malformed or oversized requests.
- Block requests to certain paths or methods.
- Enforce HTTPS and specific security headers.
This gives you a basic security layer before your own code runs.
Example API Gateway Flows
Simple Routing Example
Imagine you have 3 microservices:
user-serviceathttp://users.internal:8000order-serviceathttp://orders.internal:8001product-serviceathttp://products.internal:8002
Your public domain is https://api.shop.com.
The gateway config might say:
routes:
- path_prefix: /users
upstream: http://users.internal:8000
- path_prefix: /orders
upstream: http://orders.internal:8001
- path_prefix: /products
upstream: http://products.internal:8002Requests:
GET https://api.shop.com/users/42→GET http://users.internal:8000/users/42POST https://api.shop.com/orders→POST http://orders.internal:8001/ordersGET https://api.shop.com/products?category=books→ forwarded toproduct-service
Aggregation Example
Add a new endpoint to the gateway:
GET /me/summary
Gateway logic, in pseudocode:
@app.get("/me/summary")
def summary(request):
user_id = request.headers["X-User-Id"]
profile = http_get(f"http://users.internal:8000/users/{user_id}")
orders = http_get(f"http://orders.internal:8001/orders?user_id={user_id}&limit=3")
return {
"user": profile.json(),
"recent_orders": orders.json(),
}The client makes a single request and gets combined data from multiple services.
Basic Token Validation Example
Gateway middleware pseudocode:
def auth_middleware(request, next_handler):
token = extract_bearer_token(request.headers.get("Authorization", ""))
if not token:
return Response(status_code=401, json={"detail": "Missing token"})
try:
payload = jwt_decode(token, public_key)
except InvalidTokenError:
return Response(status_code=401, json={"detail": "Invalid token"})
# Attach user info to the request
request.headers["X-User-Id"] = payload["sub"]
request.headers["X-User-Roles"] = ",".join(payload.get("roles", []))
# Pass request to route handler or upstream service
return next_handler(request)All services behind the gateway can assume that:
- Requests without valid tokens are already filtered out.
- They will always receive
X-User-IdandX-User-Rolesheaders.
Common API Gateway Products and Tools
You do not have to write an API gateway from scratch. Many tools exist.
| Category | Examples |
|---|---|
| Cloud managed gateways | AWS API Gateway, Azure APIM, GCP APIG |
| Open source gateways | Kong, Tyk, KrakenD, APISIX |
| Service mesh gateways | Istio Gateway, Linkerd ingress |
| Reverse proxies with plugins | Nginx, Traefik, Envoy |
For backend development with Python and FastAPI, you will often see:
- Nginx or Traefik used as a simple gateway or reverse proxy.
- Kong or Envoy in more advanced systems.
- Cloud gateways in managed environments, for example AWS.
Each product differs in configuration format, but conceptually they all provide:
- Routes and upstreams.
- Security and rate limiting.
- Logging and monitoring.
Benefits and Trade‑Offs
Benefits
- Single entry point
Clients use one base URL and one security model. - Simplified clients
Less logic in frontend or external applications. - Centralized cross‑cutting concerns
Authentication, rate limiting, logging, caching are managed in one place. - Flexibility for internal services
You can: - Change service URLs.
- Split or merge services.
- Change internal payloads, while keeping the external API stable.
- Improved observability
You can easily measure API usage, errors, and performance.
Trade‑Offs and Risks
- Single point of failure
If the gateway is down, your whole API is unavailable. You must design it to be highly available. - Additional latency
Every request passes through one more network hop and processing layer. Usually small, but it exists. - Complex configurations
Rules can become complex, especially in large systems. You need good processes for versioning and testing gateway configs. - Too much logic in the gateway
If you move too much business logic to the gateway, it becomes hard to maintain. Use the gateway mainly for cross‑cutting concerns and light composition.
Good practice: Keep business rules inside your services, and use the API gateway mainly for routing, security, and common infrastructure concerns.
API Gateways in a Microservices Architecture
In a microservices system, you often have this structure:
Client → API Gateway → Many microservices
Internally, you might also have:
- One gateway for external clients.
- Another internal gateway for communication between services.
- A service mesh for service to service networking.
Typical pattern:
- The public API gateway:
- Handles external traffic from browsers, mobile apps, third‑party integrations.
- Enforces strong security, rate limiting, and quotas.
- Exposes stable, consumer friendly APIs.
- The internal gateway or mesh:
- Manages communication between microservices.
- Handles mutual TLS, retries, and service discovery.
You do not need this complexity at the beginning, but it is important to understand how gateways fit into larger architectures.
When You Need an API Gateway
In small systems, a simple reverse proxy like Nginx in front of a single backend application is enough. You should consider an API gateway when:
- You have multiple backend services that clients must call.
- You want to expose a public API to external developers.
- You need strong, centralized control over:
- Authentication and authorization.
- Rate limits and quotas.
- API keys and billing.
- You want analytics and dashboards for your API usage.
- You need to support multiple versions of your API for a long time.
For many beginner projects, you will:
- Start without a gateway, or with a simple reverse proxy.
- Introduce an API gateway when your architecture grows or when you expose stable public APIs.
Example: Simple API Gateway Design for a Backend Project
Imagine you built several FastAPI services:
auth-apifor authentication.user-apifor user profiles.shop-apifor products and orders.
You want:
- One public domain:
https://api.example.com - JWT based authentication.
- Rate limiting per user.
A minimal design:
- Use an API gateway (for example Kong or AWS API Gateway).
- Configure routes:
/auth/*→auth-api/users/*→user-api/shop/*→shop-api- Configure auth:
- For
/auth/*: - Allow anonymous requests for
/loginand/register. - For
/users/and/shop/: - Require valid JWT.
- Extract
user_idand forward as header. - Configure rate limits:
- Logged in users:
2000requests per hour. - Anonymous endpoints:
50requests per hour per IP.
This setup gives you:
- A single, secure entry point.
- Centralized policies.
- Simpler, more focused microservices behind the gateway.
Views: 6
KAHIBARO