SDSystem DesignConcepts to case studies
System DesignDSA
x
0/311
Part 1: Foundations
Part 2: APIs and Communication
Part 3: Caching
Part 4: Data and Storage
Part 5: Architecture
  • Service Discovery
  • API Gateway Pattern
  • Backend for Frontend (BFF)
  • Sidecar Pattern
  • Circuit Breaker
  • Bulkhead
  • Strangler Fig
  • Service Mesh
  • Database per Service
  • Timeouts and Deadlines
  • API Composition
  • Anti-Corruption Layer
  • Ambassador Pattern
  • Idempotent Consumer and Inbox Pattern
Part 6: Distributed Systems
Part 7: Advanced Data Topics
Part 8: Operations and Security
Part 9: Estimation and Interview Method
Part 10: Case Studies
System Design/Architecture/Microservices Patterns

API Gateway Pattern

One front door for all clients that routes, secures and limits requests to the services behind it.

⏱ 14 min readIntermediateMust KnowInterview FavouriteHas visualizer
SummaryConceptReal-Life ExampleWhy?Where?How It WorksStepsKey TermsPros & ConsMistakesReal WorldRead NextInterview Q&ACheat-Sheet

01Quick Summary

An API gateway is one front door for all your backend services. Clients talk to the gateway, and the gateway routes each request to the right service.

  • Clients know one address, not the address of every microservice.
  • The gateway handles shared jobs in one place: login checks, rate limits, TLS, logging, caching.
  • It can also combine several service answers into one response, which saves round trips.

02Concept: What is it?

With microservices, a single screen in an app might need data from Users, Orders, Payments and Shipping. If the app calls all of them directly it must know every address, make many slow calls over the internet, and every service must be exposed publicly and handle login, limits and HTTPS by itself.

The API Gateway pattern puts one server in front of all the services. It is the single entry point for outside traffic (sometimes called "north-south" traffic: from outside to inside). Inside, services talk to each other on a fast private network.

A gateway is a reverse proxy with extra skills. It looks at the request path, header or method, picks the target service, applies shared rules, forwards the call and returns the answer.

Without and with a gateway
No gateway
πŸ“±Clientknows 4 addresses
↓
↓
↓
↓
πŸ‘€Users
πŸ“¦Orders
πŸ’³Pay
🚚Ship
With a gateway
πŸ“±Clientknows 1 address
↓
πŸšͺAPI Gatewayauth, limits, routing
↓
↓
↓
↓
πŸ‘€Users
πŸ“¦Orders
πŸ’³Pay
🚚Ship
The gateway hides the inside of the system and gives clients one simple door.
🧠Gateway vs load balancer
A load balancer spreads requests across copies of the same service. A gateway looks inside the request and decides which service should answer, and adds features like authentication. Many systems use both: a load balancer in front of several gateway copies.

03Real-Life Example

🍡The Reception Desk of a Big Office Building
A big building has many companies inside. Visitors do not wander the corridors. They go to the reception desk. The receptionist checks the visitor's ID, writes the visit in a log, turns away anyone not allowed, and then sends the visitor to the right floor. If a visitor needs three companies, the receptionist can even arrange all three meetings at once. The companies inside never need to check IDs at their own doors, and their office numbers can change without the visitors noticing.
Office building
API gateway
Reception desk
The gateway, a single public entry
Checking the visitor’s ID
Authentication (token check)
Turning away too many visitors
Rate limiting
Sending the visitor to the right floor
Routing by path, host or header
Arranging three meetings at once
Aggregation of several services
The visit log
Central logging and metrics
Companies change office number
Services move, and clients do not notice
Reception closed
Gateway outage: nobody gets in
The life of one request
πŸ“±RequestGET /orders/42
→↓
πŸ”Checktoken and limit
→↓
🧭Routeto Orders service
→↓
πŸ“¦Servicedoes the work
←response

04Why Do We Need It?

πŸšͺOne entry point
Clients use a single stable address, while the services behind can move, split or be rewritten.
πŸ”Security once
Check tokens, block bad traffic and end TLS in one place instead of in every service.
🧩Fewer round trips
Combine calls to several services, over the fast internal network, into one response.
🚦Protect the backend
Rate limits, quotas and request size limits stop abuse before it reaches the services.
πŸ“ŠCentral view
Logs, metrics and traces for all incoming traffic come from one place.
πŸ”€Safe change
Route 5% of traffic to a new version, or send old URLs to new services, without touching clients.
One smart front door means clients stay simple, services stay private, and shared rules live in one place.

05Where Do We Use It?

