System Design Fundamentals
Vote

0% completed

Usage of API gateway

Deciding Where the Request Goes

Reshaping the Request

Protecting the Backend

Running It as a Business

A Real Example

A microservices architecture has many small independent services, and managing the communication between all of them and every client gets complicated fast. A gateway is where that complexity goes.

There are twenty things people use one for. They fall into four groups.

The twenty uses of an API gateway grouped into deciding where a request goes, reshaping it, protecting the backend, and running the business
The twenty uses of an API gateway grouped into deciding where a request goes, reshaping it, protecting the backend, and running the business

Deciding Where the Request Goes

Request routing. Directing each incoming request to the appropriate backend service. In an e-commerce application with separate services for user management, product catalog and order processing, a request for product details is routed to the product catalog service, and a request to place an order goes to order processing.

Content-based routing. Routing based on the content of the request rather than only the path: headers, body, or query parameters. An API handling image, video and document uploads can have the gateway inspect the Content-Type header and route each upload to a service specialized for that media type.

Service discovery integration. In an environment where services scale up and down, such as Kubernetes, the gateway integrates with a discovery tool like Consul or Eureka so it always routes to instances that currently exist and are healthy, with no manual reconfiguration.

A/B testing and canary releases. Directing a subset of traffic to a different backend version. Deploying a new recommendation service, the gateway can send a small percentage of requests to it while the majority stay on the stable version, which lets you monitor the new version's behavior before rolling it out to everyone.

Reshaping the Request

Aggregation of multiple services. Combining responses from several backends into one response. A mobile app needing profile information, recent orders and recommendations on one screen does not have to call three services. The gateway fetches from the user service, the order service and the recommendation service, then returns a single unified response.

Without aggregation the client makes three calls and stitches the results together, and with it the gateway makes them and returns one response
Without aggregation the client makes three calls and stitches the results together, and with it the gateway makes them and returns one response

Protocol translation. Converting between the protocols the client and the backends speak. A client may send HTTP or HTTPS while some backends use WebSockets or gRPC, and the gateway performs the conversion so both sides work unchanged.

Transformation of requests and responses. Changing the data format or structure. If a client expects JSON but a backend returns XML, the gateway converts the XML response into JSON before sending it on, so the backend does not have to change.

Localization and internationalization. Adapting responses to the client's locale, detected from request headers or parameters, so dates, numbers and currencies match regional expectations, or so content comes from a region-specific service.

Reducing client complexity. Moving multi-step work to the server side. A registration flow that must create an account, send a welcome email and log the event can be one gateway endpoint that orchestrates all three behind the scenes, instead of three client calls.

Protecting the Backend

Security enforcement. Before a request reaches any backend service, the gateway can verify the user's authentication token, check that they have permission for the data they are asking for, and limit how many requests they are making. Who are you, what may you access, and how often are you asking.

Rate limiting and throttling. Controlling how many requests a client may make in a given time frame, which protects the backends from being overwhelmed. A public API might allow a maximum of 100 requests per minute per user and temporarily block further requests beyond that.

Circuit breaker pattern. Detecting that a backend is failing and stopping requests to it. If the order processing service becomes unresponsive, the gateway trips a circuit breaker: it stops sending new requests there for a period, giving the service time to recover, and can return fallback responses in the meantime.

While the circuit is open the gateway stops calling the failing service and answers with a fallback, then tries again after a delay
While the circuit is open the gateway stops calling the failing service and answers with a fallback, then tries again after a delay

SSL termination. Handling SSL/TLS encryption and decryption at the gateway instead of in every service. Clients connect to the gateway over HTTPS, the gateway forwards over HTTP or a secure internal network, and certificate management stops being a per-service problem.

Policy enforcement. Applying organizational rules to all traffic consistently. If every request must carry certain headers or have specific fields validated, the gateway validates each request before it reaches a backend and rejects any that do not comply.

Running It as a Business

Load balancing. Distributing requests across multiple instances of a backend service so no single instance becomes a bottleneck.

Caching responses. Storing frequently requested data so the gateway can answer without querying the backend every time. Product catalog data that changes rarely is the classic case, and serving it from cache cuts both latency and backend load.

Monitoring and logging. Recording request paths, response times and error rates, which is what you use to find performance problems, understand usage patterns and troubleshoot.

API versioning. Managing multiple versions so older clients keep working. The gateway routes requests to different backend versions based on the API version in the request, which is what lets you ship changes without breaking an app that has not been updated.

API monetization. Selling access by tier. A company offering a weather API in free, basic and premium tiers can have the gateway handle authentication, track usage per subscription plan, and integrate with billing systems.

Multi-tenancy support. Serving many customers from one infrastructure. A SaaS platform's gateway distinguishes tenants by headers or authentication tokens and applies tenant-specific routing, rate limits, logging and security policies, keeping each one isolated.

A Real Example

Netflix runs a large number of microservices covering everything from user profiles to streaming content. Its API Gateway manages the interactions between clients like smart TVs and mobile apps and that whole set of backend services, which is how it stays scalable and reliable under very heavy traffic.

💡 Do not list gateway features in an interview. Pick the one the question needs. "The mobile client is making six calls to render one screen, so I would aggregate at the gateway" answers a real problem. Reciting twenty capabilities answers nothing.

Key takeaway: A gateway decides where requests go through routing, content-based routing, service discovery and canary traffic splits. It reshapes them through aggregation, protocol translation, format transformation, localization and orchestration that reduces client complexity. It protects the backend through security enforcement, rate limiting, circuit breaking, SSL termination and policy enforcement. And it runs the operational and commercial side through load balancing, caching, monitoring, versioning, monetization and multi-tenancy.

The next lesson, Advantages and Disadvantages of Using API Gateway, weighs all of that against what it costs.

Ricardo Franco

Ricardo Franco

· 3 years ago

If the API Gateway is the router, why do clients need service discovery to access the services?

Show 1 reply
Ricardo Franco

Ricardo Franco

· 3 years ago

Could you explain API Versioning in more detail? Would it mean the API Gateway routes the request to a different pool of microservices based on the version?

Show 1 reply
Oui Key

Oui Key

· 2 years ago

Isn't API gateway a basically microservice in and of itself that send requests to all these other services with custom logic?

Ricardo Franco

Ricardo Franco

· 3 years ago

The API gateway can be used to implement a circuit breaker pattern, which can help to prevent a single failed microservice from bringing down the entire system

How a single failed microservice can bring down the entire system? Is it in the case of Service Aggregation?

Show 3 replies
S

Shishir

· 2 years ago

Is there some difference between the two?

Show 1 reply
S

Shishir

· 2 years ago

The first chapter under "API Gateway" section clearly calls out that an API Gateway and a Load Balancer are different -

"An API gateway and a load balancer are both types of infrastructure that can be used in a computer network to manage incoming requests and enhance the performance of a system. However, they work in different ways and serve different purposes."

However, this chapter lists "Load Balancing" as one of the uses for an API Gateway.

Can you please elaborate on this? Does this mean that an API Gateway is a Load Balancer with routing, rate limiting, business logic, and other capabilities?

Show 4 replies
S

shivangkumarjha

· 7 months ago

Suppose the system has both a load balancer to distribute the load to different servers, and an api gateway to route API requests to the suitable backend system. Typically which sits in front for the client - the LB or the API Gateway.

Or having API gateway obviates LB completely ?

Show 1 reply
Vaishnavi Ainapure

Vaishnavi Ainapure

· 6 months ago

Hi,

I have following couple of questions

How does an API Gateway perform load balancing? Why do we need dedicated Load Balancers if API Gateways can balance load? What is difference between Azure Application Gateway or an API Gateway? What are Internal Load Balancers (ILBs) do Azure API Gateway and App Gateway use them internally

Show 1 reply
Alan Esparza

Alan Esparza

· 6 months ago

thanks for all this info maybe code samples help understanding the methods

Show 1 reply

On This Page

Deciding Where the Request Goes

Reshaping the Request

Protecting the Backend

Running It as a Business

A Real Example