What is an API gateway?
A controlled entry point through which every client talks to your backend services.
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.
Where the gateway sits
A real request crosses several layers before it reaches a service. Each layer has a different job.
Gateway vs load balancer vs reverse proxy
| Component | Primary job | Typical features |
|---|---|---|
| Load balancer | Distribute traffic across instances | Health checks, balancing algorithms, failover |
| Reverse proxy | Stand in for backend servers | TLS, routing, caching, compression |
| API gateway | API policy and routing boundary | Auth, quotas, transformation, aggregation, observability |
Routing and versioning
The gateway maps each incoming request to the right backend service, and can shift traffic between versions safely.
GET /api/users/42 → user-service
GET /api/orders/501 → order-service
POST /api/payments → payment-servicePath-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
- Send 10% of traffic to v2
- Watch error rate, latency and business metrics
- Raise to 25%, 50%, 100%, or roll back instantly
Authentication at the gateway
Authentication answers one question: who is making this request?
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.
{
"sub": "user_42",
"role": "USER",
"scope": ["booking:read", "booking:create"],
"iss": "auth.targettrek.in",
"aud": "api.targettrek.in",
"exp": 1790678000
}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(" ");
}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 / what | Limit |
|---|---|
| Free plan | 100 requests / minute |
| Pro plan | 5,000 requests / minute |
| Payment route | 20 requests / minute / user |
| OTP route | 1 request / 30 seconds / phone number |
Rejected requests get HTTP 429 Too Many Requests with a Retry-After header.
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.
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.
Backend for Frontend (BFF)
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.
Gateway caching
Some read-only responses can be answered by the gateway itself, so they never reach a 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
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
| Route | Timeout | On timeout |
|---|---|---|
| Recommendations | 300 ms | Return the page without them |
| Movie search | 500 ms | Retry once (idempotent GET) |
| Booking | 2 s | Return an error; the client retries with its idempotency key |
| Payment provider | 5 s | Mark 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
Test calls succeed → CLOSED. They fail → back to OPEN.
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);
}
}
}Gateway + service discovery
Instances appear, disappear and move as services deploy and autoscale. The gateway can't depend on hard-coded IPs.
Consul, Eureka, DNS or Kubernetes Services return only healthy instances; new ones join as they pass readiness.
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.
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: 201Access 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.
High availability, zones and regions
Every request passes through the gateway, so it must scale out and survive instance, zone and even region failures.
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
Protecting a ticket flash sale
How a BookMyShow-style platform could use its gateway when a blockbuster's tickets go live.
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-serviceA booking request during the sale
Edge
The request passes CDN and WAF checks.
Authenticate
The gateway verifies the JWT; anonymous users can browse but not book.
Rate limit
Per-IP, per-user and per-route booking quotas are checked.
Validate
Payload shape and size are verified.
Tag
A request ID and trace context are attached.
Route
Sent to a healthy booking instance, with a tight timeout and a circuit breaker.
Book
The booking service handles seat locks and the durable booking.
Pay
The payment service charges using an idempotency key.
Respond
The gateway returns the final response and records the metrics.
Failure scenarios and metrics
The gateway sits on the critical path, so every failure mode needs a planned answer.
| Failure | Response |
|---|---|
| A gateway instance crashes | The load balancer's health checks stop routing to it. |
| A backend fails | Timeouts, circuit breakers and fallbacks. |
| A backend becomes slow | Bounded timeouts so gateway resources aren't held indefinitely. |
| Auth provider is down | Cached JWKS keys keep JWT validation working; plan what's safe without it. |
| Redis rate limiter is down | Fail open or closed per route; fall back to local limits. |
| Gateway CPU saturates | Autoscale, simplify policies, move heavy work out. |
| Retry storm | Bounded retries with exponential backoff and jitter; retry budgets. |
| Bad config deployed | Validate, roll out in stages, roll back fast. |
| Region failure | Global routing shifts traffic to a healthy region. |
| Certificate expires | Automate 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
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.
1What 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.
2API 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.
3API 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.
4Where 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.
5How 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.
6Authentication 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.
7Should 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.
8Where 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.
9How 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.
10Should 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.
11What 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.
12What 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.
13When 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.
14How 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.
15When 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.
16What 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.
17How 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.
18How 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.
19What 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.
20How 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.
21What 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.
22How 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.
Quick quiz
6 questions. Pick an answer to see why it's right or wrong.
A request arrives with a valid JWT for user 42, asking to cancel booking 9001 owned by user 77. Who should reject it?
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.
Key takeaways
- The gateway is the one controlled front door: routing plus cross-cutting policy, so services don't each re-implement them.
- Authenticate at the gateway; keep resource-level authorization in the service that owns the data.
- Quotas belong at the gateway because it knows the caller. Return 429 with Retry-After.
- Aggregation and BFFs simplify clients but couple latency: call in parallel with per-call timeouts.
- Every downstream call needs a timeout. Retry only idempotent requests, and use circuit breakers to fail fast.
- No business logic in the gateway, and never log tokens or personal data.
- Run it stateless, multi-instance and multi-zone, with staged config rollouts. Otherwise it becomes the single point of failure.
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.
Token bucket, leaky bucket, sliding windows and Redis-based distributed limits: the gateway's most important policy, in depth.
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
Last reviewed 18 November 2026