API Gateway Patterns: Kong, AWS API Gateway & Nginx Guide
An API gateway is the front door to your microservices architecture. It centralizes authentication, rate limiting, routing, SSL termination, and observability so backend services stay focused on business logic. This guide covers the core patterns and tool choices.
Rate Limiting with Kong
Kong plugins are applied to services or routes. The rate-limiting plugin protects a service with per-consumer limits using a sliding window algorithm:
# Declarative Kong configuration (deck / kong.yaml)
services:
- name: user-service
url: http://user-service:8080
routes:
- name: user-api-route
paths:
- /api/v1/users
methods: [GET, POST, PUT, DELETE]
plugins:
# Rate limiting: 100 req/minute per consumer
- name: rate-limiting
service: user-service
config:
minute: 100
hour: 1000
policy: redis # Store counters in Redis for distributed deployments
redis_host: redis
redis_port: 6379
fault_tolerant: true # Allow requests if Redis is unavailable
hide_client_headers: false
# JWT authentication before routing
- name: jwt
service: user-service
config:
claims_to_verify: [exp]
key_claim_name: iss Auth Middleware Pattern (Express Gateway / Custom)
When building a lightweight custom gateway in Node.js, centralize JWT validation in middleware before proxying to upstream services:
import express from 'express';
import { createProxyMiddleware } from 'http-proxy-middleware';
import jwt from 'jsonwebtoken';
const app = express();
// Auth middleware โ validates JWT and injects user context
function authMiddleware(req: any, res: any, next: any) {
const token = req.headers.authorization?.replace('Bearer ', '');
if (!token) return res.status(401).json({ error: 'Missing token' });
try {
const payload = jwt.verify(token, process.env.JWT_SECRET!) as any;
req.headers['x-user-id'] = payload.sub;
req.headers['x-user-roles'] = payload.roles?.join(',') ?? '';
next();
} catch {
res.status(401).json({ error: 'Invalid token' });
}
}
// Route to user service โ protected
app.use('/api/v1/users', authMiddleware, createProxyMiddleware({
target: 'http://user-service:8080',
changeOrigin: true,
}));
// Route to public service โ no auth
app.use('/api/v1/products', createProxyMiddleware({
target: 'http://product-service:8081',
changeOrigin: true,
})); Nginx Rate Limiting & Routing
Nginx provides high-performance rate limiting and upstream routing with minimal configuration overhead:
# nginx.conf โ API gateway configuration
http {
# Define rate limiting zone: 10 MB memory, 10 req/sec per IP
limit_req_zone $binary_remote_addr zone=api:10m rate=10r/s;
upstream user_service { server user-service:8080; }
upstream order_service { server order-service:8082; }
upstream product_service { server product-service:8081; }
server {
listen 80;
location /api/v1/users {
limit_req zone=api burst=20 nodelay;
limit_req_status 429;
proxy_pass http://user_service;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header Authorization $http_authorization;
}
location /api/v1/orders {
limit_req zone=api burst=10 nodelay;
proxy_pass http://order_service;
}
location /api/v1/products {
# Public endpoint โ higher limit
limit_req zone=api burst=50 nodelay;
proxy_pass http://product_service;
}
}
} Kong vs AWS API Gateway vs Nginx
| Feature | Kong | AWS API Gateway | Nginx |
|---|---|---|---|
| Hosting | Self-hosted / Kong Cloud | Fully managed AWS | Self-hosted |
| Auth plugins | JWT, OAuth2, OIDC, Key Auth | IAM, Cognito, Lambda | Basic, JWT (plus) |
| Rate limiting | Built-in plugin, Redis | Built-in (usage plans) | Built-in (limit_req) |
| Cost model | OSS free, Enterprise paid | Per million API calls | Free (infra cost only) |
| WebSocket | Supported | Supported | Supported |
| Best for | Multi-cloud, Kubernetes | AWS Lambda, serverless | High perf, simple routing |
Related Products
on GumroadDevPlaybook Interview Vault
210+ real technical interview questions with model answers, asked at Google, Meta, Amazon, Microsoft, Stripe, and Shopify. Covers Frontend (55), Backend (55), System Design (50), and DSA (50). Available in English and Traditional Chinese.
Buy on Gumroad โTypeScript Quick Reference Toolkit
5 practical reference files for TypeScript developers: cheatsheet, TS vs JS comparison, 20 utility types with real examples, tsconfig best practices template, and 15 common mistakes guide. Print it. Keep it on your desk.
Buy on Gumroad โDeveloper Interview Vault
210 technical interview questions with model answers, key points, and follow-up questions. Covers Frontend, Backend, System Design, and DSA โ bilingual English + Traditional Chinese (ZH-TW). PWYW from $29.
Buy on Gumroad โYou Might Also Need
nginx Config Generator
Generate production-ready nginx server blocks instantly. Supports static sites, reverse proxy (Node.js, API), PHP-FPM, and HTTPS redirects. Includes SSL/TLS, gzip, cache headers, security headers, and
Open free tool โ
nginx Config Builder
Build nginx server blocks and location blocks with a visual form. Configure reverse proxy, static file serving, WebSocket, CORS, gzip, and security headers. Generates copy-ready nginx config snippets.
Open free tool โ
OpenAPI Validator
Paste your OpenAPI 3.x spec (YAML or JSON) to validate structure, find missing required fields, detect duplicate paths, check for missing operationIds, and get errors and warnings with path references.
Open free tool โ
More Free Tools
Related Articles
FastAPI vs Django REST Framework 2025: Which Should You Choose?
FastAPI vs Django REST Framework compared for 2025. Performance benchmarks, feature comparison, real-world use cases, and a clear decision guide for your next Python API project.
Microservices vs Monolith 2026: Real-World Decision Framework
Stop following hype โ choose the right architecture for your specific context. Practical comparison of microservices vs monolith in 2026, with a decision framework based on team size, scale, and stage.
Microservices vs Monolith 2026: The Definitive Guide
Should you use microservices or a monolith in 2026? Updated decision framework covering team size, scaling needs, modern tooling, and the modular monolith approach.
Hono.js: Build Blazing-Fast APIs for Edge and Serverless (2026 Guide)
Complete guide to Hono.js covering routing, middleware, RPC client, Cloudflare Workers, Bun, Deno, and Node.js runtimes, OpenAPI integration, and comparison with Express and Fastify for edge workloads.
Microservices vs Monolith in 2026: When to Choose What
The honest guide to choosing between microservices and monolithic architecture in 2026. Real tradeoffs, migration strategies, service mesh, event-driven patterns, and case studies from Netflix, Uber, and Shopify.
Enjoying this tool? Get more like it.
Weekly developer tool guides, productivity playbooks & AI tricks. Free. No spam.
Unlock AI-Powered Dev Tools
- โก AI Code Review, Doc Generator & SQL Builder
- โก All premium templates & early access
- โก Member discounts on Gumroad products
$9/mo after trial ยท Cancel anytime
Want the full toolkit?
Get DevPlaybook Pro
Every template, guide, boilerplate, and automation script in one bundle. 13 premium products โ grab them all at once and save big.
MIT licensed ยท Instant download ยท No subscription
See what's included โ Browse all deals โFrequently Asked Questions
What is an API gateway and why do microservices need one?▼
An API gateway is a single entry point that sits in front of your backend services. Instead of clients calling each microservice directly, they call the gateway which handles routing, authentication, rate limiting, SSL termination, and request transformation. This decouples clients from service topology changes and keeps cross-cutting concerns out of individual services.
What is rate limiting and how does it work at the gateway?▼
Rate limiting caps how many requests a client can make in a time window, protecting backend services from being overwhelmed. Gateways implement rate limiting using sliding window, fixed window, or token bucket algorithms. Limits can be applied per IP, per API key, per user, or globally per route. When a client exceeds the limit the gateway returns 429 Too Many Requests with a Retry-After header.
How does Kong differ from AWS API Gateway?▼
Kong is open-source and self-hosted (or managed via Kong Cloud), giving you full control over infrastructure and configuration. It is plugin-based, so rate limiting, OAuth, caching, and logging are all plugins. AWS API Gateway is a fully managed service tightly integrated with Lambda, IAM, and CloudWatch. AWS is ideal for serverless AWS workloads; Kong is better for hybrid or multi-cloud deployments where you need portability.
Can an API gateway handle authentication for all services?▼
Yes. This is one of the primary benefits. The gateway validates JWT tokens, API keys, or OAuth flows centrally before forwarding requests. Backend services receive pre-validated requests with user identity injected via headers (e.g. X-User-Id), eliminating duplicated auth logic across services. Each service still validates that the header was set by a trusted gateway using network policies or shared secrets.
What is service mesh vs API gateway?▼
An API gateway manages north-south traffic โ requests coming in from external clients. A service mesh (Istio, Linkerd) manages east-west traffic โ communication between internal microservices. They complement each other. The gateway handles external auth, rate limiting, and routing. The service mesh handles mutual TLS between services, circuit breaking, retries, and observability for internal calls.
What is request routing in an API gateway?▼
Request routing directs incoming requests to the appropriate backend service based on URL path, headers, query parameters, or HTTP method. For example, GET /api/v1/users routes to the user service while POST /api/v1/orders routes to the order service. Advanced gateways support canary routing (5% of traffic to v2), A/B testing, and header-based routing for testing environments.