🧱Microservices
The standard way to expose many internal services to web and mobile apps.
🌍Public APIs
Developer platforms use a gateway for API keys, quotas and usage billing.
🏒Company internal APIs
One catalog and one set of access rules across teams.
Ξ»Serverless
Services like AWS API Gateway put an HTTPS front on functions.
πŸ§“Legacy migration
A gateway can send some paths to the old monolith and some to new services (see Strangler Fig).
🀝Partners
Give outside companies a controlled, documented, limited way in.

06Types / Parts / How It Works

What a gateway usually does

JobWhat it meansExample
RoutingMatch path, host or header and forward to a service/orders/* to the Orders service
AuthenticationVerify the token or API key before the call goes inCheck a JWT signature and expiry
Authorization (coarse)Allow or deny by role or scopeOnly admins may use /admin/*
Rate limiting and quotasLimit calls per client100 requests per minute per key
TLS terminationHandle HTTPS at the edge, plain or mTLS insideOne certificate for the domain
AggregationCall several services and merge the resultsHome screen = users + orders + offers
Protocol translationConvert between stylesPublic REST in, internal gRPC out
CachingKeep common responses for a short timeProduct list for 30 seconds
ResilienceTimeouts, retries and circuit breakers toward servicesStop calling a failing service
ObservabilityLogs, metrics and a request ID on every callTrace ID added at the edge

Where the gateway sits

A typical request path
🌍Internet
→↓
πŸ›‘οΈCDN / WAFedge filtering
→↓
βš–οΈLoad balancer
→↓
πŸšͺAPI gatewaysseveral copies
→↓
🧩Services
Edge Gateway Private services
The gateway is stateless, so you can run many copies behind a load balancer.

Common products

KindExamples
Managed cloudAmazon API Gateway, Azure API Management, Google Cloud API Gateway / Apigee
Open sourceKong, NGINX, Envoy-based gateways, Traefik, Spring Cloud Gateway, Tyk
KubernetesIngress controllers and the Gateway API, which is the newer standard
VisualizerOne screen, many services: direct calls vs a gatewaySwitch between calling services directly and using the gateway. Increase the number of services and the network delay. Turn shared features on and off, then crash the gateway.
How does the app reach the services?
How do the calls relate?
Shared features every request needs
πŸ“±Appneeds 4 services
→↓4 calls on the internet
πŸ‘€Users2 features coded here
public
πŸ“¦Orders2 features coded here
public
πŸ’³Payments2 features coded here
public
🚚Shipping2 features coded here
public
Screen load time
560 ms
4 slow round trips
Public addresses
4
open to the internet
Feature copies
8
2 features x 4 places
The client calls 4 services one after another, because each answer is needed for the next call. Every call crosses the slow client network (120 ms), so the screen takes 560 ms.

A simplified model: each service takes 20 ms, an internal hop takes 2 ms, the gateway adds 5 ms, and the client network round trip is the slider. Real numbers depend on your system.

07How to Use It / Steps / Implementation

Introducing a gateway

  1. 1
    List the public needs
    Which endpoints must clients reach? Keep internal-only services off the public list.
  2. 2
    Choose a product
    Managed gateway for speed, or an open-source one if you need control and plug-ins.
  3. 3
    Define routes
    Map paths or hosts to services, and use service discovery so the targets can move.
  4. 4
    Move shared rules to the edge
    Token checks, rate limits, request size limits, CORS and logging go in the gateway.
  5. 5
    Keep business logic out
    The gateway routes and protects. Pricing rules and workflows stay inside the services.
  6. 6
    Set timeouts and retries
    Never wait forever on a slow service. Retry only calls that are safe to repeat (idempotent).
  7. 7
    Run it highly available
    Several stateless copies behind a load balancer, in more than one zone.
  8. 8
    Version the APIs
    Route /v1 and /v2 to different services, so you can change them without breaking old clients.
πŸ’‘Services still verify
Do not let the gateway be your only guard. Internal services should still check who is calling (for example, with a signed token or mTLS), in case something reaches them without passing the gateway.
⚠️The thick gateway trap
If teams keep adding business rules to the gateway, it becomes a hidden monolith that every change must go through. Keep it thin.

08Key Terms to Know

TermMeaning in easy words
API gatewayA single entry point that routes outside requests to backend services
Reverse proxyA server that forwards client requests to other servers. A gateway is a reverse proxy with extra features.
RoutingChoosing the target service from the path, host, header or method
AggregationCalling several services and merging their answers into one response
TLS terminationEnding the HTTPS connection at the gateway
Rate limitingLimiting how many requests a client can send in a time window
EdgeThe outer boundary of your system, where outside traffic enters
North-south trafficTraffic between outside clients and your system. East-west means service to service.
Cross-cutting concernA need shared by many services, like auth, logging or limits
Protocol translationConverting one protocol or format to another (REST to gRPC)
IngressIn Kubernetes, the rules and component that let outside traffic reach services

09Pros, Cons and Trade-offs

βœ… Pros
  • Clients use one simple, stable address
  • Shared features written and fixed once
  • Internal services stay private
  • Fewer slow client round trips with aggregation
  • Easier migrations, versioning and canary releases
⚠️ Cons
  • A single point of failure if not replicated
  • An extra network hop adds a little latency
  • Can become a bottleneck or a thick, risky monolith
  • Another component to deploy, secure and monitor
  • A bad config change can break every API at once

Trade-offs

ChoiceWe gainWe lose
One gateway for everythingSimple, one place for rulesShared risk and a central team that can slow others down
Several gateways (per client or per domain)Independent teams and smaller blast radiusDuplicated rules and more to run (see Backend for Frontend)
Aggregation in the gatewayFewer client callsGateway grows business logic and becomes harder to change
Auth only at the gatewaySimple servicesA mistake or bypass exposes everything inside
Managed gatewayNo servers to run, scales by itselfCost per request and less control
Self-hosted gatewayFull control and plug-insYou run, patch and scale it

10Common Problems and Mistakes

Common mistakes

  1. One gateway instance. It is the front door. If it fails, the system looks down.
  2. Business logic in the gateway. It becomes a bottleneck for every team.
  3. No timeouts. A slow service ties up gateway connections and then everything slows down.
  4. Only the gateway checks auth. Internal services trust anything that reaches them.
  5. Too much aggregation. One slow service makes the whole combined call slow, and a failing one can break the response.
  6. Unlimited retries. The gateway multiplies traffic against a service that is already struggling.
  7. Unreviewed config changes. A wrong route or rule applies to all traffic immediately.

Things to watch

🐌Added latency
Each hop costs time. Keep gateway work light, and measure it.
πŸ’₯Overload
Large uploads or streaming through the gateway can exhaust it. Use direct signed uploads for big files.
🧯Partial failure
When aggregating, decide what to do if one service fails: fail all, or return the rest with a gap.
πŸ”—Coupling
If every API change needs a gateway change, the gateway slows everyone down. Prefer automatic route discovery.

11Real-World Examples

🎬Netflix
Built Zuul, and later Spring Cloud Gateway based tooling, as the edge for its device apps.
☁️Amazon API Gateway
A managed gateway that fronts Lambda functions and HTTP services with auth, throttling and usage plans.
🦍Kong
An open-source gateway built on NGINX, with a large plug-in system.
🏦Banks and partners
Expose limited, audited APIs to fintech partners through a gateway with strict quotas.
☸️Kubernetes
Ingress controllers and the Gateway API route outside traffic to Services inside a cluster.
πŸ›’Online retail
Product, cart and checkout services all appear under a single domain, such as api.shop.com.
πŸ“Note
Product names and features change over time. Check the vendor documentation for current limits.
Mini case: a shop home screen
πŸ“±PhoneGET /home
→↓1 call
πŸšͺGatewayauth, then aggregate
→↓3 calls
πŸ‘€Users
πŸ“¦Orders
🏷️Offers
One call from the phone. Three quick calls on the private network.

12Related Topics to Read Next

Proxy vs Reverse Proxy→

A gateway is a reverse proxy with extra jobs.

Backend for Frontend (BFF)β†’

A gateway per type of client, to shape data for each one.

Service Discovery→

How the gateway finds the live instances of each service.

Rate Limiting→

One of the main jobs done at the gateway.

What are Load Balancers?β†’

Run several gateway copies behind one.

Microservices→

The architecture that makes a gateway useful.

Strangler Fig→

A gateway can move traffic from an old system to a new one step by step.

13Interview Questions with Short Answers

14Quick Revision Cheat-Sheet

  • βœ”What: one front door that routes outside requests to the right backend service.
  • βœ”Jobs: routing, auth, rate limits, TLS, logging, caching, aggregation, protocol translation.
  • βœ”Not: a load balancer (copies of one service) and not a place for business logic.
  • βœ”Wins: simple clients, private services, shared rules in one place, fewer client round trips.
  • βœ”Risks: single point of failure, extra hop, thick gateway, bad config hitting everything.
  • βœ”Run it: stateless, several copies, behind a load balancer, with timeouts and limited retries.
  • βœ”Tools: Kong, NGINX, Envoy, Spring Cloud Gateway, Amazon API Gateway, Azure APIM, Apigee.
  • βœ”One line: β€œOne smart front door, so clients stay simple and services stay safe.”
← Previous
Service Discovery
Next β†’
Backend for Frontend (BFF)