Skip to content
Alnashiri.dev

API Gateway in Microservices: Request Flow & Examples

By Khaled Abdh Ali Al-Nashery
Updated:
7 min read
Table of Contents+

In a monolithic backend, web and mobile clients typically talk to a single entry address. Once you adopt microservices—splitting the platform into User, Catalog, Cart, Order, Payment, and Notification services—letting clients call every internal service directly exposes internal routes, forces duplicated authentication across services, breaks clients when internal topologies change, and triggers excessive network round trips.

An API Gateway—the edge entry pattern cataloged in Chris Richardson’s API Gateway guide—solves this by acting as a single, API-aware entry layer between external clients and internal services. It terminates TLS, enforces edge authentication and rate limits, routes paths to healthy backends via service discovery, and hides internal refactoring behind stable public endpoints.

Core Rule: An API Gateway is the front door of a microservices system, not a home for domain business rules, database access, or service-to-service workflows.

How API Gateway Request Flow Works

A gateway receives incoming external traffic (north-south traffic), validates edge policies once, routes to an internal backend service, and returns the response while collecting telemetry.

API Gateway in microservices architecture diagram
Clients call one API Gateway, which routes each request to the owning microservice

Every gateway request typically passes through a deterministic pipeline:

Client -> TLS Termination -> Auth & Token Check -> Rate Limit -> Route Match (/api/orders) -> Order Service
API Gateway request flow in microservices
Step-by-step request path through authentication, rate limits, and backend routing

Notice how cleanly that separates edge policy from domain behavior:

  • The gateway verifies JWT signatures, enforces 120 req/min quotas, injects a trace correlation ID, and forwards POST /api/orders to Order Service.
  • Order Service still checks resource-level permissions (can this user modify this order?) and executes order validation inside its own domain and private database boundary.

Core Responsibilities (And What Belongs Elsewhere)

ResponsibilityKeep in API GatewayKeep Inside Microservices
Routing & versioningPath/header routing (/v1/orders, /v2/orders)Internal controller & handler logic
SecurityTLS termination, JWT/API-key verificationDomain authorization & ownership checks
Traffic protectionRate limiting, quotas, IP throttlingDomain invariants & concurrency locks
ObservabilityAccess logs, edge latency, trace ID injectionService-level spans & business metrics
Edge response shapingLight header normalization, public read cachingOrder totals, discounts, payment approvals

The “God Gateway” Trap and Backend for Frontends (BFF)

The fastest way to ruin a microservices architecture is letting teams treat the API Gateway as a convenient dumping ground for cross-domain pricing rules, complex response joins, and screen-specific formatting.

Bad API Gateway design with too much business logic
Anti-pattern: piling pricing, discounts, and domain rules into the gateway turns it into a central bottleneck

When mobile, web, and partner teams all need conflicting payload aggregations, one shared gateway turns into a monolith in the middle—where every UI tweak risks breaking unrelated clients. As documented in Sam Newman’s Backend for Frontends (BFF) pattern, Azure Architecture Center’s BFF guide, and Microsoft’s gateway design guidance, teams solve this by splitting edge aggregation into client-owned BFFs (mobile-bff, web-bff) behind shared TLS/rate-limiting.

Practitioner warning: Keep each BFF owned by its client team and resist pulling UI mapping code into a shared bff-common package—shared BFF libraries silently reintroduce cross-team lockstep deployments.

E-Commerce Routing & Direct Calls Comparison

In an e-commerce setup, clients call clean resource endpoints while backend teams refactor freely underneath:

  • GET /api/products/123 → Product Service
  • POST /api/orders → Order Service (authenticated, rate-limited at the edge)
  • POST /api/payments → Payment Service
E-commerce microservices API Gateway routing example
Client traffic routed to Product, Order, Payment, and Inventory services behind a stable edge

Wait before adding a gateway prematurely, however. Compare it directly against direct client calls (as examined in Microservices vs Monolithic Architecture):

API Gateway vs direct client-to-service calls
Direct client calls couple consumers to internal hosts; an API Gateway centralizes edge control
Comparison DimensionDirect Client CallsAPI Gateway
Client couplingClients track every backend URL & auth schemeClients rely on one stable public contract
Attack surfaceMany internal endpoints exposed publiclyOnly the gateway edge sits public-facing
Best fit1–2 services, internal tools, early MVPsMultiple services, external apps, shared rate/auth policies

API Gateway vs Load Balancer, Service Discovery & Service Mesh

In production, gateways rarely replace load balancers, service discovery, or service meshes—each sits at a different layer of traffic:

