Skip to content

Latest commit

Β 

History

5 Commits

Folders and files

NameName
Last commit message
Last commit date
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

πŸš€ API Gateway β€” Microservices Architecture

A production-style API Gateway built with Node.js that acts as the single entry point for a microservices-based backend system. It handles rate limiting, response caching, JWT authentication, and structured logging β€” routing traffic intelligently to three independent downstream microservices, each backed by its own isolated MongoDB instance.


πŸ“ Architecture Overview

Client
  β”‚
  β–Ό
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚               API Gateway (Port 3000)        β”‚
β”‚                                              β”‚
β”‚  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”  β”‚
β”‚  β”‚ Rate     β”‚  β”‚ Redis  β”‚  β”‚ JWT Auth    β”‚  β”‚
β”‚  β”‚ Limiter  β”‚  β”‚ Cache  β”‚  β”‚ Middleware  β”‚  β”‚
β”‚  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜  β””β”€β”€β”€β”€β”€β”€β”€β”€β”˜  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜  β”‚
β”‚  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”  β”‚
β”‚  β”‚       Morgan HTTP Logger               β”‚  β”‚
β”‚  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜  β”‚
β”‚  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”  β”‚
β”‚  β”‚       Request Router (routes.js)       β”‚  β”‚
β”‚  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜  β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
              β”‚          β”‚          β”‚
    β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜  β”Œβ”€β”€β”€β”€β”€β”€β”€β”˜  β”Œβ”€β”€β”€β”€β”€β”€β”˜
    β–Ό            β–Ό          β–Ό
User Service  Product    Order
(Port 4000)   Service    Service
(MongoDB)     (Port 5001)(Port 6000)
              (MongoDB)  (MongoDB)
                    β”‚
              Prometheus (Port 9090)
              Grafana    (Port 3001)

All services communicate over a shared Docker bridge network (mynetwork) and are orchestrated via Docker Compose.


✨ Features

Feature Details
API Gateway Single entry point routing to all microservices
Rate Limiting Redis-backed, 1000 requests/60 seconds per IP
Response Caching Redis cache with 60-second TTL on all GET requests
JWT Authentication Token-based auth middleware (pluggable)
Structured Logging HTTP access logs via Morgan written to access.log
API Documentation Swagger UI served at /docs
Containerised All services Dockerized, orchestrated with Docker Compose
Monitoring Prometheus metrics scraping + Grafana dashboards
Input Validation express-validator on sensitive endpoints

πŸ—‚οΈ Project Structure

api-gateway/
β”œβ”€β”€ gateway/                       # API Gateway service
β”‚   β”œβ”€β”€ server.js                  # Express app bootstrap & middleware registration
β”‚   β”œβ”€β”€ routes.js                  # Request forwarding logic to microservices
β”‚   β”œβ”€β”€ auth.js                    # JWT authentication middleware
β”‚   β”œβ”€β”€ rateLimiter.js             # Redis-backed rate limiting middleware
β”‚   β”œβ”€β”€ cache.js                   # Redis response caching middleware
β”‚   β”œβ”€β”€ logging.js                 # Morgan HTTP access logger
β”‚   β”œβ”€β”€ swagger.js                 # Swagger/OpenAPI documentation setup
β”‚   β”œβ”€β”€ Dockerfile                 # Gateway container definition
β”‚   └── package.json
β”‚
β”œβ”€β”€ microservices/
β”‚   β”œβ”€β”€ user-service/              # User management microservice (Port 4000)
β”‚   β”‚   β”œβ”€β”€ server.js              # Register, Login, Profile endpoints
β”‚   β”‚   β”œβ”€β”€ Dockerfile
β”‚   β”‚   β”œβ”€β”€ .env                   # AUTH_KEY secret
β”‚   β”‚   └── package.json
β”‚   β”‚
β”‚   β”œβ”€β”€ product-service/           # Product catalog microservice (Port 5001)
β”‚   β”‚   β”œβ”€β”€ server.js              # Create, List, Update Stock endpoints
β”‚   β”‚   β”œβ”€β”€ Dockerfile
β”‚   β”‚   └── package.json
β”‚   β”‚
β”‚   └── order-service/             # Order management microservice (Port 6000)
β”‚       β”œβ”€β”€ server.js              # Create Order, Get Orders by User endpoints
β”‚       β”œβ”€β”€ Dockerfile
β”‚       └── package.json
β”‚
β”œβ”€β”€ monitoring/
β”‚   β”œβ”€β”€ prometheus.yml             # Prometheus scrape config (15s interval)
β”‚   └── grafana/                   # Grafana dashboard config
β”‚
└── deployment/
    └── docker-compose.yml         # Full stack orchestration

πŸ”§ Technology Stack

Core

