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.
Sketch an illustrative configuration for an API gateway fronting a few services: routes, how callers are authenticated, a throttling rule, and a cache policy. Then say which concerns you would deliberately keep out of the gateway to avoid centralization risk.
Sample Answer
The idea in plain words
A gateway configuration is a declarative list: which public paths exist, which service each path goes to, what proof of identity each needs, how fast callers may go, and whether answers may be reused from a cache. The skill in the interview is not the syntax (every product differs) but choosing sensible policy per route and knowing which jobs not to put there. The configuration below is illustrative and uses a made-up format, not the syntax of any product.
Illustrative configuration
# Illustrative gateway config. Not the syntax of any real product.
listeners:
- name: public
host: api.example.test
tls:
min_version: "1.2" # refuse older TLS versions
certificate: edge-cert # certificate terminated at the gateway
upstreams:
orders: { address: orders.internal:8080, timeout_ms: 2000, max_in_flight: 200 }
users: { address: users.internal:8080, timeout_ms: 1000, max_in_flight: 100 }
catalog: { address: catalog.internal:8080, timeout_ms: 1500, max_in_flight: 150 }
auth_schemes:
user_token:
type: jwt # signed token sent as: Authorization: Bearer <token>
issuer: https://login.example.test
audience: api.example.test
jwks_uri: https://login.example.test/keys # public keys used to check signatures
partner_key:
type: api_key
header: X-Api-Key # key looked up against the key store
routes:
- path: /v1/orders/*
methods: [GET]
upstream: orders
auth: user_token
required_scope: orders:read # coarse check only
limit: { key: consumer, requests: 100, per_seconds: 60, burst: 20 }
cache: off
- path: /v1/orders/*
methods: [POST]
upstream: orders
auth: user_token
required_scope: orders:write # coarse check only
limit: { key: consumer, requests: 100, per_seconds: 60, burst: 20 }
cache: off
- path: /v1/users/me
methods: [GET]
upstream: users
auth: user_token
limit: { key: consumer, requests: 100, per_seconds: 60, burst: 20 }
cache: off
- path: /v1/catalog/*
methods: [GET]
upstream: catalog
auth: partner_key
limit: { key: api_key, requests: 100, per_seconds: 60, burst: 20 }
cache: { ttl_seconds: 60, vary: [Accept] } # shared cache; public data only
Every field, in plain words
- listeners.tls: the gateway decrypts HTTPS here (TLS termination), refuses protocol versions below 1.2 (TLS 1.0 and 1.1 are deprecated by RFC 8996 because of known weaknesses), and holds the certificate.
- upstreams: the backends. timeout_ms is how long the gateway waits for that service. max_in_flight caps simultaneous requests to it so one slow service cannot use every connection (a bulkhead).
- auth_schemes: how callers prove identity. A JWT (JSON Web Token, a signed token) is verified for signature, issuer, audience and expiry using public keys fetched from jwks_uri. JWKS stands for JSON Web Key Set: a JSON document, published by the login service, that lists the public keys whose matching private keys sign its tokens; the gateway downloads it, caches it and picks the key named in each token. Besides the signature and the expiry time, the claims checked are
issuer(who created the token, which must be the trusted login service),audience(who the token is meant for, which must be this API) and, per route, the scope (what the holder was granted: reading orders and writing orders are separate scopes). An API key is a shared secret passed in a header and looked up. - routes: path pattern, allowed methods (any other method gets 405 Method Not Allowed), the upstream, which auth scheme applies, and the policies. required_scope is a coarse check that the token was granted the permission (here one route per method so that reading orders does not demand the write scope); whether this user may touch this order is decided inside the orders service.
- limit: a token bucket, a counter that refills at a steady rate and spends one token per request. Here requests: 100 per per_seconds: 60 is a refill of 100 / 60 = 1.67 tokens per second, and burst: 20 means a caller can send 20 requests back to back before being slowed. key says what is counted: per consumer (the authenticated caller) or per API key, never per IP address alone, since many users can share one address.
- cache: for the catalog, a response may be reused for 60 seconds (
ttl_seconds, time to live), varying by the Accept header (vary: the named request headers become part of the cache key). It is a shared cache: one stored copy serves many callers, which is why it is only for public data. It is off for orders and user data, which are specific to a caller and change.
A timeline for GET /v1/catalog/items (illustrative): at second 0 a caller sends Accept: application/json; nothing is stored, so the gateway asks the catalog service (a miss) and stores the answer under the key (path, application/json). At second 20 another caller sends the same request: a hit, answered from the cache with no call to the catalog. At second 25 a third caller sends Accept: text/csv: different key, so a miss and a second stored copy. At second 61 the first copy has expired, so the next application/json request is a miss again.
What a throttled caller sees
A caller that has spent its 20 burst tokens gets a rejection. The time until one token is back is 1 / 1.67 = 0.6 seconds; Retry-After is whole seconds (or a date), so the gateway rounds up to 1. This exchange is illustrative:
HTTP/1.1 429 Too Many Requests
Retry-After: 1
Content-Type: application/json
Content-Length: 31
{"error":"rate_limit_exceeded"}
429 is defined in RFC 6585 and means this caller sent too many requests. The Content-Length of 31 is the byte length of the body shown.
Concerns to keep out of the gateway, and why
- Business rules and data-dependent validation (refund limits, who owns an order). They change with the product and need data the gateway does not have.
- Orchestration that calls several services and merges results. It makes the gateway an application with its own bugs, and every team's release depends on it.
- Fine-grained authorization. The gateway sees a token and a path, not the resource.
- Per-service transformations beyond simple renaming and header mapping, which hide behavior from the service's own tests.
- Anything that needs its own database or long-lived state per user.
Centralization risk is that the gateway is on every request path and shared by every team: a mistake in one team's rule can affect all traffic, and one team becomes the queue for everyone's changes. Keep the shared chain thin, keep the config in version control, review it, and roll changes out gradually.
Common mistakes
- One global rate limit for everyone, so the heaviest customer decides everyone's experience.
- Caching a response that depends on who is calling, which can serve one user's data to another. Cache only public, caller-independent data, or include the caller in the cache key.
- Treating the gateway's token check as the only security layer.
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.
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.
You are choosing how to build an API gateway that must support authentication (OAuth2 and mutual TLS), authorization policies, request and response transformation, per-tenant throttling, plugin-based protocol translation (for example SOAP to REST), canary releases and observability. Compare adopting an open-source proxy-based gateway, a managed gateway, and building a bespoke one, and justify your choice, including the extension model and operating cost.
Sample Answer
The idea in plain words
An API gateway is the reverse proxy (a server that receives client requests and forwards them to backends) that applies shared policies: authentication, authorization, transformation, throttling, canary routing and telemetry. You can adopt an open-source proxy-based gateway (software you run and operate yourself, extended with plugins), buy a managed gateway (a vendor runs it; you configure it), or build your own. Terms used below: a plugin or filter is a small piece of code the gateway runs inside the request path to add behaviour; the extension model is how (and in which languages) you can add such code to a product; a canary release sends a small share of traffic to a new version first. The decision is mostly about three things: whether the product's extension points can express your hard requirements, who carries the operating work, and what you give up if you must leave. Features on the checklist are rarely the deciding factor, because all serious options list most of them.
1. Clarify, then map each requirement to where the risk is
| Requirement | Risk to examine |
|---|---|
| OAuth2 and mutual TLS (both sides present certificates) | Does the gateway terminate mTLS and pass the verified client identity to the authorization policy? |
| Authorization policies | Can a policy use claims, tenant and route, and can it be tested outside production? |
| Request and response transformation | Header and JSON changes are common; body changes on large payloads cost memory |
| Per-tenant throttling | Keyed on a claim, with shared counters across nodes |
| Protocol translation, SOAP (an XML message protocol) to REST | The hard one: needs WSDL/XSD knowledge (the WSDL file lists a SOAP service's operations and the XSD files define the exact shape of each XML message), SOAP faults (SOAP's own error format) mapped to HTTP status codes, and XML security handling (defences against hostile XML such as entity-expansion bombs and external-entity references) |
| Canary releases | Weighted or header-based routing with fast rollback |
| Observability | Metrics, logs and traces per route and tenant, exported to our tooling |
In an interview I would also ask: expected request volume, latency budget, team size and on-call capacity, data-residency rules (laws or contracts requiring data to stay in a given country or region), and how many SOAP operations must be translated.
2. Compare the three options
Open-source proxy-based gateway. Strength: the proxy core (HTTP/2, TLS, connection pooling, hot reload: applying new configuration without restarting) is mature, and you control the extension model: plugins or filters written in the supported languages, version-pinned and testable in your CI. Cost: you run it, upgrade it, patch its security issues and carry its on-call. Exit cost is moderate: your plugin code is the lock-in.
Managed gateway. Strength: no fleet to run, scaling and patching done for you, fastest start. Cost: you live within its policy language and limits, its extension points and its supported protocols. Exit cost is highest in configuration: every policy is expressed in its dialect. Before choosing, read the vendor's current documentation for the specific points that matter to you; I would not trust a feature checklist.
Build your own. Strength: exact fit. Cost: you must build and then maintain the parts that took others years to make robust (protocol handling, TLS, timeouts, overload behaviour, hot config reload, security fixes). Justified only when the gateway itself is the product or a requirement truly cannot be met otherwise.
3. Operating cost (every figure is an assumption, not a vendor price)
Assumptions: one engineer costs 180,000 USD per year fully loaded; traffic 200 million requests per month; a managed price of 3.50 USD per million requests; a three-year horizon.
- Adopt open source. This estimate assumes the SOAP translation is written as a gateway plugin and sits inside the setup and running effort below, so it is the like-for-like total for the full requirement list. Setup: 2 engineers x 4 months = 8 engineer-months = 8/12 of a year x 180,000 = 120,000 USD. Running: 1 engineer-year (180,000) + infrastructure 24,000 = 204,000 per year. Three years: 120,000 + 3 x 204,000 = 732,000 USD.
- Managed. Setup: 1 engineer x 2 months = 30,000. Running: 0.5 engineer-year (90,000) + usage 200 x 3.50 x 12 = 8,400 = 98,400 per year. Three years: 30,000 + 3 x 98,400 = 325,200 USD.
- Managed plus an adapter service for SOAP translation (if the gateway cannot host the translation). Extra setup: 2 engineers x 3 months = 0.5 year x 180,000 = 90,000. Extra running: 0.25 engineer-year = 45,000 per year. Three years: 325,200 + 90,000 + 3 x 45,000 = 550,200 USD.
- Build. Setup: 4 engineers x 18 months = 6 engineer-years x 180,000 = 1,080,000. Running: 2 engineers (360,000) + infrastructure 24,000 = 384,000 per year. Three years: 1,080,000 + 3 x 384,000 = 2,232,000 USD, and nothing ships for the first 18 months.
Sensitivity. A crossover is the volume at which two options cost the same; it tells you how far your real traffic is from the point where the cheaper option changes, so you know how much to trust the recommendation. Managed usage cost per year is 12 months x 3.50 USD per million x V, where V is millions of requests per month, which is 42 x V. Add the 90,000 of staff time and the annual run cost of managed is 90,000 + 42 x V. Compare run costs first. It equals the open-source 204,000 when 42 x V = 114,000, so V = 114,000 / 42 = about 2,714 million, or 2.7 billion requests per month. With the adapter service the managed run cost is 90,000 + 45,000 + 42 x V, which equals 204,000 at V = 69,000 / 42 = about 1,643 million per month.
Setup cost moves the three-year crossover. Open source and managed plus adapter have equal setup (120,000 against 30,000 + 90,000 = 120,000), so for that pair the three-year crossover is the same 1,643 million. Managed alone has 90,000 less setup than open source, so its three-year crossover is higher: 30,000 + 3 x (90,000 + 42 x V) = 120,000 + 3 x 204,000 gives 126 x V = 432,000, so V = about 3,429 million. At 200 million per month, volume is far below every one of these crossovers, so at these assumptions cost does not favour open source; that is the number to beat. If engineer cost, headcount or price differ, rerun the arithmetic with yours.
4. My recommendation
For the stated requirements and the assumptions above, I would choose the managed gateway for the edge concerns and put SOAP-to-REST translation in a small adapter service behind it, an adapter being a service that converts between the legacy model and ours, which also acts as an anti-corruption layer (a boundary that stops the old model leaking into new code). Reasons: over three years the managed gateway with the adapter service costs 550,200 USD against 732,000 USD for open source (a gap of 732,000 - 550,200 = 181,800 USD), and the gateway part alone, which covers authentication, throttling, canary and observability, costs 325,200; those are commodity concerns that are cheaper when someone else runs them. SOAP translation is the risky part, and a separate service is testable on its own, written in a language the team knows, and does not tie the gateway's extension model to XML handling.
Run a one-week spike before committing. The managed gateway must show, in a test account: mTLS client identity reaching an authorization policy, per-tenant throttling keyed on a token claim, header-based canary weights with rollback, and log and trace export to our tooling. If any of these four fails, switch to the open-source gateway. Also switch if volume grows past the crossover, if a rule requires self-hosting (data residency or a private network with no vendor connectivity), or if the plugin approach to translation turns out to be required by an existing team's constraints. I would not build unless the gateway becomes a product.
5. Extension model, in practice
For the open-source path, define a plugin interface contract, a CI harness that starts the gateway with stub upstreams, and a rule that plugins are version-pinned and upgraded on a schedule. For the managed path, keep policies as exported configuration in version control and run the same test suite against it, so leaving later is a translation of a tested ruleset, not a rediscovery of it.
Common mistakes
- Comparing feature lists instead of testing the two or three hardest requirements.
- Counting licence or usage cost but not the engineers who run it.
- Embedding heavy XML translation in a shared gateway process where a bug can affect all routes.
- Building for "full control" without a requirement that needs it.
Design the edge security posture of an API gateway for partner and mobile traffic. Requirements: tenant-scoped limits, protection from volumetric abuse, mutual TLS for partners, tamper-evident audit logs, and low latency worldwide. Where do TLS termination, caching and authentication enforcement sit relative to the CDN or WAF, and how do you manage certificates and test the whole flow?
Sample Answer
The idea in plain words
The edge is the outermost layer that internet traffic meets before it reaches your own servers. The origin is your own backend, here the API gateway and the services behind it, as opposed to the edge servers in front of it. For partner and mobile traffic the edge is built in layers, each doing the job it is positioned to do: a CDN (content delivery network, servers spread around the world close to users) and a WAF (web application firewall, which filters malicious requests) soak up volumetric abuse (floods of junk traffic meant to use up your bandwidth, as opposed to clever single requests) and terminate TLS for public clients (TLS is the encryption layer under HTTPS, and terminating it means being the device that decrypts); the API gateway behind them knows who the caller is and applies tenant limits and authentication; services check object-level permissions. The insight is placement: a control only works where the traffic it must see actually passes, and where the information it needs (such as the tenant) is available. Partner mutual TLS (mTLS, where the client also proves its identity with a certificate) is the case that breaks the simple "terminate everything at the CDN" picture. The core of the answer is placement of TLS termination, authentication and limits (Steps 1 to 4); certificates and the audit log (Step 5) and the latency arithmetic (Step 6) support it, and the remaining steps are checks.
Step 1: The layers and what each enforces
Request path for mobile and other public clients:
client, then DNS or anycast (one address announced from many locations, so the network delivers each client to the nearest one) to the nearest edge, then CDN and WAF (terminate TLS, soak up DDoS, filter, cache public responses), then a second TLS connection to the origin gateway, then the gateway (authentication, tenant limits, validation, audit), then services.
| Layer | Enforces | Why here |
|---|---|---|
| Edge network (DDoS protection) | Volumetric floods at the network and transport layers | Only large spare capacity close to the sources can survive floods larger than your origin links |
| CDN and WAF | TLS termination for public traffic, bot and injection filtering, coarse per-IP limits, caching of public GETs | Sees the request in plain text early, and is close to users |
| Gateway | Authentication, tenant-scoped limits, schema validation, audit log, partner mTLS | The tenant and caller identity are known only after credentials are checked |
| Services | Object-level authorisation and business rules | Only they know what an object means |
Origin lock (making the origin unreachable except through the CDN): the origin accepts connections only from the CDN (allow-listed address ranges, or mutual TLS from the CDN, or a shared secret header checked at the gateway). Otherwise an attacker finds the origin address and sends traffic around the WAF. Test this explicitly (Step 8).
Step 2: TLS termination and mutual TLS for partners
TLS termination means the device that decrypts the traffic holds the server certificate. A CDN that terminates TLS creates two separate TLS connections: partner to CDN, and CDN to origin. The partner's client certificate is presented only on the first one, so it is validated, or not, at the CDN. The second connection is a new handshake in which the CDN is the client, so the gateway sees the CDN's certificate, never the partner's, unless the CDN forwards the partner's identity in a header. Forwarded identity headers are only as trustworthy as the channel carrying them.
Recommendation: give partners their own hostname (for example partners.example.com) whose traffic reaches the gateway listener directly, where the gateway requires and validates a client certificate. Direct does not mean unprotected: a network-layer DDoS service can sit in front and forward the raw TCP bytes without decrypting them. It is not a CDN because it never holds the server certificate or reads HTTP, so the TLS handshake still runs end to end between the partner and the gateway and the client certificate arrives intact. Public and mobile traffic uses the CDN hostname. Reasons: the certificate chain is checked by the component that enforces authorisation; partner traffic is predictable and low volume, so losing CDN caching costs little; and the audit log can record the verified certificate identity. If the CDN offers client-certificate validation and your risk assessment accepts it, the alternative is to validate there and forward a signed identity assertion, with the origin accepting it only over the locked CDN-to-origin channel.
Step 3: Tenant-scoped limits and abuse protection
- Edge: only things visible without credentials, such as IP address, network, request rate and request shape. Per-IP limits are coarse (many users share a mobile carrier IP address), so keep them loose.
- Gateway: per-tenant limits keyed by the verified client or tenant ID, because that identity exists only after authentication.
- Together: the edge protects the gateway's capacity; the gateway protects tenants from each other.
Step 4: Caching at the edge
Cache only responses that are the same for everyone: public data with Cache-Control: public, max-age=.... Authenticated responses use private or no-store unless the cache key includes the tenant. Never rely on Vary: Authorization (a header telling caches to keep a separate copy per value of the named request header) to separate users; it creates one cache entry per token. A mistake here leaks one tenant's data to another, so a test that requests the same URL as two tenants and compares bodies belongs in the pipeline.
Step 5: Certificates and audit logs
Certificate management:
- Server certificates: automated issue and renewal (the ACME protocol, a standard way for software to request and renew certificates from a certificate authority without a human), short lifetimes, alerts at 30, 14 and 7 days before expiry.
- Partner client certificates: issued by a private certificate authority (CA, the signer) you control, valid for a limited period (for example 90 days), with an overlap window so a partner can install the new certificate before the old one expires, and a revocation path (a revocation list the gateway reloads, or simply very short lifetimes).
- Mobile apps: pinning means the app accepts only a specific certificate or key instead of any certificate a trusted authority signed. A certificate chain runs from the leaf (the server's own certificate, which rotates often) through an intermediate (a CA certificate that signed the leaf) to a root. Avoid pinning the leaf. If you pin, pin the public key of an intermediate and include a backup pin; a wrong pin locks every installed app out until users update.
Tamper-evident audit logs: each entry stores the hash of the previous entry, so changing or deleting one breaks every later hash. Illustrative: entry_n stores hash_n = SHA-256(hash_(n-1) followed by the entry text). A three-entry chain, with each hash shown as its first 8 hex characters for reading (the chain itself uses the full 64), shows what verification sees:
import hashlib
def link(prev_hash, text):
return hashlib.sha256((prev_hash + text).encode()).hexdigest() # full 64 hex characters
entries = [
"1 allow tenant=acme route=/orders",
"2 deny tenant=acme route=/admin",
"3 limited tenant=zed route=/orders",
]
def build(entries):
chain, prev = [], "start"
for text in entries:
prev = link(prev, text)
chain.append((text, prev))
return chain
def first_break(stored, entries):
prev = "start"
for i, (text, saved) in enumerate(zip(entries, [h for _, h in stored])):
prev = link(prev, text)
if prev != saved:
return i + 1
return None
stored = build(entries)
for text, h in stored:
print(h[:8], text) # shortened to 8 characters only for display
print("intact:", first_break(stored, entries))
print("entry 2 deleted:", first_break(stored, [entries[0], entries[2]]))
print("entry 2 edited:", first_break(stored, [entries[0], "2 allow tenant=acme route=/admin", entries[2]]))
Output:
df6198f4 1 allow tenant=acme route=/orders
3f08517f 2 deny tenant=acme route=/admin
4bd5a95b 3 limited tenant=zed route=/orders
intact: None
entry 2 deleted: 2
entry 2 edited: 2
Each stored hash covers everything before it. Verification recomputes the chain from the first entry and reports the first position where the recomputed hash differs from the stored one: None means the chain is intact, and both deleting entry 2 and editing it are caught at position 2. The chain alone has two limits. An attacker who rewrites every later hash produces a chain that verifies, and cutting entries off the end leaves a shorter chain that still verifies. So ship entries immediately to storage that the gateway can append to but not rewrite, and periodically write the most recent hash to a separate system (an anchor) that the attacker cannot reach. An attacker with access to the gateway host can still stop logging, so alert on a gap in sequence numbers or a missing heartbeat. The log records caller identity, tenant, route, decision (allow, deny, limited), request ID and time, never request bodies containing secrets.
Step 6: Global latency, with arithmetic
Setting up a new HTTPS connection costs round trips before the first request byte can be sent: 1 round trip for the TCP handshake plus 1 for TLS 1.3 (RFC 8446), so 2 round trips. Assume a user in a distant region has a round-trip time (RTT) of 150 ms to the origin and 20 ms to the nearest edge.
- Directly to origin: 2 x 150 = 300 ms before the request is sent.
- To the edge: 2 x 20 = 40 ms; the edge keeps warm connections to the origin, so the user does not pay the long path for setup.
HTTP/3 runs over QUIC, a transport built on UDP that carries the TLS 1.3 handshake inside its own connection setup, so there is no separate TCP handshake: the client's first packet starts both, and one round trip completes them (20 ms at the edge). The assumed RTTs are illustrations, not measurements of any real network. The edge also removes the setup cost for repeat visits through connection reuse.
Step 7: Mobile-client specifics
- Mobile networks change addresses and drop connections; HTTP/3 survives address changes better than TCP.
- Retries by the app must be bounded with jitter, and non-idempotent calls carry an idempotency key.
- Per-IP limits hit shared carrier addresses, so prefer per-device or per-account limits at the gateway.
- Include the app version in a header to allow forced upgrade and targeted blocking.
- Keep configuration endpoints cacheable at the edge.
Step 8: Testing the whole flow
- Functional TLS tests: valid partner certificate accepted; expired, wrong-CA, revoked and missing certificate each rejected, checked with
openssl s_client -cert ... -key ...orcurl --cert ... --key .... - Origin bypass: connect directly to the origin address from a non-CDN network; it must fail.
- WAF rules first in log-only mode against replayed production traffic, then enforce.
- Cache isolation: two tenants, same URL, different bodies.
- Limit tests: a noisy tenant cannot raise another tenant's 429 rate.
- Audit: delete a log entry in a copy; verification must fail at that point.
- Performance: synthetic probes from several continents report connection, TLS and first-byte times separately; load tests ramp to peak plus headroom.
- Certificate expiry drill in staging.
Common mistakes
- Putting authentication only at the CDN and leaving the origin reachable.
- Trusting identity headers from the CDN without locking the origin.
- Caching authenticated responses with a shared key.
- Pinning a certificate with no backup.
Judgment
I would terminate public and mobile TLS at the CDN with a locked origin, serve partners on a separate hostname with mTLS validated at the gateway, enforce tenant limits and authentication at the gateway, and chain audit entries with an external anchor. What would flip the partner decision: a CDN that validates client certificates and a risk review that accepts forwarded identity.
Unlock Full Question Bank
Get access to all 10 API Gateways and API Management interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.