Clients -> L4/L7 Load Balancer -> API Gateway Cluster -> Internal Services (Mesh / Discovery)
Infrastructure LayerPrimary TrafficCore Responsibility
Load BalancerClient → Gateway or Service replicasDistributes connections across healthy nodes
Reverse ProxyEdge / HTTP forwardingGeneral proxying, caching, TLS termination
API GatewayNorth-South (external → services)API routing, JWT auth, rate limits, versioning
Service DiscoveryDynamic instance lookupTracks healthy container/VM endpoints at runtime
Service MeshEast-West (service → service)Mutual TLS (mTLS), internal traffic policies, internal retries

Popular implementations span NGINX/NGINX Plus, Kong Gateway, Apache APISIX, Tyk, Envoy-based gateways, Spring Cloud Gateway, Ocelot (.NET), AWS API Gateway, and Azure API Management. Choose your architecture boundaries before picking a vendor.

Preventing SPOFs, Bottlenecks, and Retry Storms

A classic concern raised on Stack Overflow—both in API Gateway vs. no gateway and why gateways are recommended—is whether routing all traffic through one gateway introduces a Single Point of Failure (SPOF).

  1. Physical availability: Running an active-active cluster of stateless gateway replicas behind a redundant load balancer makes the gateway no more a hardware SPOF than any edge load balancer. Store tokens/sessions outside gateway RAM.
  2. Logical cascading failures (the real hazard): If a downstream service hangs and the gateway lacks strict timeouts, circuit breakers, and bounded retries with backoff and jitter, stalled requests tie up gateway worker threads until every healthy client route collapses.
  3. Multiplicative retry storms: If the gateway retries 3 times and two downstream services each retry 3 times, a single failing checkout spawns 3 × 3 × 3 = 27 upstream attempts.

In a controlled local simulation sending 100 requests against a severely degraded downstream dependency (85% failure rate), unbounded per-hop retries amplified traffic to 460 downstream calls, whereas capping retries at the edge behind a circuit breaker kept downstream load to 10 calls while fast-failing 95 requests:

Scenario: 100 incoming requests, degraded downstream (85% failure rate)
  Unbounded per-hop retries (3x3x3): downstream_calls=460, completed=79
  Edge-only retry + circuit breaker: downstream_calls=10, completed=0, fast_failed=95

Keep gateway policies declarative in Git—never hand-edited in a dashboard or mixed with business code—and publish edge contracts with OpenAPI (Microservices Documentation Tools):

routes:
  - id: orders-api
    match: /api/orders/**
    upstream: http://order-service.internal:8080
    timeout_ms: 2500
    retry:
      attempts: 2 # safe only on idempotent GET/HEAD or Idempotency-Key operations
      backoff: exponential-jitter
    rate_limit:
      requests_per_minute: 120
      key: jwt.sub

When You May Not Need an API Gateway

Skip a standalone gateway when operating a monolith, an early MVP, or a single internal backend. Adding an extra network hop, routing config, and certificate surface without multiple client consumers or service domains creates complexity without return.

Frequently Asked Questions

Is an API Gateway a Single Point of Failure?

Only if deployed as a single instance without failover or resilience controls. Clustered stateless gateway instances behind a load balancer—paired with strict upstream timeouts and circuit breakers—eliminate both hardware SPOFs and cascading thread exhaustion.

Should Business Logic Live Inside an API Gateway?

No. Keep pricing, order state transitions, inventory rules, and database writes inside owning microservices. Limit the gateway to routing, authentication verification, rate limits, TLS termination, and light request/response shaping.

When Should You Use a BFF Instead of One Shared API Gateway?

Use Backend for Frontends (BFF) when distinct clients—such as mobile apps versus desktop admin portals—require substantially different payload aggregations or latency optimizations that would otherwise bloat a single shared gateway.

How Do You Stop an API Gateway From Becoming a Bottleneck?

Offload heavy orchestration and domain processing to backend services, use asynchronous workflows for non-blocking tasks, cache safe public reads selectively, monitor p95/p99 edge latency, and scale gateway nodes horizontally.

What Is the Difference Between an API Gateway and a Service Mesh?

An API Gateway manages north-south traffic entering from external clients, while a service mesh governs east-west service-to-service communication (mTLS identity, internal telemetry, and internal traffic rules). Larger platforms frequently use both.

Conclusion

An API Gateway gives external clients a stable, protected front door while allowing microservices teams to split, refactor, and scale internal services safely—for a wider view of topology, see the Microservices Architecture Diagram guide. Keep your gateway thin, stateless, declarative in Git, and hardened with timeouts and circuit breakers, and add it only when client and service complexity truly demands an edge layer.