Cloud & Data Centers

API Gateways Explained

What an API gateway does between clients and services: routing, authentication, rate limits, logging, and when you need one.

Key takeaways

  • An API gateway is a single entry point that routes requests to the right backend service.
  • It commonly handles encryption, authentication, rate limiting, logging and some request transformation.
  • Services behind the gateway still need to check that each user may access the specific data requested.
  • Because all traffic passes through it, a gateway must be redundant, monitored and configured carefully.
  • A single small application often needs only a load balancer or reverse proxy.

An API gateway is a server that stands in front of your APIs and receives requests before your own services do. It checks who is calling, applies limits, decides which service should handle the request, forwards it and returns the answer. Clients see one consistent address, even if many separate programs sit behind it.

An API (application programming interface) is the set of requests a program accepts from other programs. Once you have several APIs, or outside developers using them, handling the same chores in every service gets repetitive and inconsistent. A gateway collects those chores in one place.

The problem it solves

Say a hypothetical shop app has separate services for products, carts, orders and accounts. Without a gateway, the mobile app needs to know four addresses, and each team must implement certificates, token checks, abuse limits and logging on its own. One team will do it differently, or forget.

With a gateway, the app calls api.example.com. The gateway looks at the path and method and sends /products to one service and /orders to another. You can split, merge or move services without changing what clients see.

This is especially handy when breaking a large application into parts, a trade-off discussed in microservices vs monoliths.

What happens to a request

A request's trip through a gateway
1 Accept Terminate TLS and check basic form 2 Identify Validate the API key or access token 3 Limit Count the call against a quota 4 Route Match path and method to a service 5 Forward Send on, with a timeout 6 Respond and record Return the reply, log and count it Accept Terminate TLS and check basic form 1 Identify Validate the API key or access token 2 Limit Count the call against a quota 3 Route Match path and method to a service 4 Forward Send on, with a timeout 5 Respond and record Return the reply, log and count it 6

If any early check fails, the request stops there. A missing or invalid credential typically gets 401 Unauthorized; a valid caller without permission gets 403 Forbidden. The difference is explained in 401 versus 403.

Routing and versioning

Routing rules match on host name, path, method or headers. They enable useful moves:

  • Sending /v1/ and /v2/ to different versions while clients migrate.
  • Directing a small share of traffic to a new release and widening it if errors stay low.
  • Retiring an old service by redirecting its paths one at a time to a replacement.

The gateway can also rewrite paths and headers, or translate between protocols, for example offering a REST-style interface over an internal service that uses something else. Use transformation sparingly. Business logic hidden in gateway configuration is hard to test and easy to forget.

A routing table might read like this in plain form. The names are placeholders, and each product has its own configuration syntax.

Method  Path             Send to          Rule
GET     /v1/products/*   catalog-service  public, cached 60s
POST    /v1/orders       order-service    token required
GET     /v1/orders/*     order-service    token required
ANY     /v1/admin/*      admin-service    internal network only

Anything that matches no row should be refused. An explicit list means a new internal endpoint doesn't become public just because someone deployed it. Be careful with broad wildcards, and check how your gateway treats trailing slashes, letter case and encoded characters, since a mismatch between the gateway's reading of a path and the service's can let a request slip past a rule.

Authentication and authorization

A gateway can verify API keys, validate signed tokens such as JSON Web Tokens, or work with an identity provider. API keys, tokens and OAuth explains what each one proves.

An API key mainly identifies a calling application. It's a weak way to identify a person, and a key embedded in a mobile app or web page can be extracted.

Authorization has two levels. The gateway can enforce coarse rules, such as "this client may call order endpoints". Only the order service usually knows whether this user owns order 1234. That check belongs in the service. Skipping it because "the gateway handles security" is a serious and common design flaw.

Also make sure services can't be reached by going around the gateway. Restrict them with network rules and, where possible, require the gateway to prove its identity.

Rate limits and quotas

Limits protect services from runaway scripts, buggy clients and abuse, and let you offer different service levels. A rate limit caps requests over a short window; a quota caps usage over a longer period such as a day or month.

A common method is the token bucket. Tokens are added to a bucket at a steady rate up to a maximum, and each request spends one. Short bursts are fine while tokens are saved up; sustained excess is refused.

When a caller exceeds the limit, the usual response is 429 Too Many Requests, ideally with a Retry-After header:

HTTP/1.1 429 Too Many Requests
Retry-After: 30
Content-Type: application/json

{"error": "rate_limited", "message": "Try again in 30 seconds"}

Well-behaved clients wait and retry with increasing delays. The retry and backoff simulator shows how different strategies spread out the load.

Reliability features

Gateways often help contain failures:

  • Timeouts stop requests from waiting forever on a slow service.
  • Retries can recover from brief errors, but should be limited to operations safe to repeat. Retrying a payment blindly may charge twice.
  • Circuit breakers stop sending to a failing service for a while, giving it room to recover.
  • Caching answers repeated, safe requests without touching the backend. Be careful never to serve one user's data to another.
  • Health checks remove unhealthy instances from rotation.

When the gateway can't get a good answer from a service, clients tend to see 502 or 504 errors. Logs should say which service and why.

Validating and protecting input

A gateway can reject obviously bad requests early: bodies that are too large, wrong content types, missing required fields or payloads that don't match a published schema, a formal description of the expected shape. Many gateways can import an OpenAPI description of your API and enforce parts of it.

Early rejection saves work and narrows what reaches your code. It doesn't replace validation inside the service, which knows the business rules, such as whether a quantity makes sense or a discount code belongs to this customer.

Browser clients bring one more chore. If a web page on one origin calls your API on another, the browser applies cross-origin resource sharing (CORS) rules, and the gateway is often where those response headers are set. List the origins you trust. CORS controls what browsers let pages read; it isn't authentication, and other programs ignore it.

Observability

Since every call passes through, the gateway is a natural place to measure your APIs. Useful numbers include request rate, the share of errors, and response time at the median and at the slow end, broken down by route and by client.

Have the gateway attach a unique request ID to each call and pass it to the services. When a customer reports a failure, that one value lets you follow the request through every log. Separate the time spent in the gateway from the time spent waiting for the service, or you'll argue about which one is slow.

Gateway, load balancer or reverse proxy?

The categories overlap, and one product may do all three.

Three front doors with overlapping jobs
Reverse proxy Forwards requests to servers Often handles TLS and caching General web use Load balancer Spreads traffic across instances Health checks Focus on availability and capacity API gateway Routes by API operation Keys, tokens and quotas Per-client usage and analytics Reverse proxy Forwards requests to servers Often handles TLS and caching General web use Load balancer Spreads traffic across instances Health checks Focus on availability and capacity API gateway Routes by API operation Keys, tokens and quotas Per-client usage and analytics

A load balancer answers "which copy of this service should take the request?" A gateway also asks "who is this caller, what may they call and how much?"

You may also hear about a service mesh, which manages traffic between internal services, often through small proxies beside each one. Gateways mainly handle traffic coming in from clients.

Another pattern is a backend for frontend: a separate gateway or thin service for each kind of client, so a mobile app can get one compact response while a web dashboard gets a richer one.

Costs and risks

A gateway adds a hop, so a little latency, plus another system to run and pay for. Managed gateways often bill per request or by capacity; check pricing against your expected volume.

It's also a concentration point. A bad configuration can break every API at once, and an outage stops all traffic. Run more than one instance across zones, keep configuration in version control, review changes and roll them out gradually.

Logs deserve care too. Don't record authorization headers, keys, passwords or personal data in URLs. Restrict who can read logs and decide how long to keep them.

Do you need one?

You probably do if you have several services behind one public API, outside developers needing keys and quotas, or repeated security code across teams.

You probably don't yet if you have a single application with its own web front end. A reverse proxy or load balancer with sensible limits is simpler.

When choosing, check:

  1. Which authentication methods it supports.
  2. How limits are counted across multiple instances.
  3. Whether configuration can be exported and managed as code.
  4. What you can see in logs, metrics and traces.
  5. How tightly it ties you to one provider.
  6. How it behaves with large uploads, streaming responses and long-lived connections, which some gateways restrict.

Start with the few features you need. Every rule you add is one more thing to understand when a request fails in the middle of the night.

Written for 4Internet with AI writing tools and not reviewed line by line by a person. Check anything you rely on with the maker, provider or standard concerned. Report an error.

Keep reading

All 45 articles in Cloud & Data Centers →

Latest news on this topic