API Gateway in Microservices

An API Gateway is a single entry point that sits between external clients (web browsers, mobile apps, third-party integrations) and a fleet of internal microservices. Instead of forcing every client to track dozens of service URLs and forcing every service to re-implement authentication, rate limiting, and logging, the gateway centralizes cross-cutting edge concerns in one place.

How an API Gateway Works

When a client calls https://api.example.com/orders, the request hits the API Gateway first. The gateway terminates TLS, validates the caller’s JWT or API key, enforces rate limits, rewrites or translates the request if needed, and routes it to the matching internal microservice.

API Gateway routing HTTPS requests from Web App and Mobile App through Auth, Rate Limit and Routing to Order Service (/orders), Inventory Service (/inventory), and Delivery Service (/deliveries) API Gateway routing HTTPS requests from Web App and Mobile App through Auth, Rate Limit and Routing to Order Service (/orders), Inventory Service (/inventory), and Delivery Service (/deliveries)
An API Gateway exposes one unified entry point and routes requests to internal microservices · Made with Akriti

Core Responsibilities of an API Gateway

  1. Request Routing & Path Rewriting: Maps external endpoints (/v1/orders, /v1/inventory) to internal services (often via service discovery) so you can refactor, split, or rename microservices without breaking mobile or web clients.
  2. Authentication & Authorization: Verifies OAuth2/JWT tokens or API keys once at the edge and forwards trusted identity headers to downstream services.
  3. Rate Limiting & Quotas: Protects internal services from abusive traffic bursts, scraping, or noisy tenants before requests reach business logic.
  4. Protocol Translation: Exposes client-friendly REST or GraphQL externally while talking to internal microservices over gRPC, Protobuf, or asynchronous messaging.
  5. Response Aggregation (Composition): Combines responses from two or three internal services into a single round trip — especially valuable for mobile clients on high-latency cellular networks.
  6. Observability & Edge Caching: Injects a correlationId header for distributed tracing, emits centralized access logs/metrics, and can serve cached read responses (working alongside a CDN and Redis caching).

API Gateway vs. Load Balancer

Because both sit in front of backend servers, engineers often confuse them — in production, you usually run both (a load balancer distributes traffic across redundant API Gateway instances, and internal load balancers sit in front of each service pool):

Dimension Load Balancer API Gateway
Primary job Spread traffic evenly across healthy replicas of a service Manage API contracts, security, quotas, and routing across many services
Awareness of APIs Network/HTTP level (IP, port, basic path rules) Deep API awareness (JWT claims, per-user rate limits, OpenAPI schemas, retries)
Protocol translation Usually passes the same protocol through (TCP or HTTP) Translates REST/GraphQL ↔ gRPC, JSON ↔ Protobuf
Response aggregation No — proxies one request to one backend Yes — can fan out and merge responses (or delegate to a BFF)
Examples AWS NLB/ALB, HAProxy, NGINX Kong, Envoy Gateway, AWS API Gateway, Apigee, KrakenD

The Backend-for-Frontend (BFF) Pattern

A single monolithic API Gateway shared by web, iOS, Android, and partner APIs can quickly become a team bottleneck — every frontend change requires editing the shared gateway.

The Backend-for-Frontend (BFF) pattern solves this by giving each client experience its own thin gateway (Web BFF, Mobile BFF, Public API Gateway):

  • Each BFF tailors payloads to its client (e.g., compact responses for mobile, richer tables for desktop) without bloating core domain services or creating pass-through coupling inside internal services.
  • Frontend teams own and deploy their BFF independently without blocking other clients.

Pitfalls to Avoid

  • Turning the gateway into a monolith: Never put core business rules (pricing, inventory checks, order state machines) inside the API Gateway. Keep it focused on routing, security, and cross-cutting policies.
  • Single point of failure: Always run multiple stateless API Gateway replicas behind a load balancer so a gateway crash never takes down the entire API.
  • Hidden temporal coupling: If the gateway synchronously aggregates 6 microservices on one endpoint, one slow downstream service slows the whole screen. Enforce strict per-call timeouts, circuit breakers, and graceful fallbacks.

FAQs

Do I need both a Load Balancer and an API Gateway? Usually yes in a microservices architecture. A load balancer distributes incoming connections across multiple API Gateway nodes (and across service instances internally), while the API Gateway handles API-specific concerns like JWT validation, per-user rate limiting, routing, and protocol translation.
Does an API Gateway add latency? It adds a small extra network hop (typically 1–5 ms for a well-tuned Envoy/Kong/NGINX gateway). In practice, that overhead is far smaller than the latency saved by consolidating TLS handshakes, auth checks, and multiple client round trips into one edge call.
When is an API Gateway overkill? If you are running a single monolith or two simple services behind one domain, a plain Layer 7 load balancer (like AWS ALB or NGINX) is simpler and avoids operating an extra gateway tier until you actually need API management or multi-service routing.
How is an API Gateway different from a Service Mesh? An API Gateway manages north-south traffic (external clients entering your system). A service mesh (like Istio or Linkerd) manages east-west traffic (internal service-to-service mTLS, retries, and observability inside the cluster).