Skip to main content

API Gateway

An API Gateway is a critical component in system design, particularly in microservices architecture. It acts as a single entry point for all client requests and routes them to the appropriate backend services.

Features of API Gateway

FeaturePurpose
RoutingRequest goes to the right microservice
AuthVerifies user credentials (e.g., JWT)
Rate LimitingProtects backend from overload
CachingReduces load, speeds up repeated queries
Load BalancingDistributes traffic across instances
MonitoringLogs metrics for observability

Why Use an API Gateway?

In microservices, services are often broken into small units (e.g., auth, order, payment, etc.). If clients (like mobile apps or browsers) directly interact with all these, it:

  • Increases complexity
  • Exposes internal service structure
  • Requires handling cross-cutting concerns multiple times

An API Gateway abstracts these concerns and centralizes them.

API Gateway Worflow

Let’s say you’re designing an e-commerce system:

Services:

  • User Service (/users)
  • Product Service (/products)
  • Order Service (/orders)

Client Flow:

  • The client sends a request to /api/products.
  • The API Gateway receives the request.
  • It authenticates the user (via token).
  • It routes the request to the Product Service.
  • The response comes back to the gateway.
  • The gateway may transform the response.
  • The client gets the response.

Example of API Gateway

// api-gateway.js
const express = require("express");
const { createProxyMiddleware } = require("http-proxy-middleware");

const app = express();

// Middleware: Log all requests
app.use((req, res, next) => {
console.log(`[Gateway] ${req.method} ${req.originalUrl}`);
next();
});

// Forward /users requests
app.use(
"/users",
createProxyMiddleware({
target: "http://localhost:5001", // User Service
changeOrigin: true,
})
);

// Forward /products requests
app.use(
"/products",
createProxyMiddleware({
target: "http://localhost:5002", // Product Service
changeOrigin: true,
})
);

// Forward /orders requests
app.use(
"/orders",
createProxyMiddleware({
target: "http://localhost:5003", // Order Service
changeOrigin: true,
})
);

app.listen(3000, () => {
console.log("API Gateway running on port 3000");
});

Benefits and Trade-offs of API Gateway

BenefitsTrade-offs
Simplifies client interactionSingle point of failure (if not replicated)
Centralizes security and loggingAdds latency (extra network hop)
Enables decoupled service developmentCan become complex (requires scaling & config management)
Supports versioning, throttling, caching