Design an API Gateway
Hundreds of internal services need one front door that checks who is calling, limits how often, sends each request to the right place and records what happened. This lesson designs that gateway: a stateless data plane of proxies running a chain of filters, fed by a control plane that rolls out routes and policies safely, with local token checks, a two-level rate limiter, resilient routing, and tracing on every request.
What you will learn
- Split the gateway into a stateless data plane that handles requests and a control plane that manages configuration.
- Each request passes through a chain of filters: TLS, auth, rate limit, routing, transformations, observability.
- Verify signed tokens locally with cached public keys; never call an auth service on every request.
- Rate limit with local counters synced to a shared store, accepting small overshoot for low latency.
- Protect services with timeouts, retry budgets, circuit breakers and load shedding, not just retries.
- Roll out configuration like code: validated, versioned, canaried, and instantly reversible.
In this lesson
- The question
- Step 1: Clarify the requirements
- Step 2: Back-of-the-envelope estimates
- Step 3: Data plane and control plane
- Step 4: The request pipeline
- Step 5: Authentication without a network call
- Step 6: Rate limiting across a hundred proxies
- Step 7: Stopping abuse before it costs anything
- Step 8: Routing and service discovery
- Step 9: Protecting the services behind it
- Step 10: Observability
- Step 11: Rolling out configuration safely
- Step 12: One request, end to end
- Step 13: Scaling and failures
- Step 14: The parts people forget
- Step 15: The follow-up questions
- Recap
The question
Welcome to lesson twenty-six of the InterviewDryRun system design course. Today we design an API gateway: the single front door that every external request passes through before reaching any of a company's internal services.
Without a gateway, each of hundreds of services must check tokens, apply rate limits, terminate encryption, log requests and handle abuse on its own. Each team does it slightly differently, and the weakest one becomes the way in. A gateway puts those cross-cutting concerns in one place. That makes it extremely valuable, and also extremely dangerous: if it is slow, everything is slow, and if it is down, the whole company is down. This interview is about building something central that does not become the single point of failure.
Max asks
“Design a gateway that handles auth, rate limits, routing and observability for hundreds of services.”
That is how Max, our AI interviewer, asks it. Four responsibilities are named: authentication, rate limits, routing, observability. Treat them as a checklist you must cover. And hundreds of services tells you that configuration is a real problem: hundreds of teams change routes and policies every day, and a bad change can break everything at once.
The plan: requirements and numbers, then the shape of the system, a data plane and a control plane. Then the request pipeline, followed by deep dives on authentication, rate limiting, routing and resilience, and observability. Then rolling out configuration safely, one request end to end, scaling, failures, and the follow-up questions.
Step 1: Clarify the requirements
- 01RouteMap host, path and method to a backend service
- 02AuthenticateUser tokens, partner API keys, service identity
- 03Rate limitPer client, per route, per plan
- 04ObserveMetrics, logs and traces for every request
- 05Self-service configTeams manage their own routes and policies
Start with questions.
The gateway receives every external request and routes it by host, path and method to the right backend service: slash orders goes to the orders service, slash payments to payments.
It authenticates callers. Ask which kinds: signed-in users with tokens from our identity service, partners with API keys, and perhaps mobile apps. It rejects requests that fail, before they reach any service. And it rate limits: per client, per route, and often per pricing plan, so a free partner gets a hundred requests a minute and a paying one ten thousand.
It records metrics, logs and traces for every request. And because there are hundreds of services, teams must be able to change their own routes and policies without waiting for a central team, but without being able to break anyone else's. Ask whether the gateway should also transform requests or combine several backend calls into one. Usually light transformations yes, heavy business logic no.
- 01Low added latencyA few milliseconds at the median
- 02Very high availabilityMore available than any service behind it
- 03Scales horizontallyAdd proxies for more traffic
- 04IsolationOne bad route or service cannot hurt others
- 05Safe changeBad config caught before it spreads
The qualities.
Latency: every request pays the gateway's cost, so it must add only a few milliseconds. Availability: the gateway must be more available than the services behind it, because its downtime is everyone's downtime.
It must scale by adding machines, isolate failures between routes and services, and, the one candidates forget, make configuration changes safe. Many large outages across the industry were not hardware failures but a bad configuration pushed to every proxy at once. Say that out loud, and you have already shown seniority.
Step 2: Back-of-the-envelope estimates
Let us size it.
Say one million requests a second at peak, across all services. A well-built proxy handles around twenty thousand requests a second per server for typical small requests, so about fifty proxies, and we would run a hundred, spread across zones, for headroom and failures.
The latency budget is under five milliseconds at the median. That rules out anything that makes a network call on every request, like asking an auth service to validate each token, or a remote rate-limit check with a slow store. Keep that number in mind; it drives the authentication and rate-limiting designs.
Five thousand routes across four hundred services is small: the whole route table fits in memory on every proxy, a few megabytes. Rate-limit state for ten million users and fifty thousand keys is also small per entry, but it must be shared across a hundred proxies, which is the interesting part.
Logs: a million requests a second at about five hundred bytes each is half a gigabyte a second, over forty terabytes a day. So we will sample detailed logs and keep metrics for everything. Saying that early shows you noticed that observability has a cost too.
Step 3: Data plane and control plane
The most important structural idea: split the gateway into two parts.
The data plane is the fleet of proxies that handle requests. A simple layer four load balancer spreads connections across them. Each proxy is stateless: it holds the configuration in memory and needs nothing else to process a request.
The proxies route requests to the backend services, hundreds of them.
The control plane is separate. Teams define routes and policies in configuration, ideally kept in version control with review. The control plane validates it, compiles it into a complete snapshot, and pushes it to every proxy.
The crucial property: if the control plane goes down, the proxies keep serving with their last good configuration. Nobody can change routes for a while, which is annoying, but no request fails. The request path never depends on the control plane. Separating what must be fast and always up from what changes things is a pattern worth naming in many designs.
The rate-limit store is the one piece of shared state the proxies use, and we will design it so that even its failure does not stop traffic.
Step 4: The request pipeline
1 TLS termination, HTTP parsing, size limits 2 request id, start trace span 3 match route (host + path + method → route config) 4 authenticate (token or API key) → identity 5 authorise (route policy: scopes, plans) 6 rate limit (identity + route) 7 transform (headers, path rewrite, strip secrets) 8 forward (pick instance, timeout, retry budget) 9 response (metrics, access log, trace end)
Inside a proxy, every request runs through a chain of filters, in a fixed order.
First, terminate the encryption and parse the request, rejecting oversized or malformed ones cheaply. Then assign a request id and start a trace, so everything after this is observable.
Then match the route, because the route's configuration decides which authentication, limits and backend apply. Authentication comes next, then authorisation against the route's policy, then rate limiting, which needs the identity to know whose budget to charge.
Order matters, and it is worth explaining. Authentication before rate limiting means limits are per real client. But unauthenticated floods must also be stopped, so apply a coarse per-address limit even before authentication. Cheap checks first, expensive checks later, and nothing reaches a service until it has passed every check.
Finally, light transformations, such as adding the verified user id as a header and removing the original token, then forwarding to the service, and recording metrics and logs when the response returns. Each filter is a small, well-tested module, and routes choose which optional filters they enable. That modularity is what lets one team of gateway engineers serve hundreds of service teams.
Step 5: Authentication without a network call
| Caller | Credential | How the gateway checks it |
|---|---|---|
| Signed-in user | short-lived signed token | verify signature locally with cached public keys |
| Partner | API key | hash it; look up in a local cache, refreshed |
| Internal service | mutual TLS certificate | verify the certificate chain |
| Revoked token | deny list | small list pushed to every proxy |
The latency budget rules out calling an auth service on every request. So how do we check identity quickly?
For users, the identity service issues short-lived tokens, valid for, say, fifteen minutes, signed with its private key. Each proxy holds the matching public keys, refreshed every few minutes. Verifying a signature is pure computation, well under a millisecond, with no network call. The token contains the user id and scopes, so the gateway knows who it is and what they may do.
For partners, API keys. The gateway hashes the key and looks it up in a local cache of key records: which partner, which plan, which scopes. On a miss, it asks the key service once and caches the answer for a few minutes. Store only hashes of keys anywhere, so a leaked database does not leak keys.
Internal callers prove their identity with certificates through mutual encryption, which the gateway verifies the same way.
The weakness of self-contained tokens is revocation: a token stays valid until it expires, even if the user logs out or is banned. Short lifetimes limit the damage, and for urgent cases, the control plane pushes a small deny list of revoked token ids to every proxy within seconds. That combination, local verification with short lifetimes and a pushed deny list, is the answer interviewers look for.
After authentication, the gateway removes the original credential and forwards a header with the verified identity, signed or protected by the internal network, so services trust the gateway's word and never need to re-check tokens. Services must accept that header only from the gateway, never from outside.
Step 6: Rate limiting across a hundred proxies
- 01AlgorithmToken bucket per client and route
- 02Pure central storeExact, but a network hop on every request
- 03Pure localFast, but limit × number of proxies
- 04Local + syncLocal counters, synced every 100 ms
- 05Store downFail open, keep local limits
Rate limits have their own lesson, lesson two, so here we focus on what is special about a gateway: a hundred proxies must enforce one shared limit per client.
A token bucket per client and route is the usual algorithm: a bucket refills at the allowed rate, each request takes a token, and an empty bucket means four-two-nine, too many requests.
Where do buckets live? In a central in-memory store, every request makes a network call, maybe half a millisecond, which fits the budget but makes the store a critical dependency carrying a million operations a second. Purely local buckets on each proxy are free, but a client spread across a hundred proxies would get a hundred times its limit.
The common middle ground: each proxy counts locally and, every hundred milliseconds or so, sends its counts to the shared store and gets back the global total. Between syncs, a client might overshoot by a little, which is fine for rate limits, which protect capacity rather than money. For very strict limits, like ten requests a minute on a password reset route, call the store directly on each request; that route has low traffic anyway.
And if the store is down? Fail open: keep enforcing per-proxy limits based on the number of proxies, and let traffic through. Rejecting every request because the limiter is down would turn a small outage into a total one. Always say which way a protective component fails, and why.
Return helpful headers: the limit, how many remain, and when the bucket refills, so well-behaved clients can slow down before they hit the wall.
Step 7: Stopping abuse before it costs anything
- 01Network edgeAbsorb floods before they reach proxies
- 02Cheap early checksPer-address limits, size caps, header sanity
- 03Request rulesBlock known attack patterns per route
- 04Bot signalsChallenge suspicious clients on login and sign-up
Rate limits handle clients who are known and slightly too eager. A gateway also faces traffic that is hostile: floods, credential stuffing, scrapers. That needs defences in front of the filter chain.
The first layer is the network edge: a content delivery network or a scrubbing service in front of our load balancers absorbs huge floods of junk traffic, so they never reach our proxies at all. Our proxies are sized for real traffic, not for an attacker's botnet.
The second layer is the cheapest checks in the proxy itself, before any parsing of tokens: a limit per source address, caps on header and body size, and timeouts for clients that send their request very slowly to hold connections open. Each costs microseconds and removes a whole class of attacks.
The third is a set of request rules: block requests that match known attack patterns, such as injection attempts in query strings, configurable per route, because a search route and a file upload route have very different normal traffic.
And the fourth is bot detection on sensitive routes like login, sign-up and password reset. Attackers try leaked passwords from other sites at huge scale. Strict per-account and per-address limits, plus a challenge for clients that look automated, stop most of it. The principle to say: spend the least effort on the most obviously bad traffic, as early as possible, so the expensive checks only see requests that might be real.
Step 8: Routing and service discovery
route: orders-api match: host api.example.com, path /v1/orders/* auth: user-token, scopes [orders:read] limits: free 100/min, pro 10,000/min backend: service orders, timeout 2 s, retries 1 (GET only) canary: orders-v2 5% owner: team-orders
Now routing. The route table maps host, path prefix and method to a backend.
A team declares a route: what it matches, what authentication and scopes it requires, its limits per plan, the backend service, its timeout and retry policy, and optionally a canary that sends a small share of traffic to a new version. The owner field says which team may change it.
Matching must be fast with five thousand routes. Compile routes into a tree keyed by host and then path segments, so matching a request takes a few lookups, not a scan. And detect conflicts at validation time: two teams claiming the same path is rejected before it ever reaches a proxy.
The backend is a service name, not an address. Service instances come and go as they scale and deploy, so the proxy learns their current addresses from a service registry, pushed by the control plane, and load balances across healthy instances. Choosing the instance with the fewest requests in flight works better than round robin when some requests are slow. Health checks, both active probes and passive observation of errors, remove bad instances within seconds.
Routing is also where API versions live. Version one and version two of the orders API can be two routes pointing at different backends, or the same backend with a header added. The gateway lets a team move traffic between versions gradually with the canary weight, and lets old versions be retired with a clear error and a date, instead of silently breaking clients. Keeping version choices in configuration, rather than in code, means a rollback is a configuration change of one line.
Step 9: Protecting the services behind it
- 01TimeoutsEvery route has one; never wait forever
- 02Retry budgetRetries ≤ 10% of requests; idempotent calls only
- 03Circuit breakerToo many failures? Fail fast for a while
- 04Load sheddingOver capacity? Reject low-priority work first
- 05BulkheadsSeparate connection pools per service
A gateway that forwards blindly will happily send a struggling service more traffic than it can handle. It should protect the services behind it, and itself.
Timeouts on every route. Without them, one hung service ties up connections until the proxy itself runs out and fails for everyone.
Retries are useful for brief blips, but dangerous at scale: if a service is overloaded and every client retries three times, the load quadruples just when it can least cope. So retry only idempotent requests, like reads, at most once, and cap retries with a budget, say no more than ten percent of requests to a service, so retries can never multiply an overload.
A circuit breaker per service watches error rates. When failures pass a threshold, it opens: requests to that service fail immediately with a clear error, instead of waiting for timeouts. After a pause it lets a few test requests through, and closes again if they succeed. This gives the service room to recover.
Load shedding: when the gateway or a service is past capacity, reject some requests early, with a five-oh-three and a retry-after header, rather than letting everyone time out. Shed the least important traffic first, such as background sync, before checkout. And bulkheads: separate connection pools per backend service, so one slow service cannot use up the connections every other service needs. These five tools are the difference between a gateway that spreads failures and one that contains them.
Step 10: Observability
- 01MetricsRate, errors, latency per route, service, status
- 02TracesTrace id created or passed on; sampled spans
- 03Access logsAll errors and slow requests; sample the rest
- 04DashboardsPer team, for their routes
The fourth responsibility in the question. The gateway sees every request, which makes it the best place to measure the whole system from the outside.
Metrics for everything: request rate, error rate and latency percentiles, by route, by backend service and by status code. These are cheap counters and histograms aggregated in the proxy and scraped every few seconds. They drive alerts and the per-team dashboards.
Tracing: the gateway creates a trace id, or accepts one from a trusted caller, and passes it to the service in a header, which passes it on to every service it calls. Then one slow request can be followed through ten services. Record detailed spans for a sample, say one percent, plus every error and every slow request.
Access logs follow the same rule: log every error and every slow request in full, and sample the healthy majority. That keeps the forty terabytes a day down to a few, with no loss of the information people actually search for. Remove secrets, tokens and personal data from logs at the gateway, in one place, instead of trusting every service to do it.
Give every team a dashboard of their own routes, generated automatically from the route configuration. The gateway's position makes this almost free, and it is often the first place a team notices their service is slow.
Step 11: Rolling out configuration safely
- 01ValidateSchema, conflicts, ownership, regex cost limits
- 02VersionEvery snapshot numbered; proxies report what they run
- 03CanaryA few proxies first; watch errors and latency
- 04ProgressiveZone by zone over minutes
- 05Roll backOne step back to the last good snapshot
Now the topic that separates senior answers. Hundreds of teams change routes daily. A typo in one rule, such as a regular expression that takes seconds to evaluate, pushed to every proxy at once, can take down the entire gateway.
Validate every change: the schema, conflicts with other routes, that the team owns the paths it changes, and the cost of any pattern matching. Run the new configuration against recorded sample requests to see that it routes them as expected.
Version every compiled snapshot, and have each proxy report which version it runs, so we always know what is live where.
Then roll out like code. Push the new snapshot to a few canary proxies first and compare their error rates, latency and memory use with the rest. If they are healthy, continue zone by zone over minutes. If anything degrades, stop and roll back automatically to the previous snapshot, which every proxy still holds.
Two more safety nets. Proxies validate a new snapshot themselves before switching to it, and keep the old one if it fails. And keep an emergency path that lets an engineer push one change quickly during an incident, with an audit record. Treat configuration as code, because it is: it changes production behaviour just as much.
Step 12: One request, end to end
| ms | What happens |
|---|---|
| 0.0 | TLS on a kept-alive connection; request parsed |
| 0.1 | request id r-91; trace started |
| 0.15 | route orders-api matched in the tree |
| 0.3 | token signature verified locally; user 7, scope orders:read |
| 0.35 | local bucket: 37 tokens left; allowed |
| 0.4 | least-loaded healthy instance of orders chosen |
| 18 | orders answers 200; metrics and sampled log written |
Let us follow one request through everything.
A user's app sends a request for order forty-two. It arrives over an already-open encrypted connection to one of our proxies. The proxy parses it, gives it a request id, and starts a trace.
The route tree matches orders-api in a few lookups. The token's signature is checked with the cached public key; it is valid, the user is seven, and the scopes include orders read, which the route requires. The local token bucket for user seven on this route has thirty-seven tokens left, so the request is allowed. Under half a millisecond has passed.
The proxy removes the token, adds headers with the verified user id and the trace id, picks the healthy orders instance with the fewest requests in flight, and forwards with a two-second timeout. Orders answers in about eighteen milliseconds. The proxy records the latency in its histograms, writes no full log line because the request was fast and successful, and returns the response. The gateway added well under a millisecond of its own time.
Step 13: Scaling and failures
- 01Stateless proxiesAdd more; spread across zones and regions
- 02Proxy diesLoad balancer health checks remove it
- 03Control plane downProxies keep last good config
- 04Rate-limit store downFail open with local limits
- 05Identity service downTokens still verify; new logins wait
Scaling and what breaks.
Proxies are stateless, so scaling is adding more behind the load balancer, in every zone, and in every region, with clients directed to the nearest region by DNS. Keep enough spare capacity that losing a whole zone leaves the rest under their limits.
Go through each dependency and say what happens without it. A dead proxy is removed by health checks. A dead control plane freezes changes but not traffic. A dead rate-limit store means local limits only. A dead identity service stops new sign-ins, but existing tokens still verify locally until they expire. That last one is a strong reason for local verification: the gateway keeps working even when the auth system does not.
Notice the pattern: every dependency of the gateway is off the critical path or has a safe fallback. That is how a central component becomes more available than the services behind it, which was our non-functional requirement.
Step 14: The parts people forget
- 01Long-lived connectionsWebSockets and streaming need special care
- 02Big uploadsStream bodies; do not buffer gigabytes
- 03BrowsersCORS rules per route
- 04DrainingDeploy proxies without cutting connections
A few details that round out the answer.
Long-lived connections like WebSockets live for hours, so a proxy restart cuts them. Route them to a separate pool of proxies, and drain gracefully on deploys: stop accepting new connections and give existing ones time to finish or reconnect.
Large uploads must be streamed through to the backend rather than held in proxy memory, or a few large files can exhaust a proxy. Better still, have clients upload directly to storage with a signed address and send only the metadata through the gateway.
Browsers need cross-origin rules, configured per route, so a web app on one domain can call the API on another. And every proxy deploy must drain connections gracefully, because a hundred proxies are deployed often, and each careless restart drops thousands of requests.
Step 15: The follow-up questions
Max asks
“Should the gateway combine calls to several services into one response for the mobile app?”
That is the backend-for-frontend pattern. It is useful, but it is business logic, and putting business logic in the shared gateway makes every team depend on gateway releases. I would build it as a separate service per client type, owned by the app teams, sitting behind the gateway like any other service. The gateway stays generic and boring, which is what you want from a front door.
Max asks
“Isn't the gateway a single point of failure?”
It is a single logical component, but not a single machine: many stateless proxies across zones and regions, behind redundant load balancers, with no runtime dependency that can stop traffic. The real single point of failure is shared configuration, which is why changes are validated, canaried and reversible. If someone asks this, talk about configuration, not hardware.
Max asks
“How would you rate limit by cost rather than by count, when some requests are much more expensive?”
Give each route a cost, or compute one from the request, such as the page size of a search, and take that many tokens from the bucket instead of one. For costs known only afterwards, like query time, charge the bucket when the response returns, and let the client go briefly negative. The algorithm stays a token bucket; only the amount taken changes.
Max asks
“How do services trust the identity the gateway passes on?”
Services accept identity headers only on connections authenticated as the gateway, using mutual encryption with certificates, and the gateway strips any such headers arriving from outside. For stronger guarantees, the gateway sends a short-lived internal token it signed, which services verify locally. Either way, an external caller can never forge the header.
Recap
- 010 to 5: requirementsAuth, limits, routing, observability; safe change
- 025 to 10: estimates1 million req/s; < 5 ms; 100 proxies
- 0310 to 20: shapeData plane and control plane; filter chain
- 0420 to 35: deep divesLocal auth, synced limits, routing, resilience
- 0535 to 45: operationsObservability, config rollout, failures
On the clock: five minutes on requirements, naming the four responsibilities and the need for safe change. Five minutes of numbers: a million requests a second, under five milliseconds added.
Ten minutes on the shape: a stateless data plane, a control plane it never depends on at request time, and the filter chain.
Fifteen minutes on the deep dives: tokens verified locally, rate limits synced across proxies, routing with service discovery, and timeouts, retry budgets and circuit breakers. And ten minutes on observability, safe configuration rollout and failures. If you say that the biggest risk to a gateway is a bad config change, and show how you contain it, you will stand out.
Infrastructure questions like this reward clear structure, and structure comes from practicing out loud. You can practice this exact question with Max, our AI interviewer, at interview dry run dot com. It is free to start, and you get a scored report with what to fix. The written lesson, with every diagram, is on the site too. See you in lesson twenty-seven.
Now say it out loud
Watching an answer is not the same as giving one. Max asks this exact question, pushes back when an answer is vague and keeps time, then scores you per skill.
Practice with MaxFree: a 5-minute voice round and unlimited typed drills, with scored feedback. No card, and your camera is never recorded.