To design an API gateway is to decide which jobs every request must pass through before it reaches a service (checking who the caller is, limiting abuse, finding the right service, combining answers) and how the gateway protects itself and the services when something slows down. A good answer keeps the gateway thin and fast, lists what belongs in it and what does not, and shows with numbers what each choice costs.
This lesson designs the gateway for BusTrack, the bus tracking app from Load Balancing: Introduction, in front of its trips, stops, alerts and tickets services. Six runnable programs in Java, with Python and C++ versions, test the decisions interviewers probe most: authentication and blocking, combining several calls into one, caching a hot key, a circuit breaker, isolating a slow service, and releasing a new version safely. Capacities and timings are assumptions chosen to make comparisons clear, not benchmarks of a product.
Key takeaways
Checking a token's signature once and remembering it needed 55,370 checks for 540,000 requests (about 10%). With a 900 second token life, 20.4 refreshes per second reached the auth service. A 15 second life raised that to 243.5 per second.
Short tokens alone are a poor way to stop a blocked account. A pushed block list with a 10 second delay let 38 blocked requests through; a 300 second delay let 1,075 through.
A screen that needs four calls was slow (above 300 ms) for 7.7% of riders when each call was slow only 2% of the time. Calling in parallel with timeouts cut the p99 from 741 ms to 400 ms.
When one stop became hot, a plain cache still sent 22 simultaneous calls for it. One call per key sent 1, and serving a slightly stale copy while refreshing served 98.5% of all requests from cache.
A circuit breaker cut the average time per request from 904 ms to about 27 ms when a service failed.
With one shared pool of 100 workers, a slow ticket service dragged trips and stops down to 25.2% served. Separate pools kept them at 100%.
For a bug that failed 20% of requests, a staged rollout rolled back after 76 failed requests. Shipping to everyone and waiting for a person took 6,401.
1. Clarifying Requirements
Functional requirements
One public entry point for the rider app, with stable URLs such as
/v1/trips/...,/v1/stops/...and/v1/tickets/..., whatever the internal services are called.Authenticate each request (a signed token) and reject blocked accounts.
Rate limit callers (the algorithm is a lesson of its own, Design Rate Limiter; here we only place it).
Route to the right service, and combine several service calls into one response for screens that need it.
Cache responses that are safe to cache.
Protect services from overload and release new versions gradually.
Non-functional requirements
120,000 requests per second at peak, behind the load balancers from Design Load Balancer.
The gateway adds only a few milliseconds and never becomes the single point of failure.
A slow or failing service must not take the rest down.
Configuration changes are versioned and reversible.
Say what you leave out: business rules (they stay in the services), payments, and web application firewall rules.
2. Back-of-the-Envelope Estimation
Traffic: 120,000 requests per second at peak. We assume one gateway node can authenticate, route and proxy 8,000 requests per second, so 15 nodes would run at 100%. With 18 nodes the load is 83.3%, rising to 88.2% after one failure and 93.8% after two.
Authentication cost: from the first program, remembering a verified token cuts signature checks by about 90%, which is what lets a node reach that rate.
Configuration: 600 routes at about 2 KB each is a 1.2 MB snapshot, small enough to push to all 18 nodes in a second.
Latency budget: a few milliseconds at the 99th percentile for the gateway itself. Anything that can take longer (calls to services) is accounted for separately.
Plan for failures, and save work on the hot path.
3. Core APIs
The gateway has two kinds of interface. Clients call the public API (the thing the gateway sells). Operators use a control API to change routes and policies.
One aggregated public call: GET /v1/screens/stop/{stopId} returns arrivals, vehicle positions, alerts and fares for one stop screen. The gateway makes the four service calls and replies once. Optional parts that time out are left out and listed in a missing array so the app can retry them.
{
"stop": "HYD-0412",
"arrivals": [ { "route": "219", "in_min": 3 } ],
"positions": [
{ "bus": "TS09-4471", "lat": 17.43, "lon": 78.41 }
],
"missing": [ "alerts" ]
}
Control API (versions work like the load balancer's pools: send the whole desired state, accept only the next version number, switch in one step).
PUT /v1/gateway/routesreplaces the routing table, with aversionthat must be the current one plus one. The reply is202with{"version": 87, "state": "staged"}.PUT /v1/gateway/policies/{route}sets timeouts, cache rules, breaker limits and worker pool sizes for one route.POST /v1/gateway/versions/87:activatemakes a staged version live;:rollbackwith an older number reverts.PUT /v1/gateway/rollouts/tripssets the share of traffic sent to a new version, for example{"v2_percent": 5, "sticky_by": "rider"}.GET /v1/gateway/statuslists each node's version, its breakers (closed,open,half_open) and its worker pools.
4. High-Level Design
Requests come from the load balancers to a fleet of identical, stateless gateway nodes. Each node runs the same ordered pipeline.
Cheap checks first, expensive work last.
Limits and timeouts: reject oversized requests early and set a deadline for the whole request.
Authenticate, then rate limit: a request that cannot prove who it is should not use up anyone's rate limit.
Route, cache, breaker, bulkhead: find the service, answer from cache if possible, and otherwise call it through its breaker and its own worker pool.
As in the load balancer design, the pipeline reads an immutable snapshot of routes and policies, and the control plane swaps a new snapshot in one step.
Nodes read a snapshot; the control plane publishes versions.
The gateway is one tier between the load balancers and the services.
5. Authentication and Blocking
The app sends a signed JWT (JSON Web Token, RFC 7519) in the Authorization header. The gateway checks the signature with a published key (a JWK, RFC 7517) and reads the rider id and expiry, so the services never see a bad token. Checking a signature costs CPU, and a token stays valid until it expires, so two questions matter: how often do we check, and how fast can we stop a blocked account?
The first program has 20,000 riders and 300 requests per second for 30 minutes. 300 accounts are blocked at random times. An app refreshes its token only when it next makes a request after the old one expired. The signature is checked once per token and remembered.
Output
20000 riders, 300 requests/s for 1800 s (540000 requests). 300 accounts are blocked between second 300 and 1500.
Checking a signature costs the gateway CPU, and the auth service pays for every token refresh.
A: the gateway only trusts the token until it expires (no block list)
token lifetime refreshes per second signature checks, every request checks, once per token blocked requests let through
3600 s 5.3 540000 29237 3264
900 s 20.4 540000 55370 1717
300 s 53.3 540000 111850 550
60 s 155.9 540000 287660 60
15 s 243.5 540000 440567 4
B: token lifetime 900 s, plus a block list pushed to every gateway node after a delay
block list delay blocked requests let through requests refused
0 s 0 3942
1 s 5 3937
10 s 38 3904
60 s 251 3691
300 s 1075 2867
Remembering the verification helped a lot: with a 900 second token life only 55,370 of the 540,000 requests needed a signature check.
Short tokens cut how long a blocked account keeps working: 3,264 blocked requests got through with a 3,600 second token, 1,717 with 900 seconds, 550 with 300 seconds, 60 with 60 seconds and 4 with 15 seconds.
The price is refresh traffic on the auth service: 5.3 per second, 20.4, 53.3, 155.9 and 243.5 per second for the same lifetimes.
A block list pushed to every node fixed this without short tokens. With a 900 second token, a push delay of 0 seconds let none through, 1 second let 5, 10 seconds let 38, 60 seconds let 251 and 300 seconds let 1,075.
Short tokens trade leaks for refresh load.
A fast block list closes the gap that a long token leaves.
Choose a token life of a few minutes to an hour, add a block list that reaches every node in seconds, and remember verified tokens until they expire. Rotate signing keys by publishing the new key before using it, and keep the old key until its tokens are gone.
6. Combining Calls (Aggregation)
A stop screen needs arrivals, vehicle positions, alerts and fares. Calling four services from the phone over a mobile network costs four round trips. A gateway endpoint can call them inside the data centre and reply once. The risk is tail latency: a request that waits for four calls is slow whenever any of them is slow.
The second program calls the four services with typical latencies of 30, 40, 25 and 35 ms. 2% of calls are slow (400 to 599 ms longer). Only arrivals are essential, with a 400 ms timeout; the other three have 120 ms timeouts and may be left out.
Output
One BusTrack stop screen needs four upstream calls: arrivals (about 30 ms), positions (40), alerts (25), fares (35).
2% of calls are slow (+400 to +599 ms). 20000 screens per run. Only arrivals are essential; the other three are optional.
all services healthy
screens with at least one slow call: 7.7%
strategy p50 p95 p99 complete no arrivals (error)
one after another 163 ms 638 ms 741 ms 100.0% 0.0%
all at once, wait for every call 51 ms 516 ms 615 ms 100.0% 0.0%
all at once, timeouts + partial answer 51 ms 120 ms 400 ms 92.2% 1.9%
alerts service degraded (40% of its calls are slow)
screens with at least one slow call: 43.6%
strategy p50 p95 p99 complete no arrivals (error)
one after another 174 ms 750 ms 1178 ms 100.0% 0.0%
all at once, wait for every call 58 ms 611 ms 629 ms 100.0% 0.0%
all at once, timeouts + partial answer 58 ms 120 ms 400 ms 56.3% 1.9%
With each call slow only 2% of the time, 7.7% of screens contained at least one slow call.
Calling one after another gave a p50 of 163 ms and a p99 of 741 ms. Calling all four at once and waiting for every answer gave a p50 of 51 ms and a p99 of 615 ms.
Adding the timeouts and accepting a partial answer gave a p50 of 51 ms and a p99 of 400 ms. 92.2% of screens were complete and 1.9% had no arrivals at all (an error).
With the alerts service degraded (40% of its calls slow), 43.6% of screens had a slow call. Waiting for everything gave a p99 of 629 ms, while timeouts held it at 400 ms with 56.3% of screens complete.
Parallel calls and timeouts bound the tail.
Decide for each part whether it is essential or optional, set a timeout per part, return what you have and say what is missing. Do not hide the gaps: the app can retry the missing parts or show a message.
7. Caching and the Stampede
The gateway can answer repeated requests from memory. For GET /v1/stops/{id}/arrivals a slightly old answer is fine, so we cache it for 5 seconds. A popular key creates a risk: when its entry expires, every request that arrives while the refresh is in flight misses and calls the service. This is a cache stampede.
The third program sends 2,000 requests per second for 100 seconds over 2,000 stops (a few much more popular than others). A backend call takes 50 ms. From second 40 to 50 a match ends and 40% of requests ask about one stadium stop. It compares four policies; the last serves an expired copy for up to 10 seconds while one call refreshes it (the idea behind stale-while-revalidate, RFC 5861).
Output
GET /v1/stops/{id}/arrivals: 2000 requests/s for 100 s over 2000 stops, a few of them very popular. A backend call takes 50 ms.
From second 40 to 50 a match ends and 40% of all requests ask about one stadium stop.
Arrival data may be at most 5 s old (TTL 5 s). The last policy may also serve an expired copy for up to 10 s while one call refreshes it.
policy backend calls calls served average wait most calls, one key, oldest data served
from cache in one 50 ms window
no cache 200000 100 per 100 0.0% 50.0 ms 51 0.0 s
cache with a TTL 29767 14 per 100 85.1% 7.4 ms 22 4.9 s
TTL cache + one call per key 28101 14 per 100 85.1% 7.2 ms 1 4.9 s
TTL + one call per key + serve stale 28101 14 per 100 98.5% 0.7 ms 1 14.9 s
With no cache every request called the service (200,000 calls) and the stadium stop saw 51 calls in one 50 ms window.
A cache with a TTL cut calls to 29,767 (14 per 100 requests, 85.1% served from cache) but the stadium stop still saw 22 simultaneous calls when its entry expired.
Letting requests join a call that is already in flight kept it to 1, and 28,101 calls overall.
Serving the stale copy while refreshing served 98.5% of requests from cache and cut the average wait from 7.2 ms to 0.7 ms. The price is age: the oldest data served was 14.9 seconds, against 4.9 seconds.
One refresh at a time, and no one waits for it.
Cache only responses that are safe to share (not per-rider data), put a ceiling on staleness that the product accepts, and set Cache-Control so clients and CDNs cooperate (RFC 9111).
8. The Circuit Breaker
If a service fails by hanging, every request to it ties up a worker for the whole timeout and then errors, and the failing service keeps receiving load that stops it recovering. A circuit breaker watches recent calls. When too many fail it opens and answers at once without calling. After a pause it goes half open and lets a few trial calls through. If they succeed it closes.
Closed, open, half open, closed.
The fourth program has the ticket service fail at second 20: each call hangs 1,000 ms and then errors. It is restarted at second 80, but a cold service only recovers after 10 seconds in a row with 50 requests per second or less (an assumption about warm-up). The gateway sends 200 requests per second for 200 seconds. The breaker opens when half of the last 20 calls fail.
Output
The ticket service fails at second 20 (calls hang 1000 ms, then error) and is restarted at second 80.
It needs 10 quiet seconds (50 requests/s or less) to warm up. The gateway sends 200 requests/s for 200 s.
setup success slow errors fast errors calls to the normal again average time per request
failing service after the restart
no breaker 10.0% 36000 0 36000 never 904.0 ms
breaker, open 2 s 65.0% 44 13956 44 10 s 27.4 ms
breaker, open 10 s 65.0% 16 13984 16 10 s 26.7 ms
breaker, open 30 s 55.0% 12 17988 12 30 s 22.7 ms
With no breaker, only the first 20 seconds succeeded (10.0%), all 36,000 later calls were slow errors, and the service never recovered because the load never dropped. The average time per request was 904 ms.
With a breaker that stayed open for 2 seconds, 65.0% succeeded, only 44 calls reached the failing service, the average time was 27.4 ms and traffic was normal again 10 seconds after the restart.
Staying open for 10 seconds behaved the same (65.0%, 10 seconds).
Staying open for 30 seconds noticed the recovery late: traffic was normal 30 seconds after the restart and only 55.0% of requests succeeded.
A short open period recovers quickly, at the cost of a few probe calls. Choose the fallback with care: a cached or default answer is better than an error, but only if it is not misleading (for example, do not show old ticket prices as current).
9. Bulkheads: Keeping One Slow Service from Taking the Rest Down
A gateway node has a limited number of workers. A worker that calls a slow service stays busy for the whole call. If all routes share one pool, a slow service eventually holds all the workers and healthy routes wait for none. A bulkhead reserves workers per service so one cannot use more than its share.
The fifth program has 100 workers and three routes: trips 400 requests per second, stops 400 and tickets 200. From second 20 to 50 the ticket service takes 3,000 ms per call. A request that would wait more than 500 ms for a worker is refused. It compares one shared pool, partitions of 40, 40 and 20, and a shared pool in which tickets may use at most 20 workers.
Output
A gateway with 100 workers serves three routes: trips 400/s, stops 400/s, tickets 200/s. Healthy calls hold a worker 30-40 ms.
From second 20 to 50 the ticket service takes 3000 ms per call. A request that would wait more than 500 ms for a worker is refused.
worker setup phase trips + stops served their average wait tickets served
shared pool of 100 before (0-20 s) 100.0% 0.0 ms 100.0%
during (20-50 s) 25.2% 467.7 ms 16.4%
after (50-60 s) 93.6% 66.7 ms 92.5%
partitions 40 / 40 / 20 before (0-20 s) 100.0% 0.0 ms 100.0%
during (20-50 s) 100.0% 0.0 ms 3.6%
after (50-60 s) 100.0% 0.0 ms 74.6%
shared 100, tickets capped at 20 before (0-20 s) 100.0% 0.0 ms 100.0%
during (20-50 s) 100.0% 0.0 ms 3.6%
after (50-60 s) 100.0% 2.1 ms 74.6%
Before the incident everything was served in all three setups.
During the incident the shared pool served only 25.2% of trips and stops, with an average wait of 467.7 ms. It served 16.4% of tickets.
Both bulkhead setups served 100.0% of trips and stops with no wait. Tickets fell to 3.6%, which is the honest cost: the failing service gets only the capacity it has been given.
After the incident the shared pool needed time to drain (93.6% for trips and stops) while the bulkheads stayed at 100.0%.
Isolation turns a total outage into a partial one.
The capped shared pool matched the partitions here. In principle it wastes less when everything is healthy, because idle workers can serve any route, but we did not measure that. Combine bulkheads with the breaker above: the breaker stops calling, the bulkhead limits the harm until it does.
10. Releasing a New Version Safely
Because every request passes through the gateway, it is a natural place to split traffic between versions. A staged (canary) rollout sends 1%, then 5%, 25% and 100% of traffic to the new version, checking after each step. An automatic check that compares failure rates can roll back without waiting for a person.
The sixth program ships trips v2 at minute 10 to 20,000 riders sending 2,000 requests a minute. The check rolls back when v2 has handled at least 200 requests in the last 5 minutes and 1.5% or more failed. v1 fails 0.1% of requests. It tries a bug that fails 20% of requests, 3%, and 0.8% (below the check). It also compares sending each request to a random version with a sticky assignment, where a rider always has the same version.
Output
BusTrack ships trips v2 at minute 10. 20000 riders send 2000 requests a minute for 60 minutes. v1 fails 0.1% of requests.
The automatic check rolls back when v2 has 200 requests in the last 5 minutes and 1.5% or more failed.
v2 fails 20% of its requests
rollout rolled back v2 requests failed on v2 riders who hit a failure riders who saw both versions
all at once, noticed by a person minute 26 32000 6401 5511 15786
all at once, automatic check minute 11 2000 375 372 1895
staged, random per request minute 22 380 76 76 377
staged, sticky per rider minute 22 386 88 81 279
v2 fails 3% of its requests
rollout rolled back v2 requests failed on v2 riders who hit a failure riders who saw both versions
all at once, noticed by a person never 100000 2935 2751 12566
all at once, automatic check minute 11 2000 59 59 1895
staged, random per request minute 22 380 14 14 377
staged, sticky per rider minute 22 386 14 14 279
v2 fails 0.8% of its requests (below the check)
rollout rolled back v2 requests failed on v2 riders who hit a failure riders who saw both versions
all at once, noticed by a person never 100000 793 774 12566
all at once, automatic check never 100000 793 774 12566
staged, random per request never 46129 380 374 17536
staged, sticky per rider minute 22 386 6 6 279
For a 20% bug, shipping to everyone and waiting for a person to notice took until minute 26 and 6,401 failed requests (5,511 riders hit a failure). An automatic check with all traffic moved at once rolled back at minute 11 with 375. A staged rollout rolled back at minute 22 with 76 (random) or 88 (sticky).
For a 3% bug a person never noticed (2,935 failed requests). The automatic check at once cost 59, and the staged rollout only 14.
A 0.8% bug stayed below the check. Everyone who got v2 saw it: 793 failures with an all-at-once release. The staged random run never rolled back either. The sticky run rolled back at minute 22, but only by chance, because a handful of failures happened to cross the 1.5% line: do not count on that.
In the 20% run, riders who saw both versions: 15,786 when a person rolled back late, 1,895 with an immediate rollback, 377 staged at random and 279 staged and sticky. Flip-flopping between versions confuses users, and sticky assignment reduces it.
Small steps, an automatic check, and a threshold you can defend.
A small canary only tells you something if it gets enough traffic. At 1% of 2,000 requests a minute a canary sees 20 requests a minute, so the first stage cannot satisfy a check that needs 200 requests until it has run for 10 minutes. Size the stages and the check together.
11. What Belongs in a Gateway?
Put what is the same for every service in the gateway.
| Concern | Gateway | Service |
|---|---|---|
| Authentication and blocking | Yes, once at the edge | Reads the rider id; checks permissions |
| Rate limiting | Yes, per caller and route | Protects its own expensive actions |
| Routing and versioning | Yes | No |
| Combining calls for a screen | Yes, when it is only joining data | Business logic stays here |
| Caching | Public, safe responses | Its own caches |
| Breakers and bulkheads | Toward each service | Toward its own dependencies |
A gateway that grows business rules becomes a bottleneck that every team must change. Keep it to concerns that are the same for every service. A service mesh (sidecar proxies between services) covers service-to-service traffic with similar tools; the gateway covers traffic from outside.
12. Trade-offs to Mention
A central gateway is one place to enforce rules, and also a place where a bug affects everything. Keep it small, stateless and heavily tested.
Short tokens are simple and a block list is fast, but a block list is state that must reach every node.
Aggregation saves phone round trips and adds a dependency on every part. Mark parts optional.
Serving stale data keeps latency low and breaks freshness. Put a number on the staleness you accept.
Bulkheads waste some capacity in exchange for isolation.
Canaries trade release speed for safety, and small canaries trade evidence for risk.
13. Common Mistakes
Verifying a signature on every request when it can be remembered until the token expires.
Relying on token expiry alone to remove access.
Waiting for every upstream call, with no timeouts and no partial responses.
Caching without protection against a stampede on a hot key.
Sharing one worker pool between routes with very different latencies.
Putting business rules in the gateway.
Releasing to everyone at once and relying on a person to notice.
14. Interview Questions
Why authenticate at the gateway? It checks once for every service and keeps bad requests away from them. Services still check permissions.
How do you revoke access quickly with JWTs? Combine short tokens with a block list pushed to all nodes, and measure how many requests leak while it propagates.
How do you stop a slow service from taking the gateway down? Timeouts, a circuit breaker and a bulkhead (a separate pool) for each service.
What is a cache stampede and how do you prevent it? Many requests refresh an expired hot key at once. Let one request refresh it, make others wait or serve a stale copy.
How would you release a risky change? Staged rollout with sticky assignment and an automatic check sized to the traffic each stage receives.
Summary
The gateway runs one ordered pipeline: limits, authentication, rate limiting, routing, caching, breakers and bulkheads.
Verify tokens once, push block lists fast, and keep token lifetimes moderate.
Call services in parallel with timeouts and return partial answers.
Coalesce cache refreshes and serve stale data within a stated limit.
Isolate services with breakers and bulkheads.
Release gradually with an automatic check that has enough traffic to judge.
Conclusion
An API gateway earns its place by making the common work cheap and the bad days survivable. The design above does that by doing each job once at the edge, bounding every wait, and limiting how far any one failure can spread. In an interview, name each job, say what it costs, and say how it fails.
Previous topic: Design Load Balancer. Next topic: Design Key-Value Store.
References and further reading
Design Load Balancer for health checks, retry budgets and safe configuration changes.