Technology Version Purpose
Node.js 18 Runtime for all services
Express.js ^4.21.0 HTTP server framework

API Gateway

Package Purpose
ioredis Redis client for rate limiting & caching
rate-limiter-flexible Redis-backed rate limiting strategy
jsonwebtoken JWT generation & verification
morgan HTTP request logger
node-fetch Internal HTTP forwarding to microservices
swagger-jsdoc + swagger-ui-express OpenAPI 2.0 documentation

Microservices

Package Purpose
mongoose MongoDB ODM for all three services
bcryptjs Password hashing (User Service)
express-validator Input validation (User & Product services)
dotenv Environment variable management

Infrastructure

Technology Purpose
Docker Containerisation of each service
Docker Compose Multi-container orchestration
Redis Rate limiting store + response cache
MongoDB Document database (3 isolated instances)
Prometheus Metrics collection (scrapes gateway every 15s)
Grafana Metrics visualisation dashboard

🌐 API Endpoints

All client requests hit the API Gateway at port 3000, which proxies them to the appropriate microservice.

πŸ‘€ User Service (/api/users/* β†’ user-service:4000)

Method Endpoint Description Auth Required
POST /api/users/register Register a new user ❌
POST /api/users/login Login and receive JWT token ❌
GET /api/users/me Get authenticated user profile βœ…

Register Request Body:

{
  "name": "John Doe",
  "email": "john@example.com",
  "password": "secret123"
}

Login Response:

{
  "token": "<JWT>"
}

πŸ“¦ Product Service (/api/products/* β†’ product-service:5001)

Method Endpoint Description Auth Required
POST /api/products Create a new product ❌
GET /api/products List all products ❌
PUT /api/products/:id/stock Update product stock level ❌

Create Product Request Body:

{
  "name": "Widget",
  "price": 9.99,
  "stock": 100
}

πŸ›’ Order Service (/api/orders/* β†’ order-service:6000)

Method Endpoint Description Auth Required
POST /api/orders Create a new order (auto-calculates total) ❌
GET /api/orders/user/:userId Get all orders for a specific user ❌

Create Order Request Body:

{
  "userId": "<user_id>",
  "products": [
    { "productId": "<product_id>", "quantity": 2 }
  ]
}

Note: The Order Service fetches real-time product prices from the Product Service internally to compute totalAmount.


βš™οΈ Gateway Middleware Pipeline

Requests entering the gateway pass through the following middleware stack in order:

Incoming Request
      β”‚
      β–Ό
1. Morgan Logger         β†’ Appends to access.log
      β”‚
      β–Ό
2. Rate Limiter          β†’ 1000 req/min per IP via Redis
      β”‚                    Returns 429 if exceeded
      β–Ό
3. Redis Cache           β†’ Checks Redis for cached response (GET)
      β”‚                    Returns cached JSON if hit (200)
      β–Ό
4. Router (routes.js)   β†’ Forwards request to correct microservice
      β”‚                    via node-fetch (method + headers preserved)
      β–Ό
Microservice Response   β†’ Cached in Redis (TTL: 60s), returned to client

JWT Auth middleware is implemented in auth.js and can be enabled by uncommenting the app.use('/api/*', auth) line in server.js.


πŸ“Š Monitoring

Prometheus

Grafana

  • Pre-configured container based on Prometheus data source
  • Build custom dashboards to visualise request rates, latency, and error rates

πŸš€ Getting Started

Prerequisites

  • Docker & Docker Compose installed

Running the Full Stack

# Clone the repository
git clone <repo-url>
cd api-gateway

# Start all services
cd deployment
docker-compose up --build

Service URLs

Service URL
API Gateway http://localhost:3000
Swagger Docs http://localhost:3000/docs
User Service http://localhost:4000
Product Service http://localhost:5001
Order Service http://localhost:6000
Prometheus http://localhost:9090
MongoDB (User) localhost:27017
MongoDB (Product) localhost:27018
MongoDB (Order) localhost:27019
Redis localhost:6379

πŸ” Environment Variables

User Service (.env)

AUTH_KEY=your_jwt_secret_key
PORT=4000

πŸ“‹ Data Models

User

{
  name: String,
  email: String (unique),
  password: String (bcrypt hashed)
}

Product

{
  name: String,
  price: Number,
  stock: Number
}

Order

{
  userId: String,
  products: [{ productId: String, quantity: Number }],
  totalAmount: Number,
  status: String (default: "Pending")
}

πŸ“„ License

This project is open source and available under the MIT License.

About

An API Gateway with built-in rate limiting, request/response caching, and load balancing using Node.js, Redis (for caching), NGINX/HAProxy (for load balancing), Express, MongoDB.

Resources

Stars

1 star

Watchers

1 watching

Forks

Releases

Packages

Contributors

Languages