API Gateways and API Management Questions
The API gateway as a component and the API program it enforces: routing and aggregation, a policy chain for authentication hand-off, throttling hooks, request validation and transformation, protocol translation, telemetry, TLS termination, failure isolation, scaling, multi-region placement, response caching with stampede protection, tenant-aware routing and isolation, traffic steering by version or experiment cohort, and safe policy rollout and testing, plus gateway versus service mesh versus BFF placement of cross-cutting concerns. Also the management surface around it: key and credential provisioning with approval, plan and tier enforcement, separating public from partner audiences, usage analytics, and central policy governance. Excludes throttling algorithms and distributed counters, OAuth/JWT mechanics, load-balancer algorithms, documentation and developer-portal content, and whole-API-surface design.
A company runs one centralized API gateway for all clients. Compare keeping it with moving to Backend-For-Frontend services or client SDKs. Discuss governance, latency, delivery speed, deployment independence and security, and propose a migration path if you decide to modularize.
Sample Answer
The idea in plain words
A BFF (backend for frontend) is a small server owned by one client team that sits between that client (web, mobile, partner) and the shared backend services, and shapes data for exactly that client: it combines several service calls into one and returns only the fields the screen needs. A client SDK (software development kit, a library that wraps the API for developers) makes calling the API easier but runs on the client's device. My recommendation: keep a thin central gateway for what must be uniform (TLS, authentication, coarse throttling, telemetry), and move client-specific aggregation and response shaping into BFFs owned by the client teams. SDKs are a convenience for developers, never a place to enforce anything. Three terms used below: a release train is a fixed schedule on which many teams' changes ship together, so a change waits for the next departure; a composition endpoint is a route that calls several services and merges their answers into one response; deployables are the separately built and run units of the system.
The comparison
| Dimension | One central gateway doing everything | Thin gateway plus BFFs | Client SDKs |
|---|---|---|---|
| Governance | Strong, one place to audit; but one team reviews every client's change | Shared standards at the edge, client logic owned by client teams; needs templates and lint (an automated check that configuration or specs follow agreed naming and shape rules) to keep BFFs consistent | Weak: logic ships inside apps that cannot be updated at will |
| Latency | One hop; but clients make several round trips (each a request and its response across the network) to assemble a screen | One extra internal hop, fewer client round trips | Fewer lines of client code, same number of network calls unless the SDK merges them |
| Delivery speed | Queue for the gateway team | Client team changes its BFF without waiting | Fast to write, slow to fix once an app version is in users' hands |
| Deployment independence | Low: one release train | High per client; the cost is more deployables | Tied to app store release cycles |
| Security | One enforcement point; the larger the logic in it, the larger the shared risk | Authentication at the edge, authorization in services; each BFF is more surface to patch | Secrets or rules in a client can be extracted; the server must still enforce everything |
Counting deployables, with an assumption of three client types (web, mobile, partner): the central model has 1 component; the modular model has 1 gateway + 3 BFFs = 4 components to build, run and patch. The price is real: more things to monitor, and the risk that each BFF reimplements auth differently unless the gateway still does it.
Worked latency example (all inputs are assumptions)
A mobile screen needs data from 4 independent services. Network round trip between phone and edge: 80 ms. Each service answers in 10 ms. A BFF-to-service call adds nothing beyond that 10 ms, and the extra BFF hop costs 2 ms. Three ways to build the screen:
- Client calls the services one after another through the gateway (for example because the SDK or app code awaits each call before the next): 4 x (80 + 10) = 4 x 90 = 360 ms.
- Client sends all four calls at once through the gateway: 80 + 10 = 90 ms, because the calls overlap and the slowest takes 10 ms.
- Client makes one call to a mobile BFF, which calls the four services in parallel: 80 + 2 + 10 = 92 ms.
So against a sequential client the BFF saves 360 - 92 = 268 ms, and the saving comes from removing client round trips on a slow network, not from the BFF being faster. Against a client that already issues the four calls in parallel, the BFF is 2 ms slower: latency alone does not justify it. What it still buys is one request instead of four on a weak radio connection (each extra request costs battery and can fail on its own), a response with only the needed fields, one place to merge partial failures, and a release schedule owned by the client team. If the screen only needs one service, a BFF would add 2 ms and buy nothing. That is when to leave it out.
Decision and what would flip it
One related option: GraphQL is a query language and server layer where the client sends a query naming exactly the fields it wants from a single endpoint, and the server assembles just those. A BFF gives each client hand-written endpoints shaped for it; GraphQL lets every client shape its own response from one schema, at the cost of a server that must resolve arbitrary queries and limit their cost. Both address the same problem of clients needing different data.
Decide by evidence in the current gateway: how many routes exist only to reshape data for one client, how often a client team waits on gateway releases (for example a measured median wait for a route change), and whether client screens need many calls. If clients are similar and changes are rare, keep the central gateway and add a lightweight composition endpoint where needed. If three client teams are blocked weekly by one gateway queue, modularize. Do not adopt SDKs as a replacement for either: they cannot enforce authentication, limits or validation because the caller controls them.
Migration path if you modularize (strangler pattern: move traffic piece by piece)
- Inventory every gateway route: which client calls it, what logic it contains, who changes it. Classify each as shared policy (stays), client-specific shaping (moves to a BFF) or business logic (moves to a service).
- Slim the gateway to the shared chain first, so a BFF behind it does not need to re-implement TLS or token checks.
- Build one BFF for the client with the clearest pain (mobile in the example), behind the gateway, using a template that includes logging, request ID propagation and a standard auth hand-off.
- Shift traffic gradually: 5 percent, 25 percent, 50 percent, 100 percent of the mobile calls, comparing error rate and latency at each step. Keep the old route live for instant rollback until the last step is stable.
- Delete the old gateway routes, then repeat for the next client.
- Governance: a shared BFF template, an API style lint, an agreed set of metrics, and a short review for security-relevant changes.
Common mistakes
- Making a BFF per team instead of per client experience, which fragments the API.
- Letting BFFs hold business rules, which then diverge between clients.
- Moving authentication into each BFF or SDK, so a mistake appears three times.
- Calling services in sequence inside the BFF when they could run in parallel, and losing the latency benefit.
A gateway must authenticate callers, apply per-client limits and emit usage analytics at 50k requests per second with about 100k registered clients and under 5ms of added median latency. Size the design: which components sit on the hot path, how credential and limit state is cached or shared across gateway nodes, how the analytics pipeline stays off the request path, and how you scale horizontally.
Sample Answer
The idea in plain words
The gateway's job on the hot path (the code that runs on every request) is small: terminate the connection, identify the caller, check that caller's limit, forward the request. The insight that makes 50,000 requests per second and a median of under 5 ms achievable is that nothing on that path may wait on a remote system in the common case. Credentials and limit settings are copied into each gateway node's memory ahead of time, limit counting is done locally and reconciled in the background, and usage analytics is written to an in-memory buffer and shipped later. Anything slower than a memory read is moved off the request path.
Assumptions (labelled as such, not facts about any product): 50,000 requests per second at peak, 100,000 registered clients, an average of 300 bytes per analytics event, one gateway node can handle 8,000 requests per second at its limit and is planned at 60 percent of that.
Step 1: What sits on the hot path, in order
- Connection handling and TLS (transport encryption). TLS termination means the gateway decrypts the traffic. Clients reuse connections (HTTP keep-alive, where one connection carries many requests one after another), so the handshake cost is paid rarely, not per request.
- Parse and route: match host, method and path to a route. A lookup in an in-memory table.
- Authenticate: look up the API key, or verify a signed token, in the local cache. Verifying a signature with a locally held public key needs no network call.
- Limit check: read and decrement the caller's counter in local memory.
- Forward to the upstream service over a pooled, already-open connection.
- On response: append one analytics event to an in-memory buffer and return.
Step 2: Latency budget by hand
These per-step costs are assumptions to be replaced by measurement in the real system. The table covers only the gateway's own work; TLS handshakes (rare, because connections are reused) and the upstream service's own processing time are not in it, and the 5 ms budget is for what the gateway adds.
| Step | Assumed median cost (ms) |
|---|---|
| Network hop from load balancer to gateway | 0.30 |
| Parse and route | 0.30 |
| Key lookup in local memory | 0.05 |
| Local limit check | 0.05 |
| Header policies and proxy copy overhead | 0.90 |
| Analytics append to buffer | 0.00 (nanoseconds, rounded) |
Sum: 0.30 + 0.30 + 0.05 + 0.05 + 0.90 = 1.60 ms, leaving 3.4 ms of the 5 ms budget. Now compare with calling a shared store (for example a remote cache) on every request for the credential and the counter. Assume each call takes 0.5 ms in the same data centre, two calls: 1.60 + 1.00 = 2.60 ms. That still fits a median of 5 ms, but the cost is not the median. A remote call on the hot path adds its tail latency to every request (tail latency is how slow the slowest requests are, and p99 is the time that 99 percent of requests beat, so p99 = 20 ms means 1 request in 100 takes longer than 20 ms; a request that makes two remote calls has two chances to land in that tail), and makes the shared store a dependency whose outage fails every request. That is why the local path is the default.
Step 3: How credential state is cached and shared
100,000 clients, with an assumed 200 bytes per record (hashed key, client ID, plan ID, status, limit settings): 100,000 x 200 = 20,000,000 bytes, about 20 MB. That fits comfortably in every node, so every node holds the full table. No sharding is needed.
Keep it fresh without a database call per request:
- Load the full table at start-up from the management store.
- Receive changes by push or by short polling of a version number (for example every 5 seconds). Revoking a key then takes effect within the polling interval; state this as the revocation delay and decide whether it is acceptable (for a compromised key, push an urgent revoke event).
- Store only a hash of each key, never the key itself, and compare hashes.
- Negative caching (remembering that a key does not exist): a few thousand unknown keys per second from an attacker should be rejected from a small "unknown" cache, not trigger a lookup.
Step 4: How limit state is shared
This step is about where the counter lives, whichever counting algorithm the limiter uses. Three placements:
- Central counter: every request does one atomic increment (an add that no other writer can interleave with, so two simultaneous requests never both read the same old value) in a shared store. Exact, but 50,000 operations per second and a dependency on the hot path.
- Sticky routing: the load balancer hashes the client ID (turns it into a number that picks a node) so one node sees all of that client's requests and counts locally. Exact and local, but a very busy client cannot spread over nodes, and a node loss resets the counters of its clients.
- Local share with background reconciliation (periodically comparing what each node saw and correcting the numbers): with N nodes, each node enforces about limit / N and every second reports its counts to the shared store, which adjusts each node's share.
Recommendation: option 3 for ordinary clients and a central check only for the few clients whose limits are contractual and low. Cost of option 3: the limit is approximate. Example: limit 100 requests per second, 10 nodes, so a share of 10 each. If a client's requests land evenly it is exact. If they all land on 2 nodes, only 20 per second are admitted, a wrongful rejection of 80 percent, until the next reconciliation moves share to those nodes. State to the product owner which error is acceptable.
The reconciliation rule used below is an illustrative choice: each node reports the requests it saw (admitted plus rejected), and the store gives every node a floor of 2 per second so no node is ever shut out, then splits the remaining 100 - 10 x 2 = 80 in proportion to reported demand. A node with 50 of the 100 requests gets 2 + 80 x 50 / 100 = 42. The new shares apply from the next second. The second half of the program is a separate scenario that shows the opposite error, over-admission. The first half has no burst allowance, so its rejections come from the shares alone. In the second half the shares are not being moved; instead each node holds a bucket of 10 spare tokens (a burst allowance) that starts full and refills 10 per second, so the most one client can get in a single second in that model is the sum of the shares plus every node's burst. A limiter that has both moving shares and buckets would admit somewhat more than the first half shows; each half is read on its own.
LIMIT, NODES, FLOOR = 100, 10, 2
def reconcile(demand):
# shared store: every node keeps FLOOR, the rest follows observed demand
spare = LIMIT - FLOOR * NODES
total = sum(demand)
if total == 0:
return [LIMIT // NODES] * NODES
return [FLOOR + spare * d // total for d in demand]
# shares only, no burst bucket: a client sends 100 requests per second; where they land changes at second 3
landing = {
1: {0: 50, 1: 50},
2: {0: 50, 1: 50},
3: {2: 50, 3: 50},
4: {2: 50, 3: 50},
}
shares = [LIMIT // NODES] * NODES
print("under-admission: admitted per second, shares used that second")
for t, where in landing.items():
demand = [where.get(n, 0) for n in range(NODES)]
admitted = sum(min(d, s) for d, s in zip(demand, shares))
print(f"t={t} admitted={admitted} rejected={100 - admitted} shares={shares}")
shares = reconcile(demand)
# over-admission, separate scenario: each node holds a bucket of 10 tokens that starts full
print("over-admission: client sends 20 per node per second on all 10 nodes")
tokens = [10] * NODES
for t in (1, 2):
admitted = 0
for n in range(NODES):
can = tokens[n] + 10 # stored burst plus one second of refill
take = min(20, can)
tokens[n] = min(10, can - take)
admitted += take
print(f"t={t} admitted={admitted}")
Output:
under-admission: admitted per second, shares used that second
t=1 admitted=20 rejected=80 shares=[10, 10, 10, 10, 10, 10, 10, 10, 10, 10]
t=2 admitted=84 rejected=16 shares=[42, 42, 2, 2, 2, 2, 2, 2, 2, 2]
t=3 admitted=4 rejected=96 shares=[42, 42, 2, 2, 2, 2, 2, 2, 2, 2]
t=4 admitted=84 rejected=16 shares=[2, 2, 42, 42, 2, 2, 2, 2, 2, 2]
over-admission: client sends 20 per node per second on all 10 nodes
t=1 admitted=200
t=2 admitted=100
Read it as a timeline. At t=1 the client's traffic lands on nodes 0 and 1 whose shares are 10 each, so 20 of 100 requests pass. The report at the end of t=1 moves the shares to 42, 42 and 2 for the rest, so t=2 admits 42 + 42 = 84 and rejects 16, the remaining error caused by the floor. At t=3 the client's traffic moves to nodes 2 and 3 whose shares are only 2 each, so 4 pass until the next report, and by t=4 the shares have followed the traffic. A shorter reconciliation interval shortens these bad seconds but raises the load on the shared store. On the other side, a client that has been idle and then sends 20 requests per node on all 10 nodes gets 10 + 10 = 20 per node, 200 in that first second, twice its limit, and 100 in the second after that once the bursts are spent. In the shares-only model, after a report, the under-admission that remains is bounded by the floor (here 8 idle nodes x 2 = 16 of 100 rejected), a shift of traffic costs rejections for about one reconciliation interval (the 96 rejected at t=3), and, in the bucket model, over-admission is bounded by the burst allowance (here 100 extra requests, once). The floor, the burst size and the reconciliation interval are settings you choose.
Step 5: Keeping analytics off the request path
Event volume: 50,000 per second x 300 bytes = 15,000,000 bytes per second, which is 15 MB/s. Network links are quoted in bits, and 1 byte is 8 bits, so 15 MB/s x 8 = 120 megabits per second. Over a day, 15 MB/s x 86,400 s = 1,296,000 MB, about 1.3 TB of raw events.
Design:
- Each request appends a small event to a bounded in-memory ring buffer (a fixed-size queue that overwrites or drops when full). The request never waits.
- A background thread on each node flushes every second or every 1,000 events, whichever is first, to a durable queue (a queue that stores messages on disk or replicas, so they survive a restart of the consumer or the queue).
- A stream processor (a program that reads events continuously as they arrive and keeps running totals) aggregates by (client, route, status class, minute) and writes a few rows instead of millions. Dashboards and debugging read these rows.
- Raw events are kept for a short window for debugging, sampled if needed.
- If the queue is down, the buffer fills and the node drops raw events and counts the drops in a metric. Dropping raw events is acceptable; slowing requests is not.
- Billing and quotas must not depend on raw events that can be dropped. Each node also keeps small in-memory counters per (client, route, status class, minute), a few thousand rows rather than millions of events, and keeps retrying their flush (spilling to local disk if needed), so a queue outage delays the billing numbers instead of losing them. A node that crashes loses at most its last unflushed minute, which is the stated error bound for billing.
Step 6: Horizontal scaling
Planned capacity per node: 8,000 x 0.60 = 4,800 requests per second. 50,000 / 4,800 = 10.4, so 11 nodes; add one spare, giving 12 nodes. Steady load per node: 50,000 / 12 = 4,167 (52 percent of the limit). With one node lost: 50,000 / 11 = 4,545 (57 percent). Nodes are stateless apart from the memory caches, sit behind a layer 4 load balancer (it spreads TCP connections without reading the HTTP inside them) or DNS, and scale out on CPU or connections per node. Because HTTP/2 connections are long-lived, a balancer chooses a node only when a connection is opened. A new node added at peak receives nothing until clients open new connections, while the old nodes keep serving their existing ones, so scale-out should be ahead of the peak, not during it.
Per node, analytics is 50,000 / 12 = 4,167 events per second, so a 1-second flush carries about 4,167 events, roughly 1.25 MB.
What the answer to each ask is
- Hot-path components: connection and TLS, routing, local credential lookup, local limit check, proxy, buffer append.
- Credential and limit state: full copy in each node's memory, refreshed by push or polling; limits counted locally with background reconciliation.
- Analytics: buffer, batch, queue, aggregate, never inline; billing counts come from per-node counters that are retried, not from droppable raw events.
- Horizontal scale: 12 stateless nodes at about 52 percent load, 57 percent after losing one.
Common mistakes
- Looking up the key in a database per request.
- Writing an analytics row synchronously.
- Counting limits in a shared store without asking what happens when that store is slow.
- Quoting average latency; the median (the middle request) hides the tail, so also track p99.
Judgment
I would ship the local design and measure two things first: the revocation delay and the tail latency at p99. If the business needs exact global limits for a small set of clients, I would add central checks only for those routes, and that would be the change that flips the design for them.
What is an API gateway, and why would you put one in front of a set of services? How does it differ from a plain reverse proxy or a load balancer, what are the costs of adding one, and when is it premature?
Sample Answer
The idea in plain words
An API (application programming interface) is the set of requests a program can send to a service. A gateway is one server that sits in front of many services and is the single address clients call. It is a reverse proxy (a server that receives requests on behalf of other servers and forwards them) that also applies rules to each request: who is calling, whether they are allowed, how fast they may call, where the request goes, and what gets recorded. The point is to do these shared jobs once, at the edge, instead of re-implementing them in every service.
What it does that a reverse proxy or load balancer does not
| Component | Core job | Looks at | Typical decisions |
|---|---|---|---|
| Load balancer | Spread connections or requests across identical copies of one service | Addresses and ports (layer 4, the connection level: which machine is talking to which), sometimes the URL (layer 7, the request level: what is being asked for) | Which healthy copy gets this request |
| Reverse proxy | Receive requests for a site and forward them to servers behind it; often adds TLS termination (decrypting HTTPS at the proxy) and caching | Host, path, headers | Which backend pool gets this request |
| API gateway | A reverse proxy plus an API-aware policy chain (an ordered list of checks and transformations run on each request) | Credentials, API keys, consumer identity (which client application or customer is calling), route, request body shape | Is this caller known, allowed, within its limit, sending a valid request; which service; what to log |
The three overlap: a gateway usually contains a load balancer for each upstream pool and is built on a reverse proxy. The difference is the unit of decision. A load balancer thinks in servers, a gateway thinks in consumers and routes. Two security words matter below: authentication is proving who the caller is, and authorization is deciding what that caller may do. A gateway can authenticate every caller the same way for all services, but what a caller may do to a particular order or account depends on that service's data.
Why put one in front of services
- Single entry point. Clients know one hostname. Services can be split, merged or moved behind it without clients changing.
- Shared policy in one place: authentication hand-off (checking a token or key and passing the verified identity on), rate limiting, request validation, TLS termination, response caching, and telemetry (logs, metrics, request IDs).
- Routing and light translation: send /v1/orders to the orders service, /v1/users to the users service, rewrite paths, translate between protocols where needed.
- Insulation: services can sit on a private network and only the gateway is reachable from outside.
Worked example with stated assumptions
Assume three services (orders, users, catalog) built by three teams, each currently exposed directly. Each team has written its own token check, and two of them differ in how they treat an expired token.
- Before: 3 public endpoints, 3 TLS certificates to renew, 3 token-check implementations, 3 places where rate limits could be applied.
- After: 1 public endpoint, 1 certificate on the gateway, 1 token check, 1 place for limits and a shared request ID in every log line.
What it costs, with assumptions labelled. Suppose the gateway adds 2 ms per request (assumption, it varies with hardware and policy count) and the gateway is available 99.95 percent of the time while the service is available 99.9 percent. Availability in series multiplies:
- Combined availability: 0.9995 x 0.9990 = 0.9985005, about 99.85 percent. Two boxes in series multiply rather than average because a request succeeds only if the gateway is up and the service is up. If their outages are independent, the fraction of time both are up is the product of the two fractions; averaging would hide that a failure of either box fails the request, and a chain can never be more available than its weakest link.
- Over a 30-day month of 43,200 minutes: service alone is down 43,200 x 0.001 = 43.2 minutes. Gateway alone is down 43,200 x 0.0005 = 21.6 minutes. Together 43,200 x (1 - 0.9985005) = 64.78 minutes, which is the sum of the two, rounded.
So the gateway is a new component that can fail and that you must run at higher availability than any single service behind it, because every service inherits its downtime.
Costs
- An extra network hop and extra latency on every request.
- A new single point of failure (one component whose failure stops everything behind it) unless it is run as several stateless copies (identical instances that keep no per-user state, so any one can serve any request) across failure zones (separate data centres or racks that do not share power or network, so one failing does not take the others down).
- Operating cost: certificates, config rollout, upgrades, capacity planning, an on-call rotation.
- Change bottleneck: if every team must ask the gateway team to change a route, delivery slows.
- Logic creep: business rules leak into it and it becomes a shared codebase nobody owns.
When it is premature
- One service and one client: a reverse proxy or the framework's own middleware (functions that run on each request before the handler) already covers TLS and auth.
- A small team that deploys everything together: shared policy is a library call, not a network component.
- No consumers outside your control yet: keys (secrets that identify a consumer), plans (tiers such as free and paid) and quotas (caps such as 10,000 requests a month) have nobody to apply to.
Signals that it is time: several services each reimplementing authentication or limits, external consumers needing keys and quotas, a need to hide internal topology, or an auditor asking for one place to see who called what.
Common mistakes
- Treating the gateway as a bigger load balancer and ignoring identity-aware policy.
- Adding it without budgeting its availability, so it becomes the weakest link.
- Putting service-specific business logic in it because it is convenient.
- Skipping a per-service authorization check because the gateway already authenticated the caller. Knowing who is calling does not tell the service whether this caller may refund this particular order.
An enterprise exposes both public and partner APIs through its gateway layer. How do you separate the two audiences, where does each concern sit (identity hand-off, request validation, TLS termination, observability), and how do you support different service levels and paid tiers through keys and plans?
Sample Answer
The idea in plain words
Public APIs are used by anyone who signs up; partner APIs are used by organisations you have a contract with. They differ in who the callers are, how strongly you authenticate them, what they are promised, and what damage a mistake does. The gateway layer separates the two audiences so each has its own entry point, policies and capacity, while sharing the same code and the same management data. API management is the layer around the gateway that handles keys, plans and tiers: a key identifies a client, the client belongs to a plan, and the plan says what the client may do and how much. The insight: put the commercial rules (limits, quotas, features) in the plan, not in the key and not in the services.
Step 1: Separate the audiences
| Aspect | Public | Partner |
|---|---|---|
| Entry point | api.example.com | partners.example.com (separate hostname) |
| Deployment | Own gateway pool, own scaling | Own gateway pool, so a public flood cannot reach partner capacity |
| Authentication | API key plus user token (OAuth, a standard in which a user lets an app act for them and the app presents a token) | Mutual TLS (both sides present certificates) plus client-credentials token (a token an organisation's server obtains for itself with its own secret, with no user involved) |
| Validation | Strict size limits, public schema | Contract-specific schemas, agreed sizes |
| TLS termination (the device that decrypts HTTPS) | At the CDN or edge | At the gateway, so the client certificate is validated there |
| Limits | Per key, conservative | Per partner, negotiated |
| Observability | Dashboards by plan | Dashboards and reports by partner, with their own SLO (target for success and latency) |
Both pools run the same gateway software and policy library from one repository; they differ in configuration. That keeps one place to fix a bug and two blast radii (the blast radius is how much a failure or flood can reach: a public flood now exhausts only the public pool). Where TLS ends decides who can check a client certificate, because the certificate is presented during the handshake with whichever device holds the server certificate. Public path: client, TLS to the CDN, a second TLS connection from the CDN to the gateway, services. Partner path: partner, TLS straight to the gateway (which demands the partner's certificate and checks it was issued by the authority you trust), services. If the CDN ended the partner's TLS, the gateway would see only the CDN's certificate.
Step 2: Where each concern sits
- Identity hand-off: the gateway authenticates the caller, then passes a verified identity to services: client ID, plan, tenant, scopes (the named permissions the credential carries, such as orders:read). It does so as a signed internal token (a token the gateway signs so services can check it was not altered) or trusted headers over mutual TLS inside the network, after removing any identity headers sent by the outside caller. Services trust the gateway's assertion and still make object-level decisions. Illustrative request before and after the gateway (the
X-header names are this design's own, not a standard):
Arrives from outside: Forwarded to the service:
GET /v1/orders GET /v1/orders
Host: partners.example.com Host: orders.internal
X-Client-Id: c_999 X-Client-Id: c_204
X-Plan: free X-Plan: partner
X-Scopes: orders:read
X-Request-Id: 5e1b...
The caller tried to claim client c_999 and plan free. The gateway discarded both headers and wrote the values it derived from the verified certificate and plan table. Without that step anyone could pose as another client.
- Request validation: at the gateway, per audience, using the shared API description (size, type, schema shape). Business rules stay in the services.
- TLS termination: public traffic at the edge; partner traffic at the gateway because of mutual TLS. Re-encrypt towards services where policy requires.
- Observability: every log line and metric carries audience, client ID, plan, route, status and request ID. Partners get usage and error reports for their own traffic; the public side gets aggregated analytics.
Step 3: Keys, plans and tiers
Data model:
- Plan: name, rate limit (requests per second), quota (requests per month), allowed routes or scopes, allowed regions, support level.
- Client: an organisation or developer, linked to one plan.
- Key: a credential belonging to a client. Many keys per client are allowed, for rotation.
Illustrative plans (invented for this example):
| Plan | Rate limit | Monthly quota | Audience |
|---|---|---|---|
| Free | 10 requests per second | 10,000 requests | public |
| Pro | 100 requests per second | 1,000,000 requests | public |
| Partner | 500 requests per second | 50,000,000 requests | partner |
Rate and quota are two controls with two purposes. Check the Free plan: sustained at its rate for a 30-day month, 10 x 86,400 x 30 = 25,920,000 requests, far above the 10,000 quota, so the quota binds first; 10,000 / 30 = 333 requests per day on average. The rate limit protects capacity from bursts; the quota protects the business model.
Capacity commitment check: if 40 partners each hold 500 requests per second, committed rate is 40 x 500 = 20,000 requests per second. If the partner pool handles 30,000 at its planned load, the commitment is 20,000 / 30,000 = 67 percent. Partners rarely peak together, so some oversubscription is normal, but the number must be known and watched.
Key handling:
- Issue: the public portal creates keys self-service; partners are onboarded by a person, who also issues the client certificate.
- Store only a hash of each key (a one-way function: the stored value lets you check a presented key but cannot be turned back into the key). Keys are long random strings, so a fast hash (SHA-256) is adequate; show the key once at creation.
- Include a short non-secret prefix in the key, so support and logs can identify a key without exposing it.
The key record and what a lookup sees (the key is made up):
import hashlib
def digest(key):
return hashlib.sha256(key.encode()).hexdigest()
key = "pk_3f9a_Zm1x8Qv2LrT7yBd4NwKc6HsEj0Ua" # shown to the client once
store = {digest(key): {"prefix": key[:7], "client": "c_117", "plan": "pro"}}
print("shown once:", key)
print("stored :", digest(key), store[digest(key)])
print("lookup ok :", store.get(digest(key)))
print("wrong key :", store.get(digest("pk_3f9a_Zm1x8Qv2LrT7yBd4NwKc6HsEj0Ub")))
print("in the log:", key[:7] + "...")
Output:
shown once: pk_3f9a_Zm1x8Qv2LrT7yBd4NwKc6HsEj0Ua
stored : 710bb8fbe125fba82337e04b6e8d2fe763194daadfbcece8126a8a19dff8a4c3 {'prefix': 'pk_3f9a', 'client': 'c_117', 'plan': 'pro'}
lookup ok : {'prefix': 'pk_3f9a', 'client': 'c_117', 'plan': 'pro'}
wrong key : None
in the log: pk_3f9a...
The gateway hashes the key a client sends and looks the hash up, so the store never holds the usable key; the prefix pk_3f9a is what appears in logs and support tickets. A key that differs by one character hashes to something completely different and finds nothing.
4. Rotation: allow two active keys per client at once, so a client moves from the old to the new without downtime, then revoke the old.
5. Revocation and plan changes propagate from the management store to every gateway node within a stated delay (for example seconds, by push or polling); a compromised key may need an urgent push path.
6. Upgrade or downgrade: change the client's plan link, not the key. Nothing changes on the client side.
Enforcement at request time: the gateway looks up the key in its local copy, finds the client and plan, applies the plan's rate limit, checks the monthly quota counter, checks the route against allowed scopes, and tags telemetry with client and plan. Over rate: 429 with Retry-After (a header telling the client how long to wait, given either as a number of seconds or as an HTTP date; this gateway sends seconds). Over quota: 429 as well, with a body that names the quota and the reset date, or 403 if a plan simply does not include the route; choose one convention, document it, and keep the two cases distinguishable.
Step 4: Different service levels
- Capacity: partners get a separate pool, so their latency does not depend on public traffic.
- Priority under overload: shed Free traffic first, then Pro, then Partner (load shedding by plan: deliberately rejecting the lowest-priority requests so higher plans keep their service).
- Latency and availability targets differ by plan and are measured separately.
- Support and change notice differ: partners get longer deprecation notice and a named contact.
Step 5: Usage analytics
Count usage in the gateway as aggregates per (client, route, status class, hour) and send them to the management store asynchronously. Billing and quota enforcement use these aggregates, not sampled logs. Review for plan fit: clients that sit near 80 percent of their quota or rate are upsell candidates; clients with a high 429 share need a conversation.
Common mistakes
- Encoding the plan in the key, so every upgrade needs a new key.
- Storing keys in plain text.
- One gateway pool for both audiences, so a public flood affects partners.
- Treating rate limit and quota as the same thing.
- Letting identity headers from outside pass through to services.
Judgment
I would run two gateway pools from one codebase, separate hostnames, mutual TLS for partners, a plan table that drives limits and routes, hashed keys with dual-key rotation, and analytics aggregated at the gateway. The split would flip to a single pool only if partner volume is tiny and the contract does not require capacity isolation.
You are deciding which concerns belong in the API gateway and which stay in the services behind it. Walk through authentication, request validation, TLS termination, routing, throttling and business rules, say where each should live, and explain what goes wrong when the gateway accumulates too much logic. How does the answer change for developer experience and for testing and rollback?
Sample Answer
The idea in plain words
A useful rule: put at the gateway what is the same for every service and can be decided from the request alone (who is calling, is the request well formed, is the caller within its allowance, where does it go). Keep in the services whatever depends on the service's own data or business meaning. The gateway is shared by every team, so every piece of logic placed there raises the cost of changing it and widens the damage of a mistake.
Where each concern should live
| Concern | Gateway | Service | Reasoning |
|---|---|---|---|
| TLS termination (decrypting HTTPS at the edge) | Yes | Optional re-encryption inside | One certificate lifecycle at the edge. If the network behind it is not trusted, encrypt again to the service. |
| Authentication (proving who the caller is: verifying a token's signature, its expiry, its issuer (who created it) and its audience (which service it was meant for)) | Yes | Receives verified identity | Same for all services, and a cryptographic check needs no business data. |
| Authorization (what this caller may do) | Coarse only: is this token allowed to call this route, or does it carry this scope (a named permission inside the token, such as orders:write) | Fine-grained: may this user refund this order | Fine-grained decisions need the order, its owner and its state, which only the service has. |
| Request validation | Shape only: content type, required fields present, types, size limit | Meaning: amount does not exceed the refundable balance | Shape checks need no data; meaning checks do. |
| Routing | Yes | None | Routing tables are the gateway's job. |
| Throttling (limiting request rate) | Per consumer or tenant, per route group | Cost-based limits on expensive operations | Identity is known at the edge; the true cost of an operation is known only inside. |
| Business rules | No | Yes | Usually data-dependent and owned by one team. |
Granularity: per tenant versus per route
A per-tenant limit (for example, each customer organization gets a fixed allowance across all routes) belongs at the gateway because it needs only the identity and must be uniform. A per-route limit that reflects the cost of one operation (a report export is far more expensive than a lookup) is best set by the owning team, ideally declared in that team's own repository and applied by the gateway, with a backstop in the service for its truly expensive paths. Validation that depends on what a particular service accepts, such as which option values a given version supports, stays in that service, because the gateway would otherwise need to be redeployed whenever the service changes.
What goes wrong when the gateway accumulates logic
- Blast radius (how much breaks when one change goes wrong). Suppose one gateway config serves 40 routes owned by 8 teams (assumption). A bad deploy of a gateway rule can break 40 of 40 routes, 100 percent. A bad deploy of one service breaks the routes that service owns, say 1 of 40, 2.5 percent.
- Coupling and queueing. Teams wait for the gateway team to ship their rule, and a rule for one team is released together with everyone else's.
- Latency. Every rule runs on every matching request, in the one place all traffic passes. Heavy transformations or calls to other systems from the gateway add to the delay of unrelated routes.
- Hidden logic. A behaviour defined in the gateway is not visible in the service's code, tests or local development, so bugs show up only in the shared environment.
- Ownership blur. When a discount rule fails, nobody is sure whether the gateway team or the service team owns the fix.
Developer experience, testing and rollback
- Developer experience: the service must run and be testable locally without the gateway. If a rule exists only in the gateway, developers cannot reproduce it. Keep gateway rules declarative (a file that states what should happen, such as "route /v1/orders to the orders service, 100 requests per minute per tenant", rather than code that does it), versioned in git, and let product teams edit their own route's file through review, with the platform team owning the shared chain.
- Testing: test gateway policies with a small contract suite: a list of sample requests, each with the status code it must produce. For example, a valid refund request must return 200, the same body with a string amount must return 400, the 101st request in a minute, with a limit of 100 per minute, must return 429, and a request with no credentials must return 401. Test service rules in the service's own unit tests. Never depend on the gateway as the only place a rule is exercised.
- Rollback: a service rollback reverts one team's code. A gateway rollback reverts everyone's policy. So roll gateway changes out gradually (a small share of instances or traffic first), keep the previous config version ready to restore, and make each change small enough to explain.
Worked scenario
A client calls POST /v1/orders/981/refund with a bearer token (a token sent in the Authorization header that grants access to whoever presents it) and body {"amount": 40}.
- The gateway terminates TLS, checks the token signature, expiry and audience, confirms the token has the scope orders:write, confirms the body is JSON under the size limit with an integer amount, checks the tenant's allowance (token bucket: a counter that refills at a steady rate and is spent per request), and forwards to the orders service with the verified user ID in a header.
- The service checks that this user owns order 981, that the order is in a refundable state, and that 40 does not exceed the amount still refundable. If it does, it returns a 422 (the request is well formed but cannot be processed as it stands) or a 409 (conflict with the current state of the order) with an explanation.
If the gateway had done step 2, it would have needed read access to order data and a release in step with the orders team.
Common mistakes
- Trusting the gateway's authentication so completely that services skip their own authorization check, which fails the day a service becomes reachable another way.
- Putting orchestration (calling three services and merging the results) in the gateway, which turns it into an application.
- Keeping rules as hand-edited, unreviewed settings with no way to test or roll back.
Unlock Full Question Bank
Get access to all 15 API Gateways and API Management interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.