Home CS Fundamentals API Gateway: Architecture and Patterns for Scalable Systems
Intermediate 3 min · July 13, 2026

API Gateway: Architecture and Patterns for Scalable Systems

Learn API Gateway architecture, patterns, and best practices.

N
Naren Founder & Principal Engineer

20+ years shipping production systems from the metal up. Drawn from code that ran under real load.

Follow
Production
production tested
July 13, 2026
last updated
2,165
articles · all by Naren
Before you start⏱ 15-20 min read
  • Basic understanding of microservices architecture
  • Familiarity with HTTP and REST APIs
  • Experience with command line and configuration files
 ● Production Incident 🔎 Debug Guide ⚙ Triage Commands
Quick Answer
  • An API Gateway is a single entry point for client requests, routing them to appropriate microservices.
  • It handles cross-cutting concerns like authentication, rate limiting, and request transformation.
  • Common patterns include Gateway Routing, Gateway Aggregation, and Gateway Offloading.
  • It improves security, simplifies client code, and enables centralized monitoring.
✦ Definition~90s read
What is API Gateway?

An API Gateway is a server that acts as a single entry point for client requests, handling routing, authentication, rate limiting, and other cross-cutting concerns in a microservices architecture.

Think of an API Gateway as a receptionist in a large office building.
Plain-English First

Think of an API Gateway as a receptionist in a large office building. Instead of visitors wandering around to find the right department, they go to the receptionist who directs them to the correct office. The receptionist also checks IDs (authentication), limits how many visitors can enter (rate limiting), and can combine information from multiple offices into one report (aggregation).

In modern microservices architectures, clients often need to interact with multiple services to complete a single task. Without a central entry point, clients must know the addresses of each service, handle authentication separately, and manage complex communication patterns. This leads to tight coupling, increased latency, and security vulnerabilities.

An API Gateway solves these problems by acting as a reverse proxy that sits between clients and backend services. It provides a unified interface for routing requests, enforcing security policies, and transforming protocols. For example, a mobile app might send a single HTTP request to the gateway, which then fans out to several microservices, aggregates the responses, and returns a single payload.

This article dives deep into API Gateway architecture, common patterns, and real-world best practices. You'll learn how to design a gateway that scales, handles failures gracefully, and simplifies client development. We'll also explore a production incident where a misconfigured gateway caused a major outage, and how to debug such issues in production.

What is an API Gateway?

An API Gateway is a server that acts as a single entry point for all client requests in a microservices architecture. It handles request routing, composition, and protocol translation. Clients interact with the gateway instead of directly calling individual services. This decouples the client from the backend, allowing services to evolve independently.

Key responsibilities include
  • Routing: Forward requests to the appropriate service based on URL path, headers, or other criteria.
  • Authentication: Verify tokens, API keys, or other credentials before forwarding.
  • Rate Limiting: Control the number of requests from a client to prevent abuse.
  • Load Balancing: Distribute requests across multiple instances of a service.
  • Caching: Store responses to reduce load on backend services.
  • Monitoring: Collect metrics and logs for all traffic.

Popular API Gateway implementations include Kong, AWS API Gateway, NGINX, and Envoy. Each offers different features and trade-offs.

nginx-gateway.confBASH
1
2
3
4
5
6
7
8
9
10
server {
    listen 80;
    location /api/users/ {
        proxy_pass http://user-service/;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    }
    location /api/orders/ {
        proxy_pass http://order-service/;
    }
}
🔥Gateway vs. Load Balancer
📊 Production Insight
Always configure the gateway to forward the original client IP using headers like X-Forwarded-For, especially when behind load balancers.
🎯 Key Takeaway
An API Gateway centralizes cross-cutting concerns, simplifying client code and improving security.

API Gateway Patterns: Routing

The most basic pattern is Gateway Routing, where the gateway acts as a reverse proxy. It inspects the incoming request and forwards it to the appropriate service based on the URL path, method, or headers. This pattern is simple to implement and works well for CRUD-based services.

Example: A request to /api/users/123 is routed to the user service, while /api/orders/456 goes to the order service.

Implementation considerations
  • Use path prefixes to separate services (e.g., /api/users, /api/orders).
  • Support versioning via URL (e.g., /v1/users) or headers.
  • Handle service discovery dynamically if services scale up/down.

When to use: When services have distinct responsibilities and clients need a unified API.

kong-routing.ymlBASH
1
2
3
4
5
6
7
8
9
10
11
12
13
services:
  - name: user-service
    url: http://user-service:8080
    routes:
      - name: user-route
        paths:
          - /api/users
  - name: order-service
    url: http://order-service:8080
    routes:
      - name: order-route
        paths:
          - /api/orders
💡Path Design
📊 Production Insight
Use a service mesh or DNS-based service discovery to avoid hardcoding service URLs in the gateway configuration.
🎯 Key Takeaway
Gateway Routing is the simplest pattern, ideal for separating concerns with clear path mapping.

API Gateway Patterns: Aggregation

In the Gateway Aggregation pattern, the gateway combines responses from multiple services into a single response. This reduces the number of client-server round trips and simplifies client logic. For example, a dashboard page might need user details, recent orders, and notifications. The gateway can fetch all three in parallel and merge the results.

Implementation
  • Use asynchronous calls (e.g., async/await in Node.js) to fetch data concurrently.
  • Handle partial failures gracefully (e.g., return a default value if one service fails).
  • Consider using GraphQL for flexible aggregation.
Trade-offs
  • Increases gateway complexity and latency (though parallel calls mitigate this).
  • Can become a bottleneck if not scaled properly.

When to use: When clients need data from multiple services for a single view.

aggregation.jsBASH
1
2
3
4
5
6
7
8
9
10
11
12
13
14
const express = require('express');
const app = express();
app.get('/dashboard/:userId', async (req, res) => {
  const [user, orders, notifications] = await Promise.all([
    fetch(`http://user-service/users/${req.params.userId}`),
    fetch(`http://order-service/orders?userId=${req.params.userId}`),
    fetch(`http://notification-service/notifications?userId=${req.params.userId}`)
  ]);
  res.json({
    user: await user.json(),
    orders: await orders.json(),
    notifications: await notifications.json()
  });
});
⚠ Aggregation Pitfall
📊 Production Insight
Implement circuit breakers for each backend call to prevent a slow service from degrading the entire aggregation.
🎯 Key Takeaway
Gateway Aggregation reduces client round trips but adds complexity; use it judiciously.

API Gateway Patterns: Offloading

The Gateway Offloading pattern moves common functionality from individual services to the gateway. This includes authentication, SSL termination, rate limiting, and logging. By centralizing these concerns, services can focus on business logic.

Examples
  • SSL Termination: The gateway handles HTTPS, and internal services communicate over HTTP.
  • Authentication: The gateway validates JWT tokens and passes user info via headers.
  • Rate Limiting: The gateway enforces limits before requests reach services.
Benefits
  • Reduces duplication across services.
  • Simplifies service code.
  • Centralized security policies.
Drawbacks
  • Gateway becomes a single point of failure if not highly available.
  • Can become a performance bottleneck.

When to use: When multiple services share the same cross-cutting concerns.

kong-offloading.ymlBASH
1
2
3
4
5
6
7
8
9
10
11
plugins:
  - name: jwt
    service: user-service
    config:
      secret: my-secret
      claims_to_verify: ["exp", "nbf"]
  - name: rate-limiting
    service: order-service
    config:
      minute: 100
      policy: local
🔥Offloading vs. Sidecar
📊 Production Insight
Always enable health checks for the gateway itself and run multiple instances behind a load balancer to avoid single points of failure.
🎯 Key Takeaway
Gateway Offloading centralizes cross-cutting concerns, reducing service complexity but increasing gateway responsibility.

API Gateway Patterns: Circuit Breaker and Retry

The Circuit Breaker pattern prevents cascading failures by stopping requests to a failing service. The gateway monitors failures and opens the circuit after a threshold, returning a fallback response. After a timeout, it allows a few requests to test if the service recovered.

Retry pattern automatically retries failed requests, often with exponential backoff. However, retries can amplify load if not used carefully.

Implementation
  • Use libraries like Hystrix (Java) or resilience4j.
  • Configure thresholds: e.g., 5 failures in 10 seconds opens circuit.
  • Set a half-open state to probe recovery.

When to use: When services have transient failures or are prone to overload.

circuit-breaker.jsBASH
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
const circuitBreaker = require('opossum');
const options = {
  timeout: 3000,
  errorThresholdPercentage: 50,
  resetTimeout: 30000
};
const breaker = circuitBreaker(fetchUser, options);
breaker.fallback(() => ({ error: 'Service unavailable' }));
app.get('/users/:id', async (req, res) => {
  try {
    const result = await breaker.fire(req.params.id);
    res.json(result);
  } catch (e) {
    res.status(503).json({ error: 'Service unavailable' });
  }
});
⚠ Retry Storm
📊 Production Insight
Monitor circuit breaker state changes and alert when a circuit opens. Use distributed tracing to correlate failures.
🎯 Key Takeaway
Circuit breakers and retries improve resilience but must be configured carefully to avoid cascading failures.

API Gateway Security Best Practices

Security is a primary reason to use an API Gateway. Key practices include: - Authentication: Validate JWT tokens, API keys, or OAuth2 tokens at the gateway. - Authorization: Implement role-based access control (RBAC) or attribute-based access control (ABAC). - Input Validation: Sanitize and validate request payloads to prevent injection attacks. - Rate Limiting: Protect against DDoS and brute force attacks. - IP Whitelisting/Blacklisting: Restrict access to known clients. - TLS Termination: Offload SSL to the gateway for performance.

Example: Kong's JWT plugin validates tokens before forwarding requests.

Common pitfalls
  • Not forwarding the original client IP.
  • Exposing internal service endpoints.
  • Storing secrets in configuration files.

When to use: Always, as a baseline for any production gateway.

nginx-security.confBASH
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
location /api/ {
    # Rate limiting
    limit_req zone=api_limit burst=20 nodelay;
    # IP whitelist
    allow 192.168.1.0/24;
    deny all;
    # JWT validation (using lua)
    access_by_lua_block {
        local jwt = require("resty.jwt")
        local token = ngx.var.http_authorization
        if not token then
            ngx.exit(401)
        end
        local jwt_obj = jwt:verify("secret", token)
        if not jwt_obj.verified then
            ngx.exit(401)
        end
    }
    proxy_pass http://backend;
}
💡Secrets Management
📊 Production Insight
Regularly audit gateway logs for suspicious activity. Implement a Web Application Firewall (WAF) for additional protection.
🎯 Key Takeaway
Centralize security at the gateway to enforce consistent policies and reduce attack surface.

API Gateway Performance and Scaling

An API Gateway can become a bottleneck if not scaled properly. Key considerations: - Horizontal Scaling: Run multiple gateway instances behind a load balancer. - Caching: Cache responses for idempotent requests to reduce backend load. - Connection Pooling: Reuse connections to backend services. - Asynchronous Processing: Use non-blocking I/O (e.g., Node.js, NGINX) to handle many concurrent connections. - Monitoring: Track latency, error rates, and throughput.

Example: Use Redis for distributed caching of rate limit counters and response data.

Trade-offs
  • Caching can serve stale data; use appropriate TTLs.
  • More instances increase complexity and cost.

When to use: Always plan for scaling from the start. Use auto-scaling groups for cloud deployments.

docker-compose.ymlBASH
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
version: '3'
services:
  gateway:
    image: kong:latest
    environment:
      KONG_DATABASE: postgres
      KONG_PG_HOST: kong-database
    ports:
      - "8000:8000"
    deploy:
      replicas: 3
      resources:
        limits:
          cpus: '0.5'
          memory: 512M
  kong-database:
    image: postgres:13
    environment:
      POSTGRES_DB: kong
      POSTGRES_USER: kong
      POSTGRES_PASSWORD: kong
🔥Stateless Gateway
📊 Production Insight
Use a CDN for static content and offload heavy processing to backend services to keep the gateway lean.
🎯 Key Takeaway
Scale the gateway horizontally and use caching to handle high traffic without becoming a bottleneck.
● Production incidentPOST-MORTEMseverity: high

The Rate Limiter That Blocked All Traffic

Symptom
All users received HTTP 429 Too Many Requests errors, even legitimate customers with low request rates.
Assumption
The developer assumed the rate limiter was working correctly based on unit tests and low traffic during staging.
Root cause
The rate limiter's key was set to the client IP address, but the gateway was behind a load balancer that forwarded requests with the load balancer's IP. Thus, all requests appeared to come from a single IP, hitting the limit instantly.
Fix
Changed the rate limiter key to use the X-Forwarded-For header or a combination of client IP and user ID. Also added a whitelist for internal health checks.
Key lesson
  • Always test rate limiting with realistic traffic patterns and behind load balancers.
  • Use composite keys (e.g., IP + user ID) for rate limiting to avoid false positives.
  • Monitor rate limit metrics and set up alerts for sudden drops in allowed requests.
  • Include a bypass mechanism for internal services and health checks.
  • Document the rate limiting configuration and review it before high-traffic events.
Production debug guideSymptom to Action5 entries
Symptom · 01
All requests return 502 Bad Gateway
Fix
Check backend service health and connectivity. Verify gateway's upstream configuration.
Symptom · 02
Intermittent 504 Gateway Timeout
Fix
Increase timeout settings or optimize slow backend services. Check for network congestion.
Symptom · 03
Authentication failures for valid tokens
Fix
Verify token validation logic and clock skew between services. Check if the gateway is stripping headers.
Symptom · 04
Rate limiting errors for legitimate users
Fix
Inspect rate limiter key configuration. Check if client IP is correctly extracted behind proxies.
Symptom · 05
High latency in responses
Fix
Enable gateway logging and trace requests. Check for aggregation overhead or backend bottlenecks.
★ Quick Debug Cheat SheetCommon API Gateway issues and immediate actions.
502 Bad Gateway
Immediate action
Check backend health
Commands
curl -I http://backend-service/health
netstat -an | grep <backend-port>
Fix now
Restart backend or update gateway upstream config.
429 Too Many Requests+
Immediate action
Check rate limit key
Commands
grep 'rate_limit' /var/log/gateway/access.log
echo $X-Forwarded-For
Fix now
Adjust rate limit key to use X-Forwarded-For header.
401 Unauthorized+
Immediate action
Verify token
Commands
jwt decode <token>
date && date -u
Fix now
Sync clocks or update token validation logic.
504 Gateway Timeout+
Immediate action
Increase timeout
Commands
grep 'timeout' /etc/gateway/config.yaml
time curl -X GET http://backend-service/slow-endpoint
Fix now
Increase proxy_read_timeout or optimize backend.
PatternDescriptionUse CaseComplexity
Gateway RoutingForward requests to services based on pathSimple CRUD APIsLow
Gateway AggregationCombine responses from multiple servicesDashboards, mobile appsMedium
Gateway OffloadingCentralize cross-cutting concernsAuthentication, SSL, rate limitingMedium
Circuit BreakerPrevent cascading failuresUnreliable servicesHigh
⚙ Quick Reference
7 commands from this guide
FileCommand / CodePurpose
nginx-gateway.confserver {What is an API Gateway?
kong-routing.ymlservices:API Gateway Patterns
aggregation.jsconst express = require('express');API Gateway Patterns
kong-offloading.ymlplugins:API Gateway Patterns
circuit-breaker.jsconst circuitBreaker = require('opossum');API Gateway Patterns
nginx-security.conflocation /api/ {API Gateway Security Best Practices
docker-compose.ymlversion: '3'API Gateway Performance and Scaling

Key takeaways

1
An API Gateway centralizes routing, security, and cross-cutting concerns, simplifying client development and improving system resilience.
2
Common patterns include Gateway Routing, Aggregation, Offloading, and Circuit Breaker; choose based on your use case.
3
Always plan for scaling, security, and monitoring to avoid the gateway becoming a bottleneck or single point of failure.
4
Learn from real-world incidents
test rate limiting behind load balancers, use composite keys, and implement circuit breakers.

Common mistakes to avoid

5 patterns
×

Not forwarding the original client IP

×

Hardcoding service URLs in gateway config

×

Overloading the gateway with business logic

×

Ignoring gateway security

×

Not monitoring the gateway

INTERVIEW PREP · PRACTICE MODE

Interview Questions on This Topic

Q01JUNIOR
What is an API Gateway and why is it used in microservices?
Q02SENIOR
Explain the Gateway Aggregation pattern and its trade-offs.
Q03SENIOR
How would you design a rate limiter in an API Gateway to handle distribu...
Q04SENIOR
What is the Circuit Breaker pattern and how does it apply to an API Gate...
Q05SENIOR
Compare API Gateway with Service Mesh. When would you use each?
Q01 of 05JUNIOR

What is an API Gateway and why is it used in microservices?

ANSWER
An API Gateway is a single entry point for client requests that handles routing, authentication, rate limiting, and other cross-cutting concerns. It simplifies client code, centralizes security, and enables service independence.
FAQ · 5 QUESTIONS

Frequently Asked Questions

01
What is the difference between an API Gateway and a reverse proxy?
02
Can I use multiple API Gateways?
03
How does an API Gateway handle service discovery?
04
Is an API Gateway a single point of failure?
05
What are the alternatives to an API Gateway?
N
Naren Founder & Principal Engineer

20+ years shipping production systems from the metal up. Drawn from code that ran under real load.

Follow
Verified
production tested
July 13, 2026
last updated
2,165
articles · all by Naren
🔥

That's Computer Networks. Mark it forged?

3 min read · try the examples if you haven't

Previous
Load Balancers: Algorithms, Types, and Deployment
24 / 30 · Computer Networks
Next
TLS 1.3 and SSL: Complete Guide