codez.guru

What Is an API Gateway?

An API Gateway is the entry point for all client requests in a microservices system.

It routes, aggregates, transforms, and protects traffic between clients and services.

You can think of it as the traffic controller for your backend.


Why Use a Gateway in Microservices?

Without a gateway:

  • Clients must know internal service URLs
  • Every client must handle service changes
  • Cross-cutting concerns (auth, rate limit, logging) are repeated

With a gateway:
✅ Simplified client access
✅ Centralized security and monitoring
✅ Flexible routing and aggregation


Gateway Responsibilities

An API Gateway can handle:

  • Reverse proxying
  • Request routing
  • Rate limiting
  • Authentication (e.g., JWT validation)
  • Aggregation (multiple services → one response)
  • Caching
  • Load balancing
  • Logging and metrics

Tools:

  • Kong
  • NGINX
  • Traefik
  • Express (custom gateway)
  • BFF or GraphQL Gateway

Implementing a Basic Gateway (Express + Proxy)

// gateway.ts
import express from 'express';
import proxy from 'express-http-proxy';

const app = express();

app.use('/users', proxy('http://user-service:3001'));
app.use('/products', proxy('http://product-service:3002'));
app.use('/orders', proxy('http://order-service:3003'));

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

Add auth middleware if needed:

app.use('/orders', verifyJWT, proxy('http://order-service:3003'));

Aggregation Layer (BFF or GraphQL)

Sometimes the frontend needs data from multiple services.

Instead of making 3 HTTP calls from the client:

GET /users/me  
GET /orders?userId=123  
GET /notifications?userId=123

Build an aggregation layer:

  • BFF (Backend for Frontend)
  • GraphQL Gateway (Apollo, Hasura, StepZen)

Example: GraphQL query to combine user + orders

{
  me {
    name
    email
    orders {
      id
      total
    }
  }
}

The gateway resolves data from multiple services and returns it as one JSON response.


Summary

An API Gateway simplifies communication between clients and services by routing, protecting, and aggregating requests. You can implement it as a reverse proxy or a full GraphQL-powered data orchestrator.


Next:
Lesson 19 – Testing and Debugging Microservices