API gateways in system design interviews
An API gateway is the single entry point that sits between clients and a set of backend services. It routes each request to the right service and handles the shared chores on the way: TLS, authentication, rate limits, request shaping, timeouts and logging. In an interview, drawing it is easy; the marks come from saying exactly which jobs it owns, how it fails, and why it does not become a bottleneck.
By Evin JohnPublished 7 min read
1. What an API gateway is
A gateway is a reverse proxy with opinions. Clients call one public hostname; the gateway matches the path, method and headers against a route table and forwards the request to an internal service. Before forwarding, it checks who the caller is and whether they are allowed this call at this rate; after the response returns, it records what happened. Products in this space include managed services from cloud providers and self-hosted proxies such as Envoy, Kong or NGINX-based setups, but in an interview the behavior matters more than the brand.
2. Why interviewers ask about it
Almost every microservice diagram has a gateway box at the top, so interviewers probe it to check that you understand what lives there and what does not. Typical follow-ups: where is the token validated, what happens when a downstream service hangs, how does a rate limit work across many gateway nodes, and is this a single point of failure? Crisp answers show you have operated real traffic rather than copied a diagram.
3. What a gateway does, and what it should not
| Job | What it means | Interview detail worth adding |
|---|---|---|
| Routing | Map /v1/orders/* to the order service, /v1/users/* to the user service | Support weighted routes for canary releases (send 5% to the new version) |
| TLS termination | Decrypt HTTPS at the edge, talk to services over internal TLS or a mesh | Certificates are managed centrally and rotated automatically |
| Authentication | Validate API keys or JWTs, attach the caller's identity as headers | Validate signed tokens locally with cached public keys; do not call the auth service per request |
| Authorization (coarse) | Reject calls to routes the caller's scope does not allow | Fine-grained checks ("can this user edit this order?") stay in the service |
| Rate limiting and quotas | Per key, per user or per IP limits; 429 with retry headers | Shared counters in Redis or local limits per node; see the rate limiter design |
| Request shaping | Size limits, header normalization, protocol translation (REST to gRPC) | Reject oversized bodies early, before they reach a service |
| Observability | Access logs, metrics per route, trace ID injection | The gateway is where a trace begins, so it creates or forwards the trace ID |
What does not belong there: business rules, database calls and heavy response stitching. A gateway that knows about discounts or order states has become a shared monolith that every team must change, deploy and debug together.
4. How a request flows: data plane and control plane
- Clients
- Mobile, web, partner integrations
- Edge
- CDN / DDoS protection
- Layer 4 or 7 load balancer
- Data plane
- Gateway nodes (stateless)
- Rate-limit counter store
- Key and token cache
- Services
- Users
- Orders
- Payments
- Search
- Control and telemetry
- Control plane (routes, policies, certs)
- Logs, metrics, traces
- AcceptThe load balancer passes the connection to any gateway node; nodes hold no session state, so any one will do.
- CheckTerminate TLS, validate the token signature and expiry, look up the caller's plan and check the rate limit.
- RouteMatch the route, choose a healthy upstream instance (round robin or least connections), and forward with a deadline.
- RespondReturn the upstream response, or a 429, 503 or 504 generated by the gateway, and log the outcome with the trace ID.
The control plane matters in follow-ups. Route changes are written to a config store, validated, and pushed to nodes, which swap them in atomically. If the control plane goes down, nodes keep serving with the last good config. Data plane traffic should never depend on the control plane being up.
5. Timeouts, retries and circuit breakers
A gateway forwards traffic to many services. If one of them hangs, requests pile up on gateway nodes, connections and memory run out, and calls to healthy services start failing too. Three tools prevent that cascade.
- Deadlines per route. Each route has a timeout that fits its normal latency, and the remaining budget is passed downstream in a header so services stop work the client has given up on.
- Retry budgets. Retry only idempotent requests (GETs, or writes with an idempotency key), at most once or twice, with backoff and jitter, and cap retries to a small fraction of total traffic so retries cannot double the load during an outage.
- Circuit breakers. After repeated failures, stop calling the upstream for a cooldown and fail fast with 503, then let a single trial request through to test recovery.
// A per-upstream circuit breaker: closed -> open after N straight failures,
// open -> half-open after a cooldown, half-open lets one trial request through.
class CircuitBreaker {
constructor({ failures = 5, cooldownMs = 10000, now = Date.now } = {}) {
this.limit = failures; this.cooldownMs = cooldownMs; this.now = now;
this.state = "closed"; this.fails = 0; this.openedAt = 0; this.trial = false;
}
allow() {
if (this.state === "open" && this.now() - this.openedAt >= this.cooldownMs) {
this.state = "half-open"; this.trial = false;
}
if (this.state === "closed") return true;
if (this.state === "half-open" && !this.trial) { this.trial = true; return true; }
return false; // fail fast: the gateway answers 503 without calling upstream
}
record(ok) {
if (ok) { this.state = "closed"; this.fails = 0; return; }
this.fails += 1;
if (this.state === "half-open" || this.fails >= this.limit) {
this.state = "open"; this.openedAt = this.now(); this.fails = 0;
}
}
}Real proxies usually trip on an error rate over a sliding window rather than a count of consecutive failures, and keep one breaker per upstream host. The idea is the same: protect the caller, give the callee room to recover.
6. Gateway, load balancer, service mesh or BFF?
| Component | Main job | Traffic it handles |
|---|---|---|
| Load balancer | Spread connections across identical instances; health checks | Any traffic; little knowledge of APIs or callers |
| API gateway | Route by API, authenticate, limit, observe at the edge | North-south: from outside clients into the system |
| Service mesh | Mutual TLS, retries, timeouts and telemetry between services via sidecars or node proxies | East-west: service to service inside the system |
| Backend for frontend (BFF) | One small service per client type that aggregates calls and shapes responses | Sits behind the gateway; owns screen-specific logic |
If the mobile app needs data from five services for one screen, put that aggregation in a BFF owned by the mobile team, not in gateway config. The gateway stays generic; the BFF can change with the app.
peak traffic: 200,000 requests a second
per node: about 10,000 requests a second with TLS, JWT checks and logging (assumed)
nodes needed: 200,000 / 10,000 = 20
headroom: run at about 60% so a zone can fail: 20 / 0.6 = about 34
spread: 3 zones, so about 12 nodes per zone
added latency: a few milliseconds per request; measure it per route7. How the gateway shows up in common prompts
| Prompt | What the gateway does there | The interesting part |
|---|---|---|
| Rate limiter | Hosts the limiter middleware | Shared counters versus per-node limits, and fail-open policy |
| E-commerce checkout | Auth and per-account limits on place-order | Stopping bots during a flash sale before they reach inventory |
| Video conferencing | Fronts the meeting API and signaling sockets | Media never passes through it; WebSocket routing needs sticky connections |
| Distributed logging | Ingest gateways authenticate agents and enforce quotas | 429 with backoff protects storage from one noisy tenant |
| Payment system | Validates idempotency keys are present on writes | Retries at the edge must never create a second charge |
8. Mistakes to avoid
- Putting business logic in the gateway. It couples every team to one deploy and one config file.
- Calling the auth service on every request. Validate signed tokens locally and cache keys; revoke with short token lifetimes or a small deny list.
- No timeouts. A default of "wait forever" turns one slow service into a full outage.
- Retrying everything. Retrying non-idempotent writes can create duplicate orders or charges.
- Calling it a single point of failure without fixing it. Run many nodes across zones behind a load balancer, and keep the data plane independent of the control plane.
- Forgetting WebSockets and streaming. Long-lived connections change how you scale, drain and deploy gateway nodes.
9. How to talk about it in the interview
- Name the three or four jobs your gateway owns in this design, not a generic list.
- Say where auth happens and how the identity reaches services (a signed header or the token itself).
- Mention timeouts and breakers before the interviewer asks what happens when a service hangs.
- Size the fleet with one line of arithmetic and say it is stateless.
Fictional example
- Interviewer
- Everything goes through this gateway. Isn't that a single point of failure?
- Candidate
- It is a single logical entry point, not a single machine. The nodes are stateless, so I run around a dozen per zone across three zones behind a load balancer and can lose a zone. Rate-limit counters are in a replicated store, and if that store is unreachable the nodes fall back to local limits rather than blocking everyone.
- Interviewer
- And a bad config push?
- Candidate
- The control plane validates the config, rolls it out to a few nodes first and watches error rates. Nodes keep the last good config if the push fails, and rollback is one version change.
Practicing with Natively
Gateway questions are short and frequent, which makes them ideal for quick drills. On a practice call, Natively transcribes your answers on your own computer and can suggest the points you might add to the question just asked, such as retry budgets or the control plane. If you have drawn the request flow, share a screenshot and ask it what is missing. Reviewing the transcript later helps you cut long answers down to the two sentences interviewers actually want.
Questions people ask
What is an API gateway in system design?
It is the single entry point between clients and backend services. It routes each request to the right service and handles shared concerns on the way: TLS termination, authentication, rate limits, request size checks, timeouts and logging, so individual services do not each reimplement them.
What is the difference between an API gateway and a load balancer?
A load balancer spreads connections across identical instances and checks their health, with little knowledge of the API. A gateway understands routes, callers and policies: it decides which service gets a request, whether the caller is allowed and within limits, and it usually sits behind a load balancer itself.
Is an API gateway a single point of failure?
Only if you run it as one machine. Gateway nodes are stateless, so you run many across availability zones behind a load balancer, keep serving with the last good configuration if the control plane is down, and fall back to local rate limits if the shared counter store is unreachable.
Should business logic go in the API gateway?
No. Keep the gateway to routing and cross-cutting policy. Aggregating data for a particular screen belongs in a backend-for-frontend service, and rules such as pricing or order states belong in the owning service, so teams can change them without touching shared gateway config.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
