Skip to content

API Gateway and Backend-for-Frontend

Intermediate 40 min read Part 4 of 18

What an API gateway does (routing, auth, rate limits, transformation, aggregation), the BFF pattern, gateway vs LB vs mesh, and how to scale it safely.

Summary#

An API gateway is a reverse proxy that is the single entry point for client requests to many backend services. It handles the cross-cutting work every API needs: routing, authentication, rate limiting, TLS termination, request transformation, response aggregation, caching and observability. Services then focus on business logic. A Backend-for-Frontend (BFF) is a gateway-like layer built for one client type (web, iOS, partner) that shapes responses for that client's screens. Keep gateways thin: if business logic creeps in, the gateway becomes a "god gateway" that every team must change and that can take the whole system down.

Why It Exists#

With microservices, a single screen might need data from five services. Without a gateway, each client must know every service's address, authenticate to each one, handle each one's errors and make many round trips over a slow mobile network. Every service must also re-implement auth checks, rate limits, logging and TLS.

A gateway moves those shared concerns to one place and gives clients one stable address, even as services are split, merged or moved behind it. It builds on Proxies and Reverse Proxies and applies the rules from API Design consistently.

How It Works#

The core job is routing#

It is easy to describe a gateway as a bag of middleware and forget why it exists at all. The first reason is request routing: clients call one address, and the gateway decides which of many backend services should answer. Authentication, rate limiting and the rest are valuable, but they are things the gateway does while routing. In an interview, if you add a gateway and list ten middleware features without saying "it routes /users to the user service and /orders to the order service", you have skipped the main point. Say the routing first, then name only the middleware that matters for this problem.

A useful mental model is that the gateway decouples the external API surface from the internal service layout. Clients see a stable set of paths. Behind them, you can split a service in two, merge two services, move one to another cluster or rewrite it in another language. The only thing that changes is a line in the routing table, and no client needs a new release. That decoupling is what makes microservices manageable for mobile apps that cannot be updated on demand.

Responsibilities#

ResponsibilityWhat the gateway doesExample
RoutingMaps path, host, method or header to a backend service and version/v1/orders/* to order-service; 5% of traffic to the canary
AuthenticationValidates tokens (JWT signature and expiry, API keys, OAuth) and passes the caller's identity onAdds X-User-Id after verifying the JWT
Coarse authorisationChecks scopes or plans before the request reaches a serviceReject a write:orders call from a read-only key
Rate limiting and quotasLimits per user, API key, IP or plan100 req/s per key, 1M calls/month on the free plan
TLS terminationDecrypts HTTPS once at the edge; may re-encrypt (mTLS) to servicesCertificates managed in one place
Request transformationRewrites headers, paths and bodies; translates protocolsREST/JSON outside to gRPC inside
AggregationCalls several services and merges the results into one responseHome screen = profile + feed + notifications count
CachingCaches shared GET responses for seconds or minutesProduct catalog cached for 30 s
ObservabilityLogs, metrics and traces for every request; adds a request IDp99 latency per route, error rate per client

Other common features: request size limits, IP allow and deny lists, CORS handling, API key management, developer portals and usage analytics for billing.

Fine-grained authorisation ("can this user edit this document?") belongs in the service that owns the data. The gateway answers "who are you and are you allowed to call this API at all"; the service answers "may you do this to this object". See Authentication and Authorization.

Request flow#

Steps, in order: terminate TLS, match a route, authenticate, check the rate limit, transform the request, forward with a timeout (and maybe retry), transform and possibly cache the response, record metrics and traces. Each step adds latency; a well-run gateway adds roughly 1-5 ms. Token checks stay fast because the gateway caches the identity provider's public keys (JWKS) and validates JWTs locally rather than calling the auth server on every request. See Rate Limiting for how the counter works.

The request lifecycle in depth#

Every request goes through the same ordered pipeline. The order matters: cheap checks come first, so bad traffic is rejected before it costs anything.

1. Request validation. Before any real work, the gateway checks that the request is well formed: a known path, the required headers (for example an API key or Authorization header), a body under the size limit, and, if a schema is configured, a body that matches it. A mobile app that sends malformed JSON or forgets its API key gets a clear 400 or 401 straight from the gateway. Without this step, the request would travel through the network, wake up a service, open a database connection, and fail there anyway. Early rejection is cheap rejection. It also protects services from oversized payloads, which are a common way to exhaust memory.

2. Middleware. This is the configurable chain of cross-cutting features. The full menu that gateways offer is long:

  • authenticating requests, usually by verifying JWTs or API keys;
  • rate limiting and throttling, to protect against abuse and overload;
  • terminating TLS, so services can speak plain HTTP or re-encrypted mTLS internally;
  • logging and monitoring every request;
  • compressing responses (gzip or Brotli) to save bandwidth;
  • answering CORS preflight requests and adding CORS headers for browser clients;
  • allow and deny lists of IP addresses or ranges;
  • enforcing request size limits;
  • enforcing response timeouts, so a slow backend fails fast;
  • routing by API version;
  • integrating with service discovery, so the gateway learns where instances live.

Throttling and rate limiting are related but not identical. Rate limiting usually rejects requests above a limit with 429. Throttling may instead slow them down, queue them, or shape traffic to a steady rate. In interviews, three middleware items matter far more than the rest: authentication, rate limiting and IP allow or deny lists. Mention the ones that matter for your problem, with a reason, and move on. A good default sentence is: "I'll put an API gateway in front to handle routing and the usual middleware like auth and rate limiting."

3. Routing. The gateway keeps a routing table that maps a request to a backend. The match can use:

  • the URL path, for example everything under /users/ goes to the user service;
  • the HTTP method, for example GET /orders to a read replica service and POST /orders to the writer;
  • query parameters, for example ?beta=true to a new version;
  • request headers, for example X-Client: ios to the mobile backend, or a canary header to a new release.
routes:
  - match: { path_prefix: /users/ }
    service: user-service
    port: 8080
  - match: { path_prefix: /orders/ }
    service: order-service
    port: 8081
  - match: { path_prefix: /payments/ }
    service: payment-service
    port: 8082

Route matching has precedence rules that are a frequent source of bugs. Most gateways prefer exact matches over prefix matches, longer prefixes over shorter ones, and then configuration order. A catch-all / route pointing at a legacy monolith is common during migrations, and it must sit last, or it will swallow every request. Lookups are fast: routing tables are compiled into tries or hash maps, so matching costs microseconds even with thousands of routes.

Routing is also where traffic management lives. Weighted routing sends, say, 5% of traffic to a canary version and 95% to the stable one. Header-based routing lets internal testers reach a new version in production. Shadowing (or mirroring) copies live requests to a new service and discards its responses, so you can compare behaviour under real load without risk.

4. Backend communication. Most of the time the gateway forwards HTTP to HTTP. Sometimes services speak gRPC internally, because it is compact and fast. The gateway can then translate protocols: it accepts JSON over HTTP from clients and calls the service over gRPC. This is less common than people assume, since many teams simply expose HTTP from every service, but it is valuable when browsers and third parties need plain REST while the internal platform is gRPC. Envoy's gRPC-JSON transcoder and Google's Cloud Endpoints are well-known examples. Translation is not free: the gateway must know the protobuf schemas, and every schema change must be deployed to the gateway too.

The gateway also picks which instance of the service receives the request. It asks service discovery for the healthy instances and balances across them, usually with round robin or least-requests. It keeps a pool of warm connections to each service, so most requests skip the TCP and TLS handshakes. Connection reuse is one of the quiet performance wins of a gateway: thousands of short client connections become a few hundred long-lived upstream connections.

5. Response transformation. On the way back, the gateway can reshape the response into what the client expects. For example:

Client sends:        GET /users/123/profile  (HTTP, JSON expected)
Gateway calls:       userService.GetProfile, user_id 123  (gRPC)
Service returns:     a protobuf Profile message
Gateway returns:     200 with JSON: userId 123, name, email

Other common transformations: removing internal headers (server versions, debug IDs), renaming fields for an old API version, adding standard headers (request ID, rate-limit headers, security headers such as HSTS), and wrapping errors from many services into one consistent error format. The rule of thumb is that transformations should be mechanical, not business decisions. Renaming a field is fine. Calculating a discount is not.

6. Caching. Finally, the gateway can keep a copy of the response. This only makes sense for responses that are the same for everyone given the same input, and that change rarely: a product catalogue, public event details, configuration for app start-up. Per-user responses are risky to cache at a shared layer, because one bug in the cache key can show one user's data to another. Gateways support a few strategies:

  • Full response caching: store the whole response keyed by method, path and selected query parameters, with a TTL.
  • Partial caching: cache the slow, rarely-changing parts, such as the product details, while fetching the fast-changing part, such as stock level, fresh on every request.
  • Invalidation: expire entries by TTL, or purge them when an event says the data changed.

The cache can live in each gateway instance's memory (fastest, but each instance has its own copy and hit rates fall as you add instances) or in a shared store such as Redis (one copy, a network hop of about a millisecond). Even a few seconds of caching can absorb a huge spike. If 50,000 requests per second hit the same event page during a ticket sale, a 5-second cache turns that into roughly one origin request per gateway instance every 5 seconds.

Rate limiting at the gateway in depth#

Rate limiting can live in the client, in each service, or at the edge. The edge is the most popular choice in production, and the reason is simple: blocked requests never reach application servers. The gateway works like a bouncer at the door of a club. Troublemakers are turned away before they get inside, instead of being discovered after they have already used a seat, a database connection and a worker thread. Each service can then spend all its capacity on legitimate traffic.

Who is the client? The gateway can only use what is in the request: the path, the headers, the query string and the caller's IP address. It can technically call a database to learn more, but that adds latency to every request, so good designs avoid it. That leaves three natural keys:

KeyWhere it comes fromGood forWatch out for
User IDThe verified JWT in the Authorization headerLogged-in product APIsOnly works after authentication
IP addressThe connection, or X-Forwarded-For behind a load balancerAnonymous and public endpoints, login pagesMany users share one IP behind NAT, mobile carriers and offices
API keyUsually an X-API-Key headerDeveloper and partner APIsKeys leak, so pair limits with revocation

X-Forwarded-For deserves care. Any client can send that header, so the gateway must trust only the entries added by its own load balancers, typically the right-most addresses, and ignore the rest. Otherwise an attacker sets a new fake IP on every request and never gets limited.

Layered rules. Real systems do not apply one global number. They layer several rules and enforce the most restrictive one that applies:

  • per user, for example 1,000 requests per hour;
  • per IP, for example 100 requests per minute;
  • per endpoint, for example search at 10 per minute but profile reads at 100 per minute;
  • global, for example 50,000 requests per second for the whole API, as a safety net.

If a user has used only 50 of their 1,000 hourly requests but their IP has hit its 100-per-minute limit, the request is blocked. Tiered plans (free, pro, enterprise) are just different numbers for the same rule, chosen by the caller's plan.

The context problem. The gateway knows only what the request carries. A rule such as "premium users get ten times the limit" needs the user's plan. If the plan is not in the token, the gateway would have to look it up on every request. The usual fix is to put the plan or tier as a claim in the JWT when it is issued, or to cache a key-to-plan map in the gateway with a short TTL. Business-specific limits, such as "at most three password resets per account per day", often belong in the service, which has the context.

Where the counters live. With many gateway instances, a counter in one instance's memory sees only that instance's share of traffic. Shared state usually lives in Redis, which adds a dependency and about 0.5 to 1 ms per check. Plan for Redis being slow or down: most systems fail open for rate limits (let traffic through and alert), because rejecting every request is worse than briefly allowing too many. Some keep a local, approximate limit as a fallback. For very high throughput, instances can batch updates, for example syncing local counts to Redis every 100 ms, trading a little accuracy for far fewer round trips. The algorithms themselves (token bucket, sliding window and others) are covered in Rate Limiting.

Authentication at the gateway in depth#

Authentication is the gateway job with the highest stakes, because a mistake here exposes every service at once.

JWT validation without a network call. A JSON Web Token is a signed set of claims: who the user is, when the token expires, and what it may do (scopes). The gateway checks the signature with the identity provider's public keys, which it downloads from a JWKS (JSON Web Key Set) endpoint and caches. It then checks the expiry, the issuer and the audience. All of this runs in microseconds, with no call to the auth server, which is why JWTs suit gateways so well. When the provider rotates keys, the new key appears in the JWKS first, the gateway refreshes its cache, and tokens signed with either key verify during the overlap.

The revocation trade-off. Because validation is local, a stolen JWT works until it expires. Short lifetimes (5 to 15 minutes) plus refresh tokens limit the damage. For instant revocation, the gateway can check a small deny list of revoked token IDs in Redis, which brings back a network hop. Opaque tokens validated by calling the auth server (token introspection) give instant revocation at the cost of 5 to 20 ms per request unless cached.

Passing identity on safely. After verification, the gateway forwards the identity to services, either as the original token or as trusted headers such as X-User-Id and X-Scopes. The gateway must strip any copy of those headers sent by the client, or anyone can claim to be anyone. Services must also only accept traffic from the gateway, enforced with network policy or mTLS. Otherwise an attacker who reaches a service directly can skip the gateway entirely. Some platforms have the gateway mint a short-lived internal token for each request, so services verify a signature instead of trusting a header.

API keys and OAuth. For developer APIs, the gateway looks up the key (cached in memory), finds the owning account and plan, and applies that plan's quotas. Managed gateways bundle this as "API keys and usage plans". For third-party apps acting on behalf of users, OAuth 2.0 access tokens are validated the same way as JWTs or by introspection. Details are in Authentication and Authorization.

The Backend-for-Frontend (BFF) pattern#

One general-purpose gateway serving web, mobile and partners tends to fail all three. Mobile wants small payloads and one call per screen; web wants richer data; partners want stable, versioned resources. A BFF is a separate API layer per client type, usually owned by the team that builds that client.

What a BFF does: aggregates several service calls into one screen-shaped response, removes fields the client does not need, formats data for display, and handles client-specific concerns (mobile app version differences, push tokens). What it should not do: own business rules or data. Those stay in the domain services, so two BFFs never compute the same price differently.

BFFs and gateways are often layered: an edge gateway handles TLS, auth and rate limits for everyone, then routes to the right BFF. GraphQL servers are frequently used as a BFF, since clients choose the fields they need. See API Styles and Client and Mobile Considerations.

Backend-for-Frontend in depth#

Why one general API fails. A web dashboard on a fast office network can make ten calls and render big tables. A phone on a train with 200 ms round trips cannot. If every round trip costs 200 ms and a screen needs five sequential calls, the user waits a second before anything appears. A BFF makes those five calls inside the data centre, where each costs about a millisecond, and returns one response shaped for that screen. It also trims fields: a mobile list view might need 6 of the 40 fields on a product.

Ownership is the point. The pattern works because the team that builds the iOS app also owns the iOS BFF. They can change the shape of a response the same day they change the screen, without negotiating with a central API team. That is why "one BFF per client experience" is the usual rule, not "one BFF per device model". Web, mobile and partner API are typical splits. iOS and Android often share one mobile BFF because their screens match.

Avoiding duplicated logic. The risk is that each BFF reimplements a rule, such as how to compute a delivery estimate, and the copies drift apart. The fix is discipline: BFFs compose and format, while domain services decide. If two BFFs need the same computed value, that computation belongs in a service both call.

Handling partial failures in aggregation. A home screen composed from profile, feed and notifications should not show an error page because notifications timed out. Call the services in parallel, give each a deadline shorter than the client's, and return what you have, with missing sections marked. Decide in advance which parts are essential (the feed) and which are optional (the badge count).

GraphQL as a BFF. A GraphQL server lets each client ask for exactly the fields it needs from one endpoint, which removes much of the reason to write several BFFs. Larger organisations sometimes use a federated graph: each domain team publishes part of the schema, and a router composes them into one graph. The trade-offs are covered in API Styles: caching is harder, and expensive queries need limits on depth and cost.

Gateway vs load balancer vs service mesh#

Load balancerAPI gatewayService mesh
TrafficAny client to many instances of one serviceExternal clients to many services (north-south)Service to service inside the cluster (east-west)
Main jobSpread load, health checksAPI management: auth, quotas, routing, transformationmTLS, retries, timeouts, traffic shifting, telemetry between services
AwarenessConnections or HTTP requestsAPI routes, consumers, keys, plansService identities and calls
Deployed asManaged LB or proxy clusterCentral proxy cluster at the edgeA sidecar proxy next to every instance, plus a control plane
ExamplesAWS ALB/NLB, HAProxyKong, AWS API Gateway, ApigeeIstio, Linkerd

They work together. A typical path is: CDN, then a cloud load balancer, then the gateway cluster (itself spread by that load balancer), then services that call each other through a mesh. See Load Balancing.

Gateway, load balancer and service mesh in depth#

These three are often confused because they are all proxies. The difference is what traffic they see and what they know.

North-south versus east-west. Traffic entering the system from outside is called north-south. The gateway owns it: unknown clients, public internet, API keys and quotas. Traffic between services inside the system is east-west, and a service mesh owns it: known services, mutual TLS, retries and telemetry on every hop.

How a mesh works. In the classic design, a small proxy (often Envoy) runs as a sidecar next to every service instance. All of the service's inbound and outbound traffic passes through it. A control plane (Istio's istiod, for example) pushes certificates and routing rules to every sidecar. The service code just calls a local address, and the sidecar adds encryption, retries, timeouts and metrics. Newer designs such as Istio's ambient mode move some of this work out of per-pod sidecars into shared per-node proxies, to cut the memory and latency overhead of one proxy per instance.

Why not one tool for everything? You could, in principle, run gateway features in mesh proxies. But a gateway carries API product concerns that a mesh does not: developer portals, API key issuance, usage plans and billing analytics, request validation against public schemas, and protection against hostile internet traffic. A mesh carries concerns a gateway does not: workload identity for every service, and policy on every internal hop. Many teams run both, often built on the same proxy software, with Envoy as the edge gateway and as the mesh sidecar.

A path through all three. A request from a phone resolves DNS to a cloud load balancer, which forwards the TCP connection to a gateway instance. The gateway terminates TLS, authenticates, rate-limits and routes to the order service. The order service calls the payment service through its sidecar over mTLS, and the payment sidecar enforces a policy that only the order service may call it. Each layer adds a small, measurable latency, typically under a millisecond to a few milliseconds per proxy hop.

Scaling the gateway and avoiding a "god gateway"#

Every request passes through the gateway, so it must never be the bottleneck or the single point of failure.

  • Stateless instances: keep config, rate-limit counters and sessions out of instance memory (in Redis or the config store), so instances scale horizontally behind a load balancer. Auto-scale on CPU and request rate.
  • Multiple instances across zones, with health checks, so losing a zone does not stop traffic.
  • Timeouts and circuit breakers per route, so one slow service cannot use up the gateway's connections and threads and take down every route.
  • Isolate routes or tenants: separate gateway clusters for public, partner and internal traffic, so a partner traffic spike does not affect the mobile app.
  • Fail open or closed deliberately: if the rate-limit store is down, most systems allow traffic (fail open) rather than reject everyone; for auth, always fail closed.

A god gateway is one that slowly accumulates business logic: pricing rules, data joins, feature flags, special cases per customer. Then every feature needs a gateway change, one central team becomes a bottleneck, deploys become risky, and a bug in one route can break everything. Rules to avoid it:

  • The gateway handles cross-cutting concerns only; business logic lives in services.
  • Aggregation for a client belongs in that client's BFF, owned by its team.
  • Routes and policies are declarative config, managed in version control, which teams change through self-service.

Scaling the gateway in depth#

There are two separate scaling questions: handling more load in one place, and serving users spread across the world.

Horizontal scaling works because gateways are stateless. A gateway instance holds no data that matters between requests. Its routes come from config, its counters from Redis, and its keys from a cached JWKS. So you add instances behind a load balancer and remove them when traffic drops. A single modern proxy instance (Envoy, NGINX or Kong) can usually handle several thousand to tens of thousands of simple proxied requests per second per few CPU cores. The real number depends heavily on TLS, plugins and payload size, so load-test your own configuration. As a rough sizing example, 100,000 requests per second at a measured 10,000 per instance needs 10 instances. Add headroom for a zone failure, so with three zones you run at least 15, so that losing a third still leaves enough.

Two kinds of load balancing. It helps to separate them clearly:

  • Client-to-gateway: a dedicated load balancer in front of the gateway fleet, such as AWS Elastic Load Balancing, NGINX or HAProxy, spreads client connections over gateway instances.
  • Gateway-to-service: the gateway itself balances each request across the healthy instances of the target service, using service discovery.

In an interview, you rarely need to draw both. A single box labelled "load balancer and API gateway" is usually enough, because the entry point is almost never the interesting part of the problem.

L4 or L7 in front. The load balancer in front of the gateway is often a layer 4 (TCP) balancer, which just forwards connections and handles huge connection counts cheaply. A layer 7 (HTTP) balancer understands requests and can route by path, which overlaps with the gateway's own job. A rule of thumb: persistent connections such as WebSockets tend to favour L4, which keeps one long connection pinned to one backend. Request-by-request HTTP traffic benefits from L7 features. For extreme traffic, specialised hardware or kernel-bypass load balancers outperform software you run yourself, but that is network engineering far beyond a typical design interview. See Load Balancing.

Stateless services behind it scale the same way. The pattern repeats one layer down. In a ticketing system, for example, the event service holds no session state, so it scales by adding instances behind the gateway's balancing, using round robin or least connections. Read-heavy, rarely-changing data such as event names, venues and performer bios is cached in Redis or Memcached with a read-through strategy. Long TTLs suit static venue details, while short TTLs suit fast-changing availability, and database triggers or change events invalidate entries when something does change. The operational cost of many instances is real: deployments must be rolled out gradually, and rollback must be quick and rehearsed. The same is true of the gateway fleet, where a bad config push affects every route at once.

Global distribution. For users spread across continents, deploy gateway clusters in several regions, as you would a CDN:

  • Regional deployments: a gateway cluster in each region, close to users and to that region's services.
  • Geo-aware routing: GeoDNS returns the address of the nearest region, or an anycast address lets the network route each user to the closest point of presence.
  • Configuration synchronisation: routes, policies, certificates and keys must be identical everywhere. Store them in version control and roll them out through a pipeline region by region, so a mistake is caught in one region before it reaches all of them.

Rate limits get harder across regions. A user limited to 1,000 requests per hour could spend 1,000 in each region unless counters are shared. Most systems accept per-region limits, which are slightly loose, rather than pay cross-region latency on every request. Others split the global budget between regions and rebalance it periodically.

Failure handling at the entry point. If a whole region's gateway fleet fails, DNS health checks or anycast withdrawal move users to another region within seconds to minutes, depending on DNS TTLs. Keep DNS TTLs short (30 to 60 seconds) for gateway hostnames, so clients follow failover quickly.

Avoiding the god gateway in depth#

The slide from a thin gateway to a god gateway is gradual, and every step looks reasonable at the time. One team adds a small join "just for the home screen". Another adds a pricing rule because it is the quickest place to ship. A third adds per-customer special cases. A year later, the gateway holds business logic owned by nobody, every product change needs a ticket for the gateway team, and a routine deploy risks breaking every API at once.

Warning signs:

  • The gateway reads from a database other than its own config store.
  • Gateway code contains domain words such as discount, inventory or eligibility.
  • Feature work regularly waits on the gateway team.
  • One route's bug or slowness has taken down unrelated routes.

Structural fixes:

  • Keep the gateway declarative. Routes, auth policies and limits are config, not code. Custom plugins are rare, reviewed and generic.
  • Move aggregation to BFFs owned by client teams, and business rules to domain services.
  • Self-service routing. Teams own their route definitions in their own repositories, and a pipeline validates and merges them. The platform team owns the gateway software, not every route.
  • Isolation. Per-route timeouts, connection pools and circuit breakers stop one slow upstream from consuming every worker. Separate gateway clusters for very different traffic (public, partner, internal admin) contain the blast radius.

The gateway as a migration tool: the strangler fig#

A gateway makes gradual migrations possible. When breaking up a monolith, you put a gateway in front that routes everything to the monolith. Then you build a new service for one capability, say search, and change the route for /search to point at it. The monolith keeps everything else. Repeat route by route until the monolith is empty or small enough to keep. Clients never notice, and each step can be rolled back by flipping a route back. The name comes from Martin Fowler's description of the strangler fig, a plant that grows around a tree and eventually replaces it. Weighted routing makes each step safer: send 1% of /search traffic to the new service, compare error rates and latency, then increase.

Edge security beyond authentication#

Because the gateway is the first code that touches internet traffic, it is also the natural place for defences that have nothing to do with who the user is.

  • Web application firewall (WAF) rules. These block well-known attack patterns, such as SQL injection strings, path traversal (../) and oversized headers, before the request reaches a service. Managed WAFs (AWS WAF, Cloudflare and others) ship rule sets that are updated as new attacks appear. They catch broad, low-effort attacks. They do not replace input validation in services.
  • Bot and abuse protection. Login, sign-up and checkout endpoints attract credential stuffing and scalping bots. The gateway can apply stricter per-IP and per-device limits on these routes, require a challenge (such as a CAPTCHA) after suspicious patterns, and block known bad networks.
  • DDoS in layers. Huge network floods are absorbed upstream by the cloud provider or CDN, which have far more capacity than any one gateway fleet. The gateway handles the application-level floods that get through, such as many valid-looking HTTP requests, with rate limits, connection limits and timeouts for slow clients that trickle bytes to hold connections open.
  • Strict parsing. Limits on header size, header count, URL length and body size stop memory-exhaustion tricks. The gateway and the services behind it must agree on how to parse ambiguous requests, for example conflicting Content-Length and Transfer-Encoding headers. If they disagree, an attacker can hide a second request inside the first, a class of attack called HTTP request smuggling. Normalising or rejecting ambiguous requests at the edge closes it.
  • TLS hygiene. Modern protocol versions only (TLS 1.2 and 1.3), automated certificate renewal, HSTS headers so browsers never fall back to plain HTTP, and mTLS or private networking from the gateway to services.
  • Least exposure. Only routes that are meant to be public are configured. Admin and internal endpoints live on a separate internal gateway, not behind an obscure path on the public one.

The principle is defence in depth: the gateway removes the cheap, noisy attacks so services can focus on the precise checks only they can make, such as whether this user may read this order.

Choosing a gateway product#

Managed services are the easiest option, because there are no servers to run. They are usually the most expensive per request at high volume.

  • AWS API Gateway: tight integration with AWS services, with REST, HTTP and WebSocket APIs. It has built-in request throttling, API keys with usage plans, direct Lambda integration for serverless backends, and CloudWatch metrics and logs. Pricing is per request, which is cheap at low volume and adds up at billions of requests. REST integrations have historically had a timeout of about 29 seconds, which pushes long work towards asynchronous patterns.
  • Azure API Management: strong OAuth 2.0 and OpenID Connect support, policy-based configuration (transformations and limits written as policies) and a built-in developer portal for documentation and key sign-up.
  • Google Cloud: Cloud Endpoints offers deep GCP integration, strong gRPC support and documentation generated from OpenAPI specs. Apigee, also from Google, targets enterprise API programmes with analytics, monetisation and a developer portal.

Open-source and self-hosted options give more control and lower cost at scale, at the price of operating them yourself:

  • Kong: built on NGINX (via OpenResty), with a large plugin ecosystem for auth, limits, transformations and logging. It can run as a traditional gateway and also has service mesh offerings.
  • Tyk: native GraphQL support, built-in API analytics and multi-data-centre deployment.
  • Express Gateway: a lightweight gateway written in JavaScript on Node.js, friendly for teams whose services are already Node.
  • Envoy and Envoy-based gateways (for example Envoy Gateway, Gloo, Emissary): high performance, configuration pushed dynamically over APIs, first-class HTTP/2 and gRPC.
  • NGINX, Apache, Traefik and HAProxy: a plain web server or proxy is often enough as a gateway at small and medium scale. In Amazon's early days, a large fleet of Apache web servers did this job.

How to choose. Use the managed gateway of your cloud if the traffic is moderate, the team is small or the backends are serverless. Self-host Kong or an Envoy-based gateway when volume is high enough that per-request pricing hurts, when you need custom plugins, or when you run on several clouds or on-premises. Choose Apigee or Azure API Management when the API itself is a product with external developers, portals and billing. In an interview, naming one sensible option with a one-line reason is plenty.

When to propose a gateway in an interview#

The short rule: use one with microservices, skip it for a simple client and server. With several services behind one client, a gateway is close to essential. Without it, clients must know every service's address and be updated whenever the layout changes, which couples them tightly to your internals. For a monolith or a single backend with one client type, a gateway adds a hop and a component without solving a problem. A load balancer or reverse proxy already gives you TLS and spreading of load.

In most product-style interviews (a feed, a ride-sharing app, a ticketing system), drawing a gateway as the first box clients hit is a sensible default. Then move on. Interviewers rarely dig into the gateway; they want to spend time on the hard parts of the specific problem. Candidates more often lose time by over-explaining the gateway than by under-explaining it. One sentence is enough: "Clients hit an API gateway that routes to services and handles auth and rate limiting." Expand only if asked, or if the problem itself is about the edge, as in designing a rate limiter, where the gateway is where the limiter runs.

When to Use It#

  • Several backend services exposed to external clients.
  • Public or partner APIs that need API keys, quotas, usage plans and a developer portal.
  • Mobile clients where reducing round trips matters (BFF).
  • Migrating a monolith gradually: the gateway routes some paths to new services and the rest to the monolith (the strangler fig pattern).

When NOT to Use It#

  • A single service or monolith: a reverse proxy or load balancer already gives TLS and routing.
  • Service-to-service calls inside the cluster: use direct calls or a mesh, not a trip back out through the edge gateway.
  • As a place for business logic or heavy data processing.

How to Implement It#

  1. Choose managed or self-hosted (table below), based on traffic volume, cost and how much control you need.
  2. Define routes declaratively: path, upstream service, timeout, retries, auth policy and rate-limit policy per route.
  3. Validate tokens at the gateway and pass a trusted identity header to services; strip any client-sent copy of that header.
  4. Add rate limits per consumer with a shared store, and return standard rate-limit headers.
  5. Set timeouts lower than the client's, add circuit breakers, and propagate request IDs and trace context.
  6. Run at least three instances across zones and load-test the gateway with realistic traffic.
# Illustrative gateway route config (declarative, in version control)
routes:
  - name: orders
    match: { path_prefix: /v1/orders }
    upstream: http://order-service.internal:8080
    timeout_ms: 2000
    retries: { attempts: 2, on: [connect-failure, 503], methods: [GET] }
    plugins:
      jwt: { issuer: https://auth.example.com, required_scopes: [read:orders] }
      rate_limit: { key: user_id, limit_per_second: 100 }
      cors: { origins: [https://app.example.com] }
  - name: legacy
    match: { path_prefix: / }
    upstream: http://monolith.internal:8080   # strangler fig fallback

Note that retries apply only to GET: retrying a POST at the gateway can duplicate an order unless the request carries an idempotency key. See Idempotency.

ToolFits when
Kong (open source or enterprise)Self-hosted, plugin ecosystem, runs on Kubernetes or VMs
AWS API GatewayServerless and AWS-native backends, pay per request, built-in keys and usage plans
Apigee (Google Cloud)Enterprise API programmes: developer portal, monetisation, analytics
Envoy (and Envoy-based gateways)High-performance, dynamic config, gRPC; also the data plane of many meshes
Nginx, TraefikSimple routing and TLS at small to medium scale

Trade-offs#

ChoiceGainCostPick when
Single gatewayOne place for auth, limits and logsExtra hop (1-5 ms); critical componentSeveral services, external clients
Gateway + BFFsScreen-shaped responses, client teams move fastMore services to run; risk of duplicated logicSeveral very different clients
Managed gatewayNo servers to operate, built-in featuresPer-request cost at high volume, vendor limitsLow to medium traffic, small teams
Self-hosted gatewayControl, lower cost at scaleYou operate and scale itHigh volume, custom needs
Aggregation in gatewayFewer client round tripsGateway grows logic and couplingOnly simple fan-out; else use a BFF
JWT validated locallyMicroseconds, no auth-server dependencyRevocation waits for expiry unless a deny list is checkedMost user-facing APIs
Rate-limit counters in RedisAccurate shared limits across instancesExtra hop, a dependency that can failMany gateway instances
Per-region rate limitsNo cross-region latencyUsers can exceed a global limitGlobal products with loose limits

Common Pitfalls#

  • Business logic in the gateway, creating a god gateway owned by one overloaded team.
  • No per-route timeouts, so one slow service exhausts the gateway's connections and threads.
  • Trusting a client-supplied X-User-Id header because the gateway forgot to strip it.
  • Gateway retries on non-idempotent requests, duplicating writes.
  • Routing internal service-to-service traffic through the public gateway, adding latency and load.
  • Trusting every entry in X-Forwarded-For, so attackers spoof IPs and dodge per-IP limits.
  • Retrying at every layer, turning one overloaded service into a retry storm.
  • Spending five interview minutes on gateway middleware and never saying that it routes requests.

Real-World Examples#

Netflix built and open-sourced Zuul as the edge gateway in front of its microservices, handling routing, filtering and resilience for requests from many device types.

The BFF pattern was popularised by Sam Newman, who described its use at SoundCloud, where separate backends served different client experiences.

  • Lyft created Envoy and open-sourced it in 2016; it now underpins many gateways and service meshes, including Istio.
  • Amazon in its early days ran a large fleet of Apache web servers as the front door that played the gateway role.

In the Interview#

How deep to go in an interview#

For most problems, the gateway is one box and one sentence. It becomes the centre of the discussion only in a few cases:

  • Designing a rate limiter or an API platform, where the limiter runs at the gateway. Discuss client keys (user, IP, API key), layered rules, Redis counters and failure modes.
  • Very large client fan-out, such as a home screen built from many services. Discuss a BFF, parallel calls, deadlines and partial responses.
  • Public developer APIs, where API keys, quotas, usage plans and versioning at the edge are part of the product.
  • Global products, where regional gateways, GeoDNS and config rollout come up.

Follow-up questions to expect#

  • "The gateway adds latency, is it worth it?" A well-tuned gateway adds about 1 to 5 ms. It saves more than that through connection reuse, caching and early rejection of bad traffic.
  • "One service is slow and the whole API is timing out." Per-route timeouts, concurrency caps and circuit breakers, so the slow route fails alone.
  • "How do premium users get higher limits?" Put the plan in the JWT claims, or cache a key-to-plan map at the gateway, and choose the limit per plan.
  • "How do you migrate off a monolith?" Strangler fig: route paths one at a time from the monolith to new services, with weighted rollout.
  • "How do services know the request is authenticated?" The gateway verifies the token and forwards a trusted identity, strips client copies of those headers, and services accept traffic only from the gateway, enforced with network policy or mTLS.
Deep Dive: Gateway latency budgets, multi-tenancy and the edgeShow

Latency budget. Each gateway feature (JWT check, rate-limit lookup, transformation, logging) costs time. A Redis round trip for rate limiting is ~0.5-1 ms; local JWT validation is microseconds; synchronous calls to an external auth service can add 5-20 ms. Measure per plugin, cache aggressively and push non-critical work (analytics, logging) off the request path.

Aggregation and partial failure. If a BFF calls five services and one times out, return the other four sections with the slow one marked unavailable, rather than failing the whole screen. Call the services in parallel, give each its own timeout and decide in advance which sections are essential.

Multi-tenant gateways. Platforms serving many customers must stop one tenant from starving others: separate rate limits and connection pools per tenant, and sometimes separate gateway clusters ("cells") for the largest customers.

Control plane vs data plane. Modern gateways split the proxy that handles traffic (data plane, such as Envoy) from the system that stores and pushes configuration (control plane). Config changes propagate in seconds without restarts, and the data plane keeps running with its last config if the control plane is down.

Moving to the edge. Some gateway work, such as token validation, geo-blocking and simple routing, can run in CDN edge compute close to users, rejecting bad requests before they cross an ocean. The origin gateway still enforces the same policies as a second line of defence.

Inside a modern proxy: how Envoy-style gateways are builtShow

Many gateways and meshes today run on Envoy, a proxy created at Lyft and open-sourced in 2016, and now a graduated CNCF project. Its design explains why modern gateways are fast and reconfigurable.

Listeners, filter chains and clusters. A listener binds a port and accepts connections. Each connection passes through a chain of network filters. For HTTP, the key one is the HTTP connection manager, which parses requests and runs a second chain of HTTP filters: authentication, rate limiting, header rewriting, compression, the router and so on. The router filter picks a route, and the route names a cluster, which is a group of upstream endpoints with its own load-balancing policy, health checks, timeouts and connection pools. Every gateway feature on this page is a filter in that chain or a setting on a cluster.

Threading model. Envoy runs one main thread for management and a small number of worker threads, usually one per CPU core. Each accepted connection belongs to one worker for its whole life, and that worker handles all its I/O with non-blocking event loops. There is little locking on the hot path, which is why one instance can handle many thousands of concurrent connections. The same event-driven approach is behind NGINX's performance. Netflix moved its Zuul gateway from a blocking, thread-per-request model to an asynchronous one built on Netty for the same reason: a thread per open connection does not scale to the number of long-lived connections that devices hold.

Dynamic configuration (xDS). Instead of reading a static file, Envoy can fetch its configuration over gRPC from a control plane through a family of discovery APIs, collectively called xDS. Listeners come from LDS, routes from RDS, clusters from CDS, endpoints from EDS and secrets such as certificates from SDS. When a new service instance starts, the control plane pushes an endpoint update and every proxy learns about it within seconds, with no restart and no dropped connections. If the control plane goes down, proxies keep serving with their last known configuration. That split, a data plane that keeps running and a control plane that only changes it, is now standard.

Hot restart and draining. When the binary itself must be upgraded, a new process starts, takes over the listening sockets, and the old process stops accepting new connections but finishes existing ones during a drain period. Clients see no errors. Gateways without this ability must instead be drained at the load balancer one instance at a time.

Outlier detection. Besides active health checks, the proxy watches real responses. An upstream instance that returns, say, five consecutive 5xx errors is ejected from the pool for a while, and the ejection time grows if it keeps failing. A cap on the percentage of instances that can be ejected stops a cluster-wide problem from emptying the pool entirely.

Observability for free. Because every request passes through the proxy, it can emit uniform metrics per route and per cluster (request rate, latency histograms, response codes, retries, ejections), access logs, and distributed trace spans. It also propagates trace headers so the trace continues through services. This uniformity is one of the main practical reasons teams adopt a gateway even when they have only a few services.

Resilience at the gateway: timeouts, retries, circuit breakers and load sheddingShow

The gateway sits in front of everything, so its resilience settings decide whether one failing service stays a local problem or becomes an outage.

Timeouts form a budget. Each layer's timeout should be shorter than the layer above it. If the mobile app waits 10 seconds, the gateway might allow 8, and the service's own database calls 2 to 3. If the gateway waited longer than the client, it would keep doing work for a client that already gave up. Per-route timeouts matter: a search route might get 2 seconds and a report export 30, rather than one global value that is too long for most routes and too short for a few.

Retries must be bounded. Retrying a failed request on another instance hides many transient errors. Unbounded retries are dangerous, though. If a service is overloaded and every layer retries three times, a request through three layers can turn into 3 × 3 × 3 = 27 attempts, which amplifies the overload that caused the failure. Good practice:

  • retry only idempotent requests (GET, PUT, DELETE, or POST with an idempotency key);
  • use few attempts, with exponential backoff and jitter;
  • set a retry budget, for example retries may add at most 10% to the traffic of a cluster, after which the gateway stops retrying;
  • retry at one layer only, usually the one closest to the client that can do it safely.

Circuit breakers. A circuit breaker tracks failures to an upstream. When failures cross a threshold, it "opens" and fails requests immediately for a cooling-off period, instead of sending traffic that will time out and tie up connections. After the pause, it lets a few test requests through ("half-open") and closes again if they succeed. Proxies also cap concurrency per upstream: a maximum number of connections, pending requests and active requests. When a slow service hits those caps, extra requests are rejected fast instead of piling up. That keeps the gateway's own resources free for healthy routes.

Load shedding and priority. When total traffic exceeds what the system can handle, it is better to reject some requests quickly than to serve all of them slowly. The gateway can shed load by priority: keep checkout and login, drop recommendations and analytics beacons first. Returning 503 with Retry-After tells well-behaved clients to back off. Some systems use adaptive concurrency limits, which estimate a service's healthy concurrency from observed latency and reject requests beyond it, the way TCP congestion control adjusts its window.

A worked example. A product page aggregates catalogue (p99 40 ms), reviews (p99 120 ms) and recommendations (p99 300 ms, sometimes much worse). The client timeout is 2 seconds. The BFF calls all three in parallel with timeouts of 300 ms, 400 ms and 500 ms. Catalogue is essential; the other two are optional. One evening, recommendations degrade to 5-second responses. Its circuit breaker opens after a burst of timeouts, the page renders without the recommendations panel in about 150 ms, and the gateway's connection pools stay healthy. Without the per-call timeouts and breaker, every page would have waited for the 2-second client timeout and failed, and the pile-up of open connections could have exhausted the gateway's workers for unrelated routes too.

Fail open or fail closed. Decide per dependency. If the rate-limit store fails, failing open (allowing traffic) is usually right, because limits are protection, not correctness. If the auth key cache is empty and the identity provider is unreachable, fail closed (reject), because letting unauthenticated traffic through is a security incident. Write these decisions down before the outage, not during it. See Rate Limiting for limiter failure modes.

Key Takeaways#

  • An API gateway is the single entry point that handles routing, auth, rate limits, TLS, transformation, aggregation, caching and observability.
  • A BFF is a per-client API layer that shapes responses for one client type and is owned by that client's team.
  • Load balancers spread traffic, gateways manage external API traffic, and service meshes manage service-to-service traffic.
  • Scale gateways as stateless, multi-zone clusters with per-route timeouts and circuit breakers.
  • Keep business logic out of the gateway to avoid a god gateway that becomes a bottleneck and a single point of failure.
  • Routing is the core job; middleware is what the gateway does while routing, so name only what the problem needs.
  • Identify rate-limit clients by user, IP or API key, layer the rules, and decide in advance whether each dependency fails open or closed.
  • Bound retries, set per-route timeouts below the client's, and use circuit breakers so one slow service cannot take down the edge.