API gateway
medium 24 minAn API gateway is the single front door for client requests.
Video lesson · Chapter 1 of 6
Follow one cart request
API gateway
1:18Reel
Theory
Read or listen first. About 1 min.
What it is
An API gateway is a server that stands between clients and your services. Clients know one address. The gateway looks at each request, does the work that every request needs, and passes it to the service that can answer it.
It is a reverse proxy that understands your API: paths, methods, tokens and limits. A load balancer spreads calls over copies of one service; a gateway chooses which service.
Why it exists
With ten services and no gateway, every client must know ten addresses, and every service must repeat TLS, token checks, limits and logging. Moving or splitting a service breaks the clients.
A gateway puts those shared jobs in one place and hides the inside of the system. The price is an extra hop and a part that everything depends on, so it must be small, fast and redundant.
A short history
4 October 2004
Igor Sysoev's NGINX is released. It becomes a widely used reverse proxy, the base of many gateways.
9 July 2015
Amazon API Gateway is introduced as a managed service.
18 September 2015
Phil Calçado describes the back-end for front-end pattern from work at SoundCloud.
18 November 2015
Sam Newman writes up Backends For Frontends as an alternative to one general gateway.
31 October 2023
The Kubernetes Gateway API reaches version 1.0.
Words to know
- Reverse proxy
- A server that receives requests for other servers and passes them on.
- Edge
- The border between the internet and your system.
- TLS termination
- Decrypting HTTPS at the gateway, which holds the certificate.
- Upstream
- The service behind the gateway that a request is sent to.
- Cross-cutting concern
- A job every service needs: authentication, limits, logging.
- Aggregation
- One client call that the gateway answers from several services.
- BFF
- Backend for frontend: a separate gateway made for one kind of client.
How it works
Step through the idea, or press Play.
Receive and check. TLS, address rules, caller, limits, shape
Understand it
Start here
The clinic reception story
A gateway is like the receptionist of a clinic. Patients do not need to know which doctor sits where. They walk up to one desk.
The receptionist checks and directs. They do not treat patients: business logic stays in the services.
With a gateway
- One address for clients
- Authentication checked in one place
- The same limits everywhere
- Simple client code
Without one
- Clients manage many addresses
- Each service repeats the checks
- No shared limits
- Complex client code
One front door, four services
Routing
From a public path to a service
The shop's routes
| Client asks | Gateway sends to | Public? |
|---|---|---|
GET /api/products | product-service:8002/products | Yes |
POST /api/products | product-service:8002/products | No |
GET /api/cart | cart-service:8003/cart | No |
POST /api/orders | order-service:8004/orders | No |
POST /api/auth/login | user-service:8001/auth/login | Yes, with a strict limit |
GET /api/users/42 | user-service:8001/users/42 | No |
Who owns which path
| Service | Paths |
|---|---|
| User | /users, /users/:id, /auth/login, /auth/register |
| Product | /products, /products/:id, /categories, /search |
| Cart | /cart, /cart/items, /cart/checkout |
| Order | /orders, /orders/:id, /orders/:id/status |
How does the gateway know which copies of a service are alive? From a registry or the platform's own names: see service discovery.
Jobs
What a gateway does
Routing
By path, method, header or query. One entry point for all requests.
Authentication
Verifies tokens, keys and certificates early. Services still check their own objects.
Rate limiting
Stops single callers from using everything. It is one layer against floods, not full DDoS protection.
Load balancing
Chooses a healthy copy of the target service.
TLS termination
One place for certificates. Encrypt again towards services when the network is not trusted.
Caching
Keeps frequent public answers close to the client.
Transforming
Adds or removes headers, changes formats, maps old versions, REST to gRPC.
Logs, metrics, traces
One record per request, with an ID that follows it everywhere.
The pipeline of one request
When a check fails
| Check | Question | Answer on failure |
|---|---|---|
| Address | Is this address on the block list, or missing from a private allow list? | 403 |
| Limit per address | Too many requests from here? | 429 |
| Token or key | Valid? | 401 |
| Limit per caller | Within the quota? | 429 |
| Scope | Does the token allow this endpoint? | 403 |
| Shape | Does it match the OpenAPI schema and size? | 400, or 413 when too large |
| Upstream | Did the service answer in time? | 502, 503 or 504 |
Aggregation
One call instead of three
A phone's home page needs profile, cart and recommendations. Over a slow mobile network three calls hurt. The gateway can ask all three services at once and send one answer.
Time saved
Aggregation with a partial answer
More calls, more chances to fail
BFF
A gateway for each kind of client
A phone wants small answers. A website wants rich ones. Partners want something that never changes. One gateway for all of them grows special cases. The backend for frontend pattern gives each client type its own small gateway.
Three backends, the same services
What each one is made for
| BFF | Gives |
|---|---|
| Mobile | Small payloads, compressed images, data for offline use |
| Web | Rich data, server rendering, perhaps a GraphQL interface |
| Partner | A stable versioned API, limits per partner, webhooks |
{"GET /mobile/home": { "products": [{"id": 1, "name": "Desk lamp", "thumbnail": "50x50"}], "cart_count": 3, "unread_notifications": 2}, "GET /web/home": { "products": [{"id": 1, "name": "Desk lamp, oak", "image": "400x400", "specs": {}, "reviews": []}], "cart": {"items": []}, "recommendations": []}}One gateway or BFF?
| Single gateway | BFF | |
|---|---|---|
| Clients | Similar | Very different |
| Effort | Lower | Higher: more to build and run |
| Answers | General | Made for each client |
| Teams | One gateway team | Each client team owns its BFF |
| Best for | Small systems | Large teams, different clients |
Security
What the edge protects
| Area | At the gateway |
|---|---|
| Identity | Verify JWTs, partner keys and client certificates (mTLS) |
| Traffic | Limits, address lists, bot rules; large floods belong to a CDN or DDoS service in front |
| Requests | Schema check, size limit, allowed methods and content types |
| Data | TLS, browser origin rules (CORS), removing fields that must not leave |
Should the service trust the gateway?
Failure
Keep the door open
- 1
Run several copies
At least two, in two zones, with no state of their own, behind a load balancer.
- 2
Limit waiting
A timeout per route, shorter than the client's. A slow service must not use up all connections: cap the calls in flight per upstream.
- 3
Break the circuit
Stop calling a service that keeps failing, and answer 503 quickly. See circuit breaker.
- 4
Change configuration carefully
A wrong route breaks everything at once. Review it, test it, roll it out to one copy first, and keep the previous version ready.
- 5
Keep enough room
If one of three copies dies, the other two carry 50% more each.
How many copies?
Advantages
- One entry point simplifies clients
- Shared security and monitoring
- Request and response changes
- Protocol translation, such as REST to gRPC
- Balancing and discovery in one place
- Easier versioning
Costs
- A single point of failure if you run one
- An extra hop and a little latency
- Configuration that grows
- Needs high availability
- Can become the bottleneck
- More to pay for and run
Neighbours
Gateway, load balancer, service mesh
| API gateway | Load balancer | Service mesh | |
|---|---|---|---|
| Traffic | From clients into the system | Any, to one pool | Between services |
| Knows | Paths, tokens, callers | Connections or HTTP | Services and their identity |
| Main job | One API, edge checks | Spread load | mTLS, retries, telemetry inside |
| Runs as | A few shared copies | A managed service or pair | A proxy beside each service, or per node |
Tools
Popular gateways
Products
| Product | Kind | Often chosen for |
|---|---|---|
| Kong | Open source core, paid edition | Plugins, Kubernetes |
| Amazon API Gateway | Managed, pay per request | AWS systems, serverless |
| NGINX | Open source, paid edition (Plus) | Speed, simple rules |
| Envoy | Open source | Edge and service mesh data plane |
| Traefik | Open source, paid edition | Docker and Kubernetes |
| Apigee | Managed by Google Cloud | Enterprise API programmes, analytics |
Decide
Do you need one?
Three questions
Use a gateway when
- There are several services
- Web, mobile and other clients call you
- You want shared authentication and limits
- You need versioning or translation
- You want one place for logs
Consider less when
- One simple monolith
- One kind of client
- Very little traffic
- Nothing to translate
- You cannot run more than one copy
Summary
The whole topic in one minute.
A gateway gives clients one address and services one place for shared work: TLS, token checks, limits, routing, logs. Keep business rules out of it.
It sits in front of everything, so run several copies, keep configuration safe to change, set timeouts, and let each service still check what it must. Split it per client type only when the clients truly differ.
- One address outside, many services inside.
- Shared jobs: TLS, identity, limits, routing, logs. No business rules.
- Aggregate in parallel, with timeouts and optional parts.
- Strip identity headers from outside, and let services check their own objects.
- Run several copies and treat configuration like code. Use BFFs only for truly different clients.