Skip to main content

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.

โœ“ Centralized auth & rate limiting โœ“ Request routing & transformation โœ“ Kong, AWS GW, and Nginx examples โœ“ Plugin-based extensibility

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
Share this tool: X / Twitter LinkedIn
โœ“ 60,000+ developers use DevPlaybook โ˜…โ˜…โ˜…โ˜…โ˜… 4.8 / 5 on Gumroad โœ“ MIT licensed ยท Instant download โœ“ No login required

Related Products

on Gumroad

You Might Also Need

More Free Tools

nginx Config Generator nginx Config Builder OpenAPI Validator AWS CDK Infrastructure as Code Guide API Response Mock Generator API Response Time Tester OpenAPI Schema Validator OpenAPI Mock Generator AWS IAM Policy Generator API Test Case Generator API Request Builder AWS IAM Policy Validator API Mock Server Config Generator API Rate Limit Calculator API Response Formatter & Analyzer HTTP API Tester Rate Limit Calculator LLM Cost Calculator CORS Policy Builder AI Prompt Cost Calculator REST API Request Builder LLM Prompt Cost Calculator API Response Mocker AWS Cost Estimator AWS Lambda Cost Calculator AI Rate Limit Calculator API Key Generator AI Doc Generator โ€” Pro Tool HTTP Methods Reference HTTP Security Headers Generator HTTP Code Snippet Generator HTTP Status Code Reference HTTP Status Code Reference Interview Question Generator JSON Diff Viewer JSON Diff Rate Limiter Tester API Changelog Generator HTTP Mock Response Builder Load Balancer Config Generator Haproxy Config Validator HTTP Status Code Lookup HTTP Status Code Lookup Vue Component Generator HTTP Status Code Reference LLM Context Window Calculator LLM Token Counter HTTP/2 Server Push Headers Builder mTLS Certificate Chain Builder Prompt Token Estimator Mock Service Worker (MSW) API Mocking Guide Pulumi Modern IaC Guide Packer Machine Image Builder Guide HashiCorp Vault Secrets Management Guide Pulumi Stack Config Generator HTTP Cache Header Builder HTML5 Canvas API Playground Token Context Calculator OpenAI Function Calling Generator Token Counter & Cost Estimator AI API Rate Limit Calculator

Enjoying this tool? Get more like it.

Weekly developer tool guides, productivity playbooks & AI tricks. Free. No spam.

DevPlaybook Pro 7 days free

Unlock AI-Powered Dev Tools

  • โšก AI Code Review, Doc Generator & SQL Builder
  • โšก All premium templates & early access
  • โšก Member discounts on Gumroad products
Start Free Trial โ†’

$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.

$79
$241 separately Save $162 (67% off)
Get DevPlaybook Pro โ€” $79 โ†’

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.