API Gateway
An API gateway is an edge entry point for routing and selected cross-cutting policies.
What, why, when and how
What is it?
An API gateway is an entry boundary that routes requests and can apply shared policies such as authentication, quotas and request limits.
Why is it needed?
Public clients need a consistent boundary and backends need protection from invalid, oversized or excessive requests.
When should I use it?
Use it when multiple APIs need common ingress policies, routing or client-facing contract management.
When should I choose something else?
A gateway does not replace resource-level authorization or business validation. A separate gateway may be unnecessary for a small service with adequate ingress controls.
How do I use it?
Validate the caller, strip or replace untrusted identity headers, route to a scoped backend, apply limits and propagate trace and deadline information.
Can you show a concrete example?
A valid token identifies user u7 in tenant t1. The backend still verifies that notice n40 belongs to t1; successful gateway authentication alone cannot authorize access to another tenant’s notice.
Read the diagram
Gateway authenticates user u7 in tenant t1; Request targets notice n40; Backend checks tenant ownership before access
Follow the detailed diagrams below to trace the additional state changes and failure cases behind these answers.
An API gateway is an edge entry point for routing and selected cross-cutting policies. It can centralize TLS termination, authentication integration, quotas, request shaping, and observability, but it should not silently become the owner of every business rule. Its capacity, configuration rollout, and failure behavior belong in the design.
Track one request across trust boundaries
For GET /notices/n40, the gateway checks request shape/size and validates the token under its issuer/audience/expiry rules. It derives a trusted principal context and removes spoofable client headers before forwarding. The origin checks that this principal may read n40 in tenant t1. Authentication at the edge does not establish ownership of every object ID.
client: token + notice ID; untrusted tenant header=t2
gateway: validate identity; replace trusted context with t1
origin: lookup n40 WHERE tenant=t1; apply object policy
response: bounded representation; no token/body in logsRead the diagram
client: token + notice ID; untrusted tenant header=t2; gateway: validate identity; replace trusted context with t1; origin: lookup n40 WHERE tenant=t1; apply object policy; response: bounded representation; no token/body in logs
Routing uses host/path/version rules and available backends. An L7 gateway may transform responses or enforce quotas; a load balancer primarily spreads work over healthy targets under its routing contract. Cache only representations with safe scope, freshness and variation. A tenant-independent URL does not imply a tenant-independent value.
Give the request one deadline and pass the remaining budget to the origin. A gateway retry of an uncertain POST must follow its operation contract and stable identity. Horizontal gateway instances need coherent quota/configuration behavior; independent local counters approximate or multiply a global allowance unless a budget protocol exists.
Monitor request IDs, gateway latency separately from origin latency, denials, routing failures and per-tenant admission. The extra hop and configuration plane are failure boundaries. Drain long connections and preserve a rollback rule for routing changes.
Show answer and explanation
Answer: Ignoring the client t2 header is necessary but insufficient: every origin object read still enforces the derived t1 scope. Adding a gateway cannot replace that row-level check.
Step-by-step reasoning
1. 1 · Frame
Map external routes to service ownership and protocols. Specify which checks happen at the edge—coarse request size, token verification, route quota—and which must happen in the service—object authorization and business invariants. Define versioning, timeouts, retry policies, and how client identity propagates without trusting spoofable headers.
2. 2 · Model
Routes are configuration with version and rollout state. A request carries trace identity, authenticated principal, tenant, deadline, and bounded payload. Gateways should avoid logging credentials and sensitive bodies. Service discovery and route health have their own freshness. Streaming, large uploads, and WebSockets require explicit timeout and buffering behavior.
3. 3 · Scale
Use a fleet across failure zones and keep gateway CPU/memory limits known. Rate-limit by keys available at that layer but enforce critical global budgets at their authority. Circuit breaking can reduce pressure but needs a recovery policy. Deploy route changes gradually and retain rollback. Avoid synchronous gateway-to-many-service orchestration that adds latency to every request.
4. 4 · Recover
If the gateway is unavailable, can clients reach safe fallback endpoints? If it retries a POST after an upstream timeout, can it duplicate an effect? Use idempotency-aware retries and propagate an end-to-end deadline. A healthy gateway can still send traffic to an unhealthy backend; readiness and load shedding should consider upstream capacity.
Contracts and state
The following sketch makes the decision boundary concrete. Field names and capacity assumptions are illustrative; adapt them to the stated product contract.
Route(method, path, service, version, policy)
Context(principal, tenant, trace_id, deadline)
Gateway: authenticate/coarse limit -> route -> service
Service: object authorization -> invariant -> durable effect
Never log bearer credentials or trust client tenant headersWorked example
A mobile client sends a large upload through the API. Proxying every byte through the gateway consumes connection and bandwidth capacity. The gateway can authenticate the upload-session request and issue scoped object-store authorization; the byte transfer takes a separate path. Finalization returns to the service for verification.
Failure walkthrough
A gateway retry policy repeats a POST when an upstream response times out. The upstream may already have committed. Restrict retries to safe operations or propagate a stable idempotency identity that the owning service enforces. Protect against retry amplification during partial backend failure and monitor route-specific timeouts, concurrency, and rejected requests.
Read the diagram
Gateway sends POST → Service commits order → Response times out → Retry carries same identity → Service returns original result
Decisions and trade-offs
| Policy | Good boundary | Do not substitute for |
|---|---|---|
| Authentication | Verify caller identity | Resource authorization |
| Rate limit | Protect edge capacity | Inventory/payment invariant |
| Routing | Map API to owner | Business orchestration |
| Retry | Safe idempotent requests | Ambiguous write resolution |
Check your understanding
Which authorization check belongs in a service even if the gateway already authenticated the user?
Show answer and explanation
Answer: The service must check whether that principal may act on the requested object and current state. Authentication at the edge does not establish ownership. The service has the authoritative resource and must enforce its invariant even if another route bypasses a particular gateway policy.
Primary documentation
Read the first-party engineering account or official technical reference. Company engineering posts describe the scope and date of that publication; the interview reconstruction and scenarios here are original teaching examples.
Continue the connection
Study Networking Essentials and explain which guarantee from this lesson carries into that topic.
Define the boundary it actually owns
A gateway can terminate supported protocols, authenticate tokens, route requests, apply quotas and collect telemetry. Authorization still needs resource context: a valid token does not prove that its owner can access a particular school or document. Decide which checks belong at the gateway and which require application data.
Keep gateway work bounded. Large transformations, long synchronous workflows or unbounded body buffering turn a shared ingress tier into a bottleneck. Propagate request identity and deadline to downstream services. If the gateway returns a timeout, the backend may still commit; clients need operation identity for safe retry.
Separate overload protection from customer quota enforcement. A WAF rule, a per-user rate limit and an internal concurrency cap solve different problems. Use route-specific limits because an inexpensive read and a large export request have different costs. Connection draining and versioned routing configuration are part of safe deployment.
Read the diagram
Policy / Good boundary / Do not substitute for; Authentication / Verify caller identity / Resource authorization; Rate limit / Protect edge capacity / Inventory/payment invariant; Routing / Map API to owner / Business orchestration; Retry / Safe idempotent requests / Ambiguous write resolution
Operational sketch
edge -> gateway -> authentication -> route policy
application -> tenant/resource authorization
deadline and trace ID propagated
large job -> 202 + status resourceA tempting mistake
Putting a gateway in front of an API does not automatically make the origin unreachable directly. Restrict and authenticate origin access or clients may bypass the intended controls.
Transfer exercise
Which layer should check that a teacher can read one student record?
Show answer and explanation
Answer: The application authorization boundary with current tenant and relationship data, possibly assisted by gateway identity. Token validity alone is insufficient.
Shared foundation: Reliability and Overload Control
Reliability and Overload Control: Bound deadlines, queues, concurrency and retry work; calculate safe admission and recovery. Work its failure history before extending this design.
Which authorization check belongs in a service even if the gateway already authenticated the user?
Your design draft
Clarify assumptions, explain your approach, and test the difficult cases. Save your draft, then compare it with the study notes.
Self-review checklist
Self-guided practice. Automated AI feedback and code execution are not connected.