Bird
Raised Fist0
Microservicessystem_design~7 mins

API Gateway pattern in Microservices - System Design Guide

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Problem Statement
When multiple microservices serve different parts of an application, clients must call each service separately. This leads to complex client logic, increased network calls, and difficulty managing cross-cutting concerns like authentication and rate limiting.
Solution
An API Gateway acts as a single entry point for all client requests. It routes requests to the appropriate microservices, aggregates responses if needed, and handles common tasks like authentication, logging, and throttling centrally. This simplifies client interactions and centralizes control.
Architecture
Client
API Gateway
┌─────────┐
Microservice 1

This diagram shows the client sending requests to the API Gateway, which handles authentication and rate limiting before routing requests to the appropriate microservices.

Trade-offs
✓ Pros
Simplifies client by providing a single endpoint for all services.
Centralizes cross-cutting concerns like authentication, logging, and rate limiting.
Enables response aggregation to reduce client network calls.
Allows independent evolution of backend services without impacting clients.
✗ Cons
Introduces a single point of failure if the gateway is not highly available.
Can become a performance bottleneck under heavy load without proper scaling.
Adds complexity to deployment and maintenance of the gateway component.
Use when you have multiple microservices and want to simplify client interactions, especially if clients are diverse (web, mobile) or you need centralized security and monitoring.
Avoid when your system has only a few services or very simple interactions, as the added gateway layer may increase latency and complexity unnecessarily.
Real World Examples
Netflix
Netflix uses an API Gateway to route client requests to various backend services and to handle authentication and request throttling centrally.
Amazon
Amazon employs API Gateways to provide a unified interface for its diverse microservices, simplifying client access and managing security policies.
Uber
Uber uses API Gateways to aggregate data from multiple microservices, reducing the number of client calls and improving mobile app performance.
Code Example
The before code shows the client calling multiple services directly, increasing complexity and network calls. The after code shows the client calling a single API Gateway endpoint, which aggregates data from multiple services and returns a combined response, simplifying the client logic.
Microservices
### Before: Client calls multiple services directly
import requests

def get_user_profile(user_id):
    user_resp = requests.get(f'http://user-service/users/{user_id}')
    orders_resp = requests.get(f'http://order-service/orders?user={user_id}')
    return {
        'user': user_resp.json(),
        'orders': orders_resp.json()
    }


### After: Client calls API Gateway once
import requests

def get_user_profile(user_id):
    resp = requests.get(f'http://api-gateway/profile/{user_id}')
    return resp.json()


# API Gateway routing example (simplified)
from flask import Flask, request, jsonify
import requests

app = Flask(__name__)

@app.route('/profile/<user_id>')
def profile(user_id):
    # Authentication and rate limiting would happen here
    user_resp = requests.get(f'http://user-service/users/{user_id}')
    orders_resp = requests.get(f'http://order-service/orders?user={user_id}')
    combined = {
        'user': user_resp.json(),
        'orders': orders_resp.json()
    }
    return jsonify(combined)
OutputSuccess
Alternatives
Client-side Aggregation
Clients call multiple services directly and aggregate responses themselves.
Use when: Choose when clients are trusted, have sufficient resources, and the number of services is small.
Backend for Frontend (BFF)
Separate gateways are created for different client types (e.g., mobile, web) to tailor APIs specifically.
Use when: Choose when different clients have very different needs and require customized APIs.
Summary
API Gateway provides a single entry point to multiple microservices, simplifying client interactions.
It centralizes cross-cutting concerns like authentication, logging, and rate limiting.
While it adds a layer of complexity, it improves maintainability and scalability for complex systems.

Practice

(1/5)
1. What is the primary role of an API Gateway in a microservices architecture?
easy
A. It acts as a single entry point to route requests to multiple microservices.
B. It stores all the data for the microservices.
C. It replaces the database in the system.
D. It directly manages the internal logic of each microservice.

Solution

  1. Step 1: Understand the role of API Gateway

    An API Gateway serves as a single entry point that routes client requests to the appropriate microservices.
  2. Step 2: Eliminate incorrect roles

    It does not store data, replace databases, or manage internal microservice logic; those are handled by other components.
  3. Final Answer:

    It acts as a single entry point to route requests to multiple microservices. -> Option A
  4. Quick Check:

    API Gateway = Single entry point [OK]
Hint: API Gateway routes requests, it does not store data [OK]
Common Mistakes:
  • Confusing API Gateway with database or service logic
  • Thinking API Gateway manages microservice internals
  • Assuming API Gateway stores data
2. Which of the following is the correct way to describe the API Gateway's function in handling client requests?
easy
A. API Gateway directly executes business logic for each microservice.
B. API Gateway replaces the need for microservices.
C. API Gateway stores client data permanently.
D. API Gateway routes requests, handles authentication, and aggregates responses.

Solution

  1. Step 1: Identify API Gateway responsibilities

    API Gateway routes requests, manages security like authentication, and can combine responses from multiple services.
  2. Step 2: Remove incorrect options

    It does not execute business logic itself, store data permanently, or replace microservices.
  3. Final Answer:

    API Gateway routes requests, handles authentication, and aggregates responses. -> Option D
  4. Quick Check:

    Routing + Security + Aggregation = API Gateway [OK]
Hint: API Gateway routes and secures, does not store data [OK]
Common Mistakes:
  • Thinking API Gateway runs business logic
  • Confusing API Gateway with data storage
  • Assuming API Gateway replaces microservices
3. Consider this simplified request flow: A client sends a request to the API Gateway, which then calls Service A and Service B. The API Gateway combines their responses and sends back a single response to the client. What is the main benefit of this approach?
medium
A. It increases the number of client requests to microservices.
B. It reduces the number of client requests by aggregating responses.
C. It forces clients to call each microservice separately.
D. It eliminates the need for microservices.

Solution

  1. Step 1: Analyze the request flow

    The API Gateway receives one client request and internally calls multiple services, then combines their responses.
  2. Step 2: Understand the benefit

    This reduces the number of requests the client must make, simplifying client logic and improving efficiency.
  3. Final Answer:

    It reduces the number of client requests by aggregating responses. -> Option B
  4. Quick Check:

    Response aggregation reduces client calls [OK]
Hint: API Gateway aggregates responses to reduce client calls [OK]
Common Mistakes:
  • Thinking client must call each service separately
  • Believing API Gateway increases client requests
  • Confusing aggregation with service removal
4. A developer implemented an API Gateway but notices that clients receive errors when calling multiple microservices through it. Which of the following is the most likely cause?
medium
A. The client is bypassing the API Gateway and calling microservices directly.
B. The microservices do not have any APIs.
C. The API Gateway is not properly routing requests to the correct microservices.
D. The API Gateway is storing all client data incorrectly.

Solution

  1. Step 1: Identify the error source

    If clients get errors when calling multiple services via the API Gateway, routing issues are a common cause.
  2. Step 2: Exclude other causes

    Microservices usually have APIs; clients bypassing the gateway would not cause errors through it; storing data is not the gateway's role.
  3. Final Answer:

    The API Gateway is not properly routing requests to the correct microservices. -> Option C
  4. Quick Check:

    Routing errors cause client failures [OK]
Hint: Check routing rules if clients get errors via API Gateway [OK]
Common Mistakes:
  • Blaming microservices for missing APIs
  • Assuming clients bypass the gateway
  • Thinking API Gateway stores client data
5. You are designing a system with multiple microservices and want to use an API Gateway. Which of the following is the best reason to include response aggregation in the API Gateway?
hard
A. To reduce client complexity by combining data from multiple services into one response.
B. To increase the number of network calls clients must make.
C. To allow clients to manage authentication for each microservice separately.
D. To store all microservice data centrally in the API Gateway.

Solution

  1. Step 1: Understand response aggregation purpose

    Response aggregation combines data from multiple microservices into a single response, simplifying client handling.
  2. Step 2: Evaluate other options

    Increasing network calls or forcing clients to manage authentication per service adds complexity; storing data centrally is not the gateway's role.
  3. Final Answer:

    To reduce client complexity by combining data from multiple services into one response. -> Option A
  4. Quick Check:

    Aggregation simplifies client responses [OK]
Hint: Aggregate responses to simplify client communication [OK]
Common Mistakes:
  • Thinking aggregation increases client calls
  • Assuming clients handle all authentications
  • Confusing API Gateway with data storage