# API Gateway for Microservices

A high-performance API Gateway designed to handle 10,000+ users with efficient request routing, load balancing, and resilience patterns.

## Features

- **High Performance**: Utilizes Node.js clustering to leverage multiple CPU cores
- **Resilience**: Implements circuit breakers and retry mechanisms to handle service failures gracefully
- **Rate Limiting**: Protects backend services from being overwhelmed
- **Request Monitoring**: Tracks and logs request metrics for performance analysis
- **Error Handling**: Consistent error responses across all services
- **Security**: Implements security best practices with Helmet
- **Compression**: Reduces bandwidth usage with response compression

## Architecture

This API Gateway routes requests to the following microservices:

- User Service
- CRUD Service
- Dashboard Service

## Getting Started

### Prerequisites

- Node.js 14+
- npm or yarn

### Installation

1. Clone the repository
2. Install dependencies:

```
npm install
```

3. Configure environment variables in `.env` file:

```
PORT=3000
WORKERS=4 # Number of worker processes (defaults to CPU count)
USER_SERVICE_URL=http://localhost:3003
DASHBOARD_SERVICE_URL=http://localhost:3002
CRUD_SERVICE_URL=http://localhost:3004
```

### Running the Gateway

Development mode:

```
npm run dev
```

Production mode:

```
npm start
```

## API Endpoints

### Service Routes

- `/api/user-service/*` - Routes to the User Service
- `/api/crud-service/*` - Routes to the CRUD Service
- `/api/dashboard-service/*` - Routes to the Dashboard Service

### System Endpoints

- `/health` - Health check endpoint
- `/metrics` - Request metrics and system information

## Performance Considerations

This API Gateway is designed to handle high traffic with the following optimizations:

1. **Clustering**: Utilizes all available CPU cores
2. **Circuit Breakers**: Prevents cascading failures when services are down
3. **Timeouts**: Prevents long-running requests from blocking the event loop
4. **Rate Limiting**: Protects against traffic spikes and potential DoS attacks
5. **Compression**: Reduces bandwidth usage
6. **Efficient Error Handling**: Prevents memory leaks from unhandled errors

## Monitoring

The gateway provides real-time metrics through the `/metrics` endpoint and logs:

- Request counts
- Success/failure rates
- Response times
- CPU and memory usage

## License

MIT
