Module 2: Networking & Web
API Gateways
Use API gateways to manage microservice traffic — auth, routing, rate limits, BFF aggregation, and how gateways differ from LBs and reverse proxies.
When you split a monolith into services, clients should not know twenty internal URLs. An API gateway is the front door — cross-cutting concerns at the edge, domain logic in services.
What you will learn
- Explain why microservices need a single API front door
- List gateway responsibilities vs service/domain logic
- Cover auth, routing, rate limits, and optional BFF aggregation
- Contrast gateway vs load balancer vs reverse proxy
- Avoid turning the gateway into a second monolith; plan for HA
Why an API gateway exists
- Clients want one stable entry point. Services want to evolve independently. The gateway sits between those needs.
- Hides internal service topology and ports from mobile/web clients
- Centralizes cross-cutting API concerns instead of copying them into every service
- Gives a place for versioning, quotas, and edge policy
- Lets you re-split backends without forcing app releases for every URL change
Where it sits on the path
- Reuse the life-of-a-request canvas. The gateway is a specialized reverse-proxy hop for APIs.
- Typical path: Client → CDN (optional) → LB / gateway → microservices → cache/DB
- Often combined with or placed behind a load balancer for HA
- North-south traffic (clients → your APIs); service mesh often handles east-west
- Keep service instances private; only the gateway/LB need public exposure
What belongs on the gateway
- Put shared, request-scoped, mostly-stateless concerns here.
- TLS termination and certificate management at the edge
- Authentication: JWT/OAuth validation, API keys, mTLS for partners
- Routing by path/host/header to the right service; canary/weighted releases
- Rate limiting, IP allow/deny, CORS, basic schema/size validation
- Request logging, correlation IDs, metrics, and tracing headers
- Optional response aggregation (BFF) for mobile-specific payloads
What should stay in services
- If the gateway knows too much business detail, it becomes a distributed monolith.
- Domain rules, pricing, inventory math, entitlement decisions
- Multi-step business transactions and saga/workflow orchestration
- Long-lived business state — gateway should stay mostly ephemeral
- Service-specific authorization beyond “is this token valid?”
- Heavy transformation that changes every time product rules change
Auth, identity, and tenancy
- Gateways are good at verifying who is calling; services still enforce what they may do.
- Validate JWT signature/expiry at the edge; pass claims downstream
- Reject unauthenticated calls early to protect backends
- Propagate user/tenant IDs via trusted headers only on a private network
- Partner APIs may use API keys or mTLS in addition to user tokens
- Do not treat gateway auth as a substitute for service-level authorization
Routing, versioning, and releases
- Routing is how the front door stays stable while backends change.
- Path-based routes: /v1/orders → order-service
- Header or cookie-based canaries for a percentage of traffic
- API versioning at the gateway while old and new services coexist
- Health-aware upstreams: remove bad instances from rotation
- Timeouts and retries with care — avoid retry storms on non-idempotent POSTs
Rate limits and abuse controls
- Edge quotas protect shared capacity and slow down abusive clients.
- Limit by API key, user ID, IP, or tenant — pick the identity that matches the product
- Return 429 with Retry-After so well-behaved clients back off
- Combine with WAF rules for obvious attack patterns
- Global limits at gateway + finer limits inside hot services if needed
- Document quotas; silent drops confuse every client team
BFF and aggregation
- A Backend-for-Frontend is a gateway (or adjacent service) shaped for one client type.
- Mobile BFF can aggregate 3 service calls into one payload over slow networks
- Keeps chatty microservice fan-out off the device
- Risk: BFF grows into a mega-orchestrator — keep it client-shaped, not domain-shaped
- Prefer async workflows when aggregation becomes a long transaction
- GraphQL gateways are another aggregation style with similar caution
Gateway vs LB vs reverse proxy
- Same family of edge boxes — different emphasis. Keep the vocabulary clean.
- Load balancer — distribute traffic across healthy instances
- Reverse proxy — represent servers; TLS, routing, cache, HTTP features
- API gateway — reverse-proxy style front door with API auth, quotas, and service routing
- Many clouds blend these; say which jobs you need, not only product names
- You can stack: CDN → gateway → service LBs → instances
Failure modes and anti-patterns
- A gateway is a critical hop. Design for its failure and for team misuse.
- Gateway down ⇒ all external APIs down — run HA pairs / multi-AZ
- Overloading the gateway with business rules ⇒ second monolith
- Chatty gateway orchestration on every click ⇒ latency and coupling
- Passing unverified client headers as trusted identity ⇒ security bugs
- One shared gateway team bottleneck for every service change — define self-service routes
Interview framing
- Use this order when microservices appear in a design.
- Draw Client → API gateway → services; keep internals private
- List edge jobs: TLS, authN, route, rate limit, logs
- Push domain logic and transactions into services
- Call out HA for the gateway and timeouts to upstreams
- Add BFF only if a client needs aggregation — explain why
Quick revision checklist
- One gateway can front many services.
- Cross-cutting at gateway; domain logic in services.
- Gateway down = all APIs down — plan HA.
- Authenticate at the edge; authorize in services.
- Mention 429 + Retry-After for rate limits.
- Don’t turn the gateway into a business-logic monolith.
FAQs
Gateway vs load balancer?
LBs distribute connections/requests across instances. Gateways understand APIs (paths, auth, quotas) and often sit with or after an LB. Many products blur the line — describe the jobs.
Do I need a gateway for a monolith?
Not always. A reverse proxy/LB may be enough. Gateways shine when many services need a shared front door for auth, routing, and quotas.
Is a BFF the same as an API gateway?
A BFF is often implemented as a gateway (or a thin service behind one) tailored to one client. Same edge idea; BFF emphasizes client-specific aggregation.
Should the gateway call five services on every request?
Only when the client truly needs one aggregated response and the fan-out stays fast. Heavy workflows belong in a service or async pipeline, not the hot gateway path.
Where do rate limits belong?
Start at the gateway for coarse, shared protection. Add service-level limits for expensive endpoints that need finer rules.
Gateway vs service mesh?
Gateway handles north-south client traffic into your system. A mesh (sidecars) usually handles east-west service-to-service policy. Many architectures use both.
Learner’s Task
- Practice out loud for 8–10 minutes. Design a front door for a small microservice set.
- Pick 3 services (e.g. users, orders, catalog) and draw Client → API gateway → services.
- List five concerns you put on the gateway and three you keep inside services — justify each.
- Add auth (JWT) and a rate-limit rule; say what status code and headers a rejected client sees.
- Decide whether mobile needs a BFF aggregation; if yes, mark which calls it fans out to.
- Write a 4-sentence closing: front-door purpose, edge jobs, HA note, and one anti-pattern you avoided.