System designArchitectureIntermediate

API Gateway in System Design

The single, controlled front door to your microservices: what it should handle, what it must never handle, and how to keep it from becoming your biggest point of failure.

The short answerAn API gateway is the single entry point between clients and backend services. It routes each request to the right service and handles cross-cutting concerns in one place: authentication, coarse authorization, rate limiting, validation, request transformation, aggregation, timeouts and observability. Business logic stays in the services, and the gateway runs as several stateless instances so it is never a single point of failure.

HLD book
01Fundamentals

What is an API gateway?

A controlled entry point through which every client talks to your backend services.

One front door, many services
Web · mobile · partnersClients
API gatewayRoute · authenticate · limit · observe
Userservice
Orderservice
Paymentservice
Bookingservice

What it takes off every service's plate

One entry point

Clients call one public API instead of discovering many services.

Central authentication

Credentials are checked before requests reach internal services.

Coarse authorization

Requests that fail route or scope rules never get through.

Rate limiting

Per-user and per-plan quotas protect backends.

Routing

Public endpoints map to internal services and versions.

Observability

Consistent logs, metrics and trace IDs for every request.

Transformation

Headers, paths and payloads adapted between contracts.

Composition

Several backend calls merged into one response.

02Request flow

Where the gateway sits

A real request crosses several layers before it reaches a service. Each layer has a different job.

Client
DNS / CDN / WAFEdge protection, cached content
Load balancerSpreads traffic over gateway instances
API gateway clusterPolicies + routing
Service A
Service B
Service C

Gateway vs load balancer vs reverse proxy

ComponentPrimary jobTypical features
Load balancerDistribute traffic across instancesHealth checks, balancing algorithms, failover
Reverse proxyStand in for backend serversTLS, routing, caching, compression
API gatewayAPI policy and routing boundaryAuth, quotas, transformation, aggregation, observability
03Core responsibility

Routing and versioning

The gateway maps each incoming request to the right backend service, and can shift traffic between versions safely.

Path-based routinghttp
GET  /api/users/42      →  user-service
GET  /api/orders/501    →  order-service
POST /api/payments      →  payment-service

Path-based

/users/* → user-service.

Host-based

payments.api.example.com → payment-service.

Header-based

X-Client-Version: 2 → the new service.

Weighted (canary)

10% → v2, 90% → v1 during a rollout.

Geo routing

Send traffic to the nearest regional deployment.

Tenant routing

Enterprise tenants go to dedicated infrastructure.

Versioning and canary releases

Versioned routes

  • /api/v1/orders → order-service v1
  • /api/v2/orders → order-service v2
  • Old clients keep working while new ones migrate

Canary rollout

  1. Send 10% of traffic to v2
  2. Watch error rate, latency and business metrics
  3. Raise to 25%, 50%, 100%, or roll back instantly
04Security

Authentication at the gateway

Authentication answers one question: who is making this request?

ClientAuthorization: Bearer <JWT>
API gatewayVerify the credential
BackendReceives a trusted identity

Invalid or expired credentials get a 401 at the gateway and never reach a service.

JWT

Verify signature, expiry, issuer, audience and required claims.

API key

Identify the calling application or developer.

OAuth access token

Validate externally issued tokens and their scopes.

mTLS

Authenticate clients or services by certificate.

JWT claims the gateway checksjson
{
  "sub":   "user_42",
  "role":  "USER",
  "scope": ["booking:read", "booking:create"],
  "iss":   "auth.targettrek.in",
  "aud":   "api.targettrek.in",
  "exp":   1790678000
}
Verifying a JWT (Node.js, jose)js
import { createRemoteJWKSet, jwtVerify } from "jose";

// public keys are fetched once and cached; rotation is handled automatically
const JWKS = createRemoteJWKSet(new URL("https://auth.targettrek.in/.well-known/jwks.json"));

export async function authenticate(req) {
  const token = req.headers.authorization?.replace(/^Bearer /, "");
  if (!token) throw httpError(401, "Missing token");

  const { payload } = await jwtVerify(token, JWKS, {
    issuer: "auth.targettrek.in",
    audience: "api.targettrek.in",
  });                                   // throws on bad signature or expired token

  req.headers["x-user-id"] = payload.sub;   // trusted identity for the backend
  req.headers["x-scopes"] = payload.scope.join(" ");
}
05Access control

Authorization

Authorization decides what an authenticated caller may do. The gateway handles the broad rules; services handle the specific ones.

Role-based

ADMIN, USER, SUPPORT and similar roles.

Scope-based

booking:create, payment:read and other OAuth-style scopes.

Route policies

Only administrators may call /admin/*.

Tenant policies

One organisation can never reach another's APIs.

06Traffic protection

Rate limiting at the gateway

The gateway already knows who's calling, which makes it the natural place for quotas, applied before any expensive backend work starts.

Who / whatLimit
Free plan100 requests / minute
Pro plan5,000 requests / minute
Payment route20 requests / minute / user
OTP route1 request / 30 seconds / phone number
ClientToo many requests
Gateway limiterToken bucket / sliding window
BackendProtected

Rejected requests get HTTP 429 Too Many Requests with a Retry-After header.

07Input protection

Validation and transformation

Reject obviously bad requests before they cost anything, and translate between the public contract and internal ones.

Payload size

Reject unexpectedly huge bodies before forwarding.

Required headers

Content-Type, API version, auth metadata.

Schema checks

Validate the basic request shape (e.g. against OpenAPI).

Method rules

Reject unsupported HTTP methods.

Content type

Accept only supported encodings.

Sanitisation

Normalise or reject malformed traffic.

Public contract → internal contract

What the client sends

  • POST /api/orders
  • { "productId": "p1", "quantity": 2 }

What the service receives

  • POST /internal/order-service/v2/orders
  • X-User-ID: user_42 · X-Request-ID: req_991
  • { "sku": "p1", "units": 2 }

Header injection

Add request ID, caller identity and trace context.

Path rewrite

Map public route names to internal ones.

Response filtering

Strip internal fields before they reach clients.

Protocol bridging

REST outside, gRPC inside, where needed.

08API composition

Aggregation and Backend for Frontend

One screen often needs data from several services. The gateway can fetch them together, or you can give each client its own tailored API.

One request, three services
Mobile appGET /home
API gatewayFan out in parallel
Profile
Orders
Recommendations
One combined response

Backend for Frontend (BFF)

Web
Mobile
Partner
Web BFF
Mobile BFF
Partner API
Shared microservices

Mobile wants compact responses and few round trips; web wants richer payloads; partners need a stable, versioned contract. A BFF per client type lets each evolve independently, usually owned by the team that builds that client.

09Performance

Gateway caching

Some read-only responses can be answered by the gateway itself, so they never reach a service.

GET /movies/popular
Gateway cacheTTL 30 seconds
Movie service

Good candidates

  • Public data
  • Read-heavy
  • Changes slowly: catalogues, city lists, popular items

Bad candidates

  • Personalised responses (/users/me)
  • Authorisation-sensitive data
  • Fast-changing data without careful cache keys
10Resilience

Timeouts, retries and circuit breakers

The gateway calls everything, so it's where one slow service can drag down the whole system, or where you stop that from happening.

Timeouts: never wait forever

RouteTimeoutOn timeout
Recommendations300 msReturn the page without them
Movie search500 msRetry once (idempotent GET)
Booking2 sReturn an error; the client retries with its idempotency key
Payment provider5 sMark the result unknown, then reconcile

Retries: only when safe

Safer retry

  • Idempotent GETs after a network blip
  • Writes carrying an idempotency key
  • At most 2–3 attempts, backoff + jitter (100 ms, 200 ms…)

Dangerous retry

  • POST /payments without an idempotency key
  • Retrying at every layer (retries multiply)
  • Retrying instantly, in lockstep with every other client

Circuit breakers: fail fast

CLOSEDCalls pass; failures counted
OPENReject immediately / fallback
HALF-OPENLet a few test calls through

Test calls succeed → CLOSED. They fail → back to OPEN.

A minimal circuit breakerjs
class CircuitBreaker {
  constructor({ threshold = 5, cooldownMs = 10_000 } = {}) {
    Object.assign(this, { threshold, cooldownMs, failures: 0, state: "CLOSED", openedAt: 0 });
  }
  async call(fn, fallback) {
    if (this.state === "OPEN") {
      if (Date.now() - this.openedAt < this.cooldownMs) return fallback();  // fail fast
      this.state = "HALF_OPEN";                                             // try again
    }
    try {
      const result = await fn();
      this.failures = 0; this.state = "CLOSED";
      return result;
    } catch (err) {
      if (++this.failures >= this.threshold || this.state === "HALF_OPEN") {
        this.state = "OPEN"; this.openedAt = Date.now();
      }
      return fallback(err);
    }
  }
}
11Dynamic infrastructure

Gateway + service discovery

Instances appear, disappear and move as services deploy and autoscale. The gateway can't depend on hard-coded IPs.

API gatewayNeeds the booking service
Service discoveryRegistry, DNS or platform
Booking 1healthy
Booking 2healthy
Booking 3starting

Consul, Eureka, DNS or Kubernetes Services return only healthy instances; new ones join as they pass readiness.

12Operations and security

Observability and security

Almost every external request passes through the gateway, so it's the best place for consistent telemetry, and the first thing attackers hit.

What to record for every requesttext
X-Request-ID: req_18271
Trace-ID:     4bf92f3577b34da6a3ce929d0e0e4736
User:         user_42
Route:        POST /api/bookings
Backend:      booking-service (10.0.3.17)
Latency:      128 ms
Status:       201

Access logs

Method, route, status, latency and request IDs.

Distributed tracing

Generate or propagate trace context (W3C traceparent) downstream.

Metrics

Request rate, latency percentiles, errors and throttling.

Audit logs

Security-sensitive actions, where compliance requires.

Hardening checklist

TLS everywhere

Encrypt all public traffic.

Reject bad credentials early

Before any backend work.

Route and scope policies

Least privilege by default.

Payload limits

Huge bodies can't exhaust memory.

WAF integration

Filter known attack patterns.

CORS and private backends

Only allowed origins; services unreachable directly.

13Reliability

High availability, zones and regions

Every request passes through the gateway, so it must scale out and survive instance, zone and even region failures.

Users
Load balancerSpreads gateway traffic
Gateway 1zone A
Gateway 2zone B
Gateway Nzone C
Backend services

Stateless instances

Easy to add, replace and autoscale.

Many instances, many zones

Never one gateway process.

Health checks

Unhealthy instances leave rotation automatically.

Autoscaling

On request rate, CPU or latency.

External shared state

Rate-limit counters and config in replicated stores.

Graceful drain + staged config

No dropped requests; bad config rolls back fast.

Multi-region

Global users
Global traffic managerLatency + health routing
India gateway
US gateway
EU gateway
14Case study

Protecting a ticket flash sale

How a BookMyShow-style platform could use its gateway when a blockbuster's tickets go live.

Web / mobileTicket buyers
CDN / WAFEdge protection
Load balancer
API gatewayAuth · rate limit · route · trace
Searchmovies
Bookingseats
Paymenttransactions
Userprofiles
Public routeshttp
GET  /api/movies/*     →  search-service
GET  /api/shows/*      →  show-service
POST /api/bookings     →  booking-service
POST /api/payments     →  payment-service
GET  /api/users/me     →  user-service

A booking request during the sale

  1. Edge

    The request passes CDN and WAF checks.

  2. Authenticate

    The gateway verifies the JWT; anonymous users can browse but not book.

  3. Rate limit

    Per-IP, per-user and per-route booking quotas are checked.

  4. Validate

    Payload shape and size are verified.

  5. Tag

    A request ID and trace context are attached.

  6. Route

    Sent to a healthy booking instance, with a tight timeout and a circuit breaker.

  7. Book

    The booking service handles seat locks and the durable booking.

  8. Pay

    The payment service charges using an idempotency key.

  9. Respond

    The gateway returns the final response and records the metrics.

15Production engineering

Failure scenarios and metrics

The gateway sits on the critical path, so every failure mode needs a planned answer.

FailureResponse
A gateway instance crashesThe load balancer's health checks stop routing to it.
A backend failsTimeouts, circuit breakers and fallbacks.
A backend becomes slowBounded timeouts so gateway resources aren't held indefinitely.
Auth provider is downCached JWKS keys keep JWT validation working; plan what's safe without it.
Redis rate limiter is downFail open or closed per route; fall back to local limits.
Gateway CPU saturatesAutoscale, simplify policies, move heavy work out.
Retry stormBounded retries with exponential backoff and jitter; retry budgets.
Bad config deployedValidate, roll out in stages, roll back fast.
Region failureGlobal routing shifts traffic to a healthy region.
Certificate expiresAutomate renewal and alert well before expiry.

Metrics to watch

  • Requests / sec
  • p50 / p95 / p99 latency
  • 2xx / 4xx / 5xx rate
  • 429 rate
  • Auth failures
  • Timeout rate
  • Retry rate
  • Circuit opens
  • Gateway CPU & memory
  • Active connections
  • Backend latency & errors
  • Traffic per route
  • Cache hit ratio
  • TLS errors
Interview prep

API gateway interview questions, with answers

Say your answer out loud first, then open the card to compare. These are the questions interviewers actually ask.

1

What is an API gateway, and why do microservices use one?

It is one public entry point in front of many services. Without it, every client must know each service's address, auth scheme and contract, and every service must re-implement auth, rate limiting and logging. The gateway centralises those cross-cutting concerns and hides the internal topology.

2

API gateway vs load balancer?

A load balancer spreads traffic across instances of the same service, based on health and an algorithm. A gateway is an API policy boundary: it decides which service a request is for and applies auth, quotas, transformations and aggregation. In practice the gateway sits behind a load balancer, and gateway instances are themselves load balanced.

3

API gateway vs reverse proxy?

Every API gateway is a reverse proxy, but not every reverse proxy is a gateway. A reverse proxy forwards traffic and may add TLS, caching or compression. A gateway adds API-specific policy: identity, scopes, per-consumer quotas, versioning and composition.

4

Where does the gateway sit in the request path?

Typically: client → DNS/CDN/WAF at the edge → load balancer → gateway cluster → services. The CDN and WAF remove cacheable and malicious traffic first; the load balancer spreads requests over gateway instances; the gateway routes to services.

5

How would JWT validation work at the gateway?

The gateway verifies the token's signature with the issuer's public key (fetched from a JWKS endpoint and cached), then checks exp, nbf, iss, aud and required scopes. On success it forwards trusted identity headers such as X-User-ID; on failure it returns 401 without touching any backend.

6

Authentication vs authorization?

Authentication answers who is calling (a valid token for user 42). Authorization answers what they may do (can user 42 cancel booking 9001?). The gateway can do authentication and coarse authorization by role or scope; fine-grained, resource-level checks belong in the service that owns the data.

7

Should backend services trust the gateway completely?

No. Services should accept traffic only from the gateway (private network, mTLS) and still enforce their own resource-level authorization. If anything bypasses the gateway, or it is misconfigured, the services must not become wide open.

8

Where should rate limiting happen?

At the edge for coarse protection (per IP, at the CDN or WAF), at the gateway for per-user, per-API-key and per-plan quotas, and in critical services for their own protection. The gateway is the natural place for quota tiers because it already knows the caller's identity.

9

How would free and premium users get different quotas?

The gateway reads the plan from the token or API key and looks up that plan's limit, for example 100 vs 5,000 requests per minute. It enforces it with a token bucket or sliding window in a shared store such as Redis, and returns 429 with Retry-After and X-RateLimit headers when the limit is hit.

10

Should business logic live in the gateway?

No. Domain logic in the gateway couples every team to one central component, makes deploys risky and turns the gateway into a monolith. Keep it to cross-cutting concerns and light composition; put business rules in services.

11

What is API aggregation, and what is the risk?

The gateway calls several services in parallel and merges the results into one response, for example a mobile home screen built from profile, orders and recommendations. The risk is latency coupling: the response is as slow as the slowest call. Mitigate with parallel calls, per-call timeouts and partial responses.

12

What is the Backend for Frontend (BFF) pattern?

A separate gateway or API layer per client type, such as one for web, one for mobile and one for partners. Each BFF shapes responses for its client, so a mobile app gets compact payloads and fewer round trips without forcing the web API to change.

13

When should gateway responses be cached?

For public, read-heavy, fairly stable GET responses such as popular movies or a product catalogue, with a short TTL. Never cache personalised or authorisation-sensitive responses unless the cache key includes the caller's identity and permissions.

14

How should gateway timeouts be configured?

Per route, from the downstream service's real latency profile and the business need: perhaps 300 ms for recommendations and 5 s for a payment provider. The gateway timeout must also fit inside the client's overall deadline, and every downstream call should have one.

15

When is retrying safe, and how can retries duplicate payments?

Retries are safe for idempotent requests (GET, PUT with the same body, or anything carrying an idempotency key) after transient errors. If the gateway retries a POST /payments that actually succeeded but timed out, the customer is charged twice. So: bounded retries, backoff with jitter, and idempotency keys on writes.

16

What is a circuit breaker? Explain its three states.

It stops calling a dependency that is clearly failing. CLOSED: calls pass and failures are counted. OPEN: after a threshold, calls fail immediately (or use a fallback) for a cooldown period. HALF-OPEN: a few trial calls go through; success closes the circuit, failure opens it again. It fails fast and gives the dependency room to recover.

17

How does the gateway find backend instances?

Through service discovery rather than hard-coded IPs: a registry (Consul, Eureka), DNS, or the platform (Kubernetes Services, a mesh). Instances register, health checks remove dead ones, and the gateway routes only to healthy instances as they scale up and down.

18

How would you do versioning and canary releases at the gateway?

Route /api/v1 and /api/v2 (or a version header) to different service versions. For a canary, use weighted routing: send 5–10% of traffic to the new version, watch its error rate, latency and business metrics, then increase gradually or roll back instantly.

19

What should never be logged at the gateway?

Authorization headers and tokens, passwords, card numbers, OTPs and sensitive personal data. Log the request ID, route, status, latency, caller ID and backend instead, and redact or hash anything sensitive.

20

How do you stop the gateway from being a single point of failure?

Run many stateless gateway instances across availability zones behind a load balancer, with health checks, autoscaling and graceful draining. Keep shared state (rate-limit counters, config) in replicated external stores, and roll out config changes in stages with fast rollback.

21

What should happen when the Redis rate limiter is down?

Decide per route ahead of time. Low-risk reads can fail open, perhaps falling back to a local in-memory limit per instance. High-risk routes such as login, OTP and payments should fail closed or use a strict local limit, because unlimited access there is dangerous.

22

How would you protect a ticket flash sale at the gateway?

Authenticate early, apply per-IP and per-user limits on booking routes, validate payloads, attach trace IDs, route only to healthy booking instances with tight timeouts and circuit breakers, and put a waiting room or queue in front of the booking path if demand exceeds safe capacity. Seat correctness itself stays in the booking service.

Check yourself

Quick quiz

6 questions. Pick an answer to see why it's right or wrong.

Question 1 of 60 / 6

A request arrives with a valid JWT for user 42, asking to cancel booking 9001 owned by user 77. Who should reject it?

Reference

API gateway glossary

The terms from this guide, in one line each.

API gateway
The single, policy-enforcing entry point in front of backend services.
Cross-cutting concern
Something every service needs, such as auth, logging or rate limiting, handled once.
JWT
A signed token carrying claims such as user ID, scopes and expiry.
JWKS
A published set of public keys the gateway uses to verify token signatures.
Scope
A permission attached to a token, such as booking:create.
BFF
Backend for Frontend: one API layer per client type.
Aggregation
Combining several service calls into one client response.
Circuit breaker
Stops calling a failing dependency and fails fast until it recovers.
Canary release
Sending a small share of traffic to a new version first.
Idempotency key
A client-supplied ID that makes retried writes safe.
Summary

Key takeaways

  1. The gateway is the one controlled front door: routing plus cross-cutting policy, so services don't each re-implement them.
  2. Authenticate at the gateway; keep resource-level authorization in the service that owns the data.
  3. Quotas belong at the gateway because it knows the caller. Return 429 with Retry-After.
  4. Aggregation and BFFs simplify clients but couple latency: call in parallel with per-call timeouts.
  5. Every downstream call needs a timeout. Retry only idempotent requests, and use circuit breakers to fail fast.
  6. No business logic in the gateway, and never log tokens or personal data.
  7. Run it stateless, multi-instance and multi-zone, with staged config rollouts. Otherwise it becomes the single point of failure.
Questions

API gateway: frequently asked questions

What is an API gateway in system design?

An API gateway is the single entry point in front of backend services. It routes requests and handles cross-cutting concerns such as authentication, authorization, rate limiting, observability, request transformation and response aggregation.

What is the difference between an API gateway and a load balancer?

A load balancer distributes traffic across instances of a service. An API gateway decides which service a request belongs to and applies API policies such as auth, quotas, transformation and aggregation. Most architectures use both, with a load balancer in front of the gateway instances.

Can an API gateway become a single point of failure?

Yes, if it runs as one instance. Production gateways run as multiple stateless instances across availability zones behind a load balancer, with health checks, autoscaling and staged configuration changes.

Should business logic be placed inside an API gateway?

No. The gateway should handle cross-cutting concerns and light composition. Domain logic belongs in backend services; putting it in the gateway couples every team to one component.

Which API gateways are commonly used?

Popular options include Kong, NGINX, Envoy-based gateways, Apigee, Spring Cloud Gateway, and managed cloud gateways such as AWS API Gateway and Azure API Management. The design concepts are the same across them.

Is a service mesh the same as an API gateway?

No. A gateway manages north-south traffic, from outside clients into the system. A service mesh manages east-west traffic between services inside it, with mTLS, retries and telemetry. Large systems often use both.

Next topicRate Limiting

Token bucket, leaky bucket, sliding windows and Redis-based distributed limits: the gateway's most important policy, in depth.

Go deeperSee the gateway inside complete architectures

Combine gateways, caching, load balancing, databases, queues, rate limiting, locking and failure handling in full HLD interview designs.

  • API gateway
  • Caching
  • Load balancing
  • Rate limiting
  • BookMyShow
  • Scalability
Explore the book

Last reviewed 18 November 2026