A high-performance API Gateway built with Go
A feature-rich gateway with PostgreSQL, caching, authentication, tracing, and real-time capabilities
- Fast Routing: Built on top of Chi router
- Database: PostgreSQL with pgx driver
- Caching: In-memory caching with TTL support
- Concurrency: Goroutine-based concurrent request handling
- Rate Limiting: Built-in rate limiting per client
- Middleware: Logger, CORS, Recovery, Timeout, and Rate Limiting
- Proxy: Request forwarding to backend services
- Health Checks: Database and cache health monitoring
- Graceful Shutdown: Clean shutdown with connection draining
- Full Route CRUD API: Complete REST API for route management with cache integration
- Request Logging: Automatic database logging of all proxied requests with performance tracking
- Authentication & Authorization: JWT-based auth with Role-Based Access Control (RBAC)
- Prometheus Metrics: Comprehensive metrics export for monitoring (requests, latency, cache, circuit breaker states)
- OpenAPI/Swagger: Auto-generated interactive API documentation
- Load Balancing: Multiple algorithms (Round Robin, Least Connections) with health checking
- Circuit Breaker: Fault tolerance with automatic failure detection and recovery
- Distributed Tracing: OpenTelemetry integration with Jaeger for request flow visibility
- WebSocket Support: Full-duplex real-time communication with hub-based connection management
- Integration Tests: Comprehensive test suite with benchmarks and coverage reports
βββ cmd/
β βββ gateway/ # Main application entry point
βββ internal/
β βββ core/ # Core engine implementation
β βββ database/ # PostgreSQL database layer
β βββ cache/ # In-memory caching layer
β βββ router/ # HTTP routing and handlers
β βββ middleware/ # HTTP middleware
β βββ proxy/ # Request proxying logic
βββ pkg/
βββ config/ # Configuration management
βββ logger/ # Logging utilities
βββ response/ # HTTP response helpers
- Go 1.22 or higher
- PostgreSQL 12 or higher
- Clone the repository:
git clone https://github.com/zakirkun/isekai.git
cd isekai- Install dependencies:
go mod tidy-
Set up environment variables (see Configuration section)
-
Run the application:
go run cmd/gateway/main.goConfigure the gateway using environment variables:
SERVER_PORT- Server port (default: 8080)SERVER_READ_TIMEOUT- Read timeout (default: 15s)SERVER_WRITE_TIMEOUT- Write timeout (default: 15s)SERVER_SHUTDOWN_TIMEOUT- Graceful shutdown timeout (default: 30s)
DB_HOST- PostgreSQL host (default: localhost)DB_PORT- PostgreSQL port (default: 5432)DB_USER- Database user (default: postgres)DB_PASSWORD- Database password (default: postgres)DB_NAME- Database name (default: isekai_gateway)DB_SSL_MODE- SSL mode (default: disable)DB_MAX_OPEN_CONNS- Max open connections (default: 25)DB_MAX_IDLE_CONNS- Max idle connections (default: 5)
CACHE_ENABLED- Enable caching (default: true)CACHE_TTL- Cache TTL (default: 5m)CACHE_CLEANUP_INTERVAL- Cleanup interval (default: 10m)CACHE_MAX_SIZE- Max cache entries (default: 1000)
GATEWAY_MAX_CONCURRENT_REQUESTS- Max concurrent requests (default: 1000)GATEWAY_REQUEST_TIMEOUT- Request timeout (default: 30s)GATEWAY_RATE_LIMIT_ENABLED- Enable rate limiting (default: true)GATEWAY_RATE_LIMIT_PER_SECOND- Requests per second per client (default: 100)
AUTH_ENABLED- Enable JWT authentication (default: false)JWT_SECRET- Secret key for JWT signing (required if auth enabled)JWT_TOKEN_DURATION- Token expiration duration (default: 24h)
TRACING_ENABLED- Enable OpenTelemetry tracing (default: false)OTLP_ENDPOINT- OpenTelemetry collector endpoint (default: localhost:4318)SERVICE_NAME- Service name for tracing (default: isekai-gateway)
GET /health # Health check endpoint
GET /api/status # Gateway status
POST /api/auth/login # Login and get JWT token
GET /api/routes # List all routes
POST /api/routes # Create a route (requires auth if enabled)
GET /api/routes/{id} # Get a route by ID
PUT /api/routes/{id} # Update a route (requires auth if enabled)
DELETE /api/routes/{id} # Delete a route (requires auth if enabled)
GET /metrics # Prometheus metrics endpoint
GET /swagger/index.html # Swagger UI documentation
GET /swagger/doc.json # OpenAPI JSON specification
GET /api/load-balancer/status # Load balancer status
GET /api/circuit-breaker/status # Circuit breaker status
WS /ws # WebSocket connection endpoint
GET /api/websocket/stats # WebSocket statistics
# Run all tests
go test ./...
# Run integration tests
go test ./internal/integration/...
# Run with coverage
go test -coverprofile=coverage.out ./...
go tool cover -html=coverage.out
# Run benchmarks
go test -bench=. ./internal/integration/...go build -o bin/gateway cmd/gateway/main.goSERVER_PORT=3000 go run cmd/gateway/main.go# Install swag
go install github.com/swaggo/swag/cmd/swag@latest
# Generate documentation
swag init -g cmd/gateway/main.go -o docs- Language: Go 1.23
- Router: Chi v5
- Database: PostgreSQL with pgx/v5
- Concurrency: Goroutines and sync primitives
- Caching: In-memory with expiration
- Authentication: JWT with RBAC
- Metrics: Prometheus
- Tracing: OpenTelemetry + Jaeger
- WebSocket: Gorilla WebSocket
- Circuit Breaker: Sony gobreaker
- Load Balancing: Custom implementation (Round Robin, Least Connections)
- API Documentation: Swagger/OpenAPI with swaggo
- JWT-based authentication with configurable token duration
- Role-Based Access Control (RBAC) for fine-grained permissions
- Rate limiting to prevent abuse and DDoS attacks
- Request validation and sanitization
- Prometheus Metrics: Track requests, latency, cache performance, and more
- Distributed Tracing: OpenTelemetry integration with Jaeger for request flow visualization
- Request Logging: All proxied requests logged to database with performance metrics
- Health Checks: Monitor database and cache connectivity
- Load Balancing: Multiple strategies (Round Robin, Least Connections) with health checking
- Circuit Breaker: Automatic failure detection and recovery to prevent cascade failures
- Caching: In-memory caching with TTL for improved response times
- Connection Pooling: Efficient database connection management
- Concurrent Processing: Goroutine-based request handling
- WebSocket Support: Full-duplex communication with hub-based connection management
- Broadcast Messaging: Send messages to all connected clients
- Connection Tracking: Monitor active WebSocket connections and statistics
- Interactive API Documentation: Swagger UI for exploring and testing APIs
- Comprehensive Tests: Integration tests with benchmarks and coverage reports
- Hot Reload: Easy development workflow
- Docker Support: Containerized deployment with Docker Compose
- Architecture Overview - System design and components
- Quick Start Guide - Common tasks and examples
- Features Guide - Complete feature documentation with examples
- Observability Stack - Monitoring, metrics, and tracing
- Development Roadmap - Future features and development plans πΊοΈ
- API Documentation - Swagger UI (when running)
curl -X POST http://localhost:8080/api/routes \
-H "Content-Type: application/json" \
-H "Authorization: Bearer YOUR_TOKEN" \
-d '{
"path": "/api/users",
"target_url": "http://backend:3000/users",
"method": "GET",
"enabled": true,
"rate_limit": 100,
"timeout": 30
}'# Login to get JWT token
curl -X POST http://localhost:8080/api/auth/login \
-H "Content-Type: application/json" \
-d '{"username": "admin", "password": "password"}'
# Use the token in subsequent requests
curl http://localhost:8080/api/routes \
-H "Authorization: Bearer YOUR_JWT_TOKEN"const ws = new WebSocket('ws://localhost:8080/ws');
ws.onopen = () => {
console.log('Connected to gateway!');
ws.send(JSON.stringify({
type: 'message',
payload: 'Hello from client!'
}));
};
ws.onmessage = (event) => {
const data = JSON.parse(event.data);
console.log('Received:', data);
};# View all available metrics
curl http://localhost:8080/metrics
# Query in Prometheus
# Example: Rate of HTTP requests
rate(isekai_http_requests_total[5m])Run the full observability stack with OpenTelemetry, Prometheus, Jaeger, and Grafana:
docker-compose -f docker-compose.observability.yml up -dAccess:
- Grafana: http://localhost:3000 (admin/admin)
- Pre-configured dashboards for request metrics, latency, and system health
- Jaeger: http://localhost:16686
- Distributed tracing UI for request flow visualization
- Prometheus: http://localhost:9090
- Metrics scraping and querying interface
- Swagger UI: http://localhost:8080/swagger/index.html
- Interactive API documentation
The gateway exposes comprehensive Prometheus metrics at /metrics:
isekai_http_requests_total- Total HTTP requests by method, path, and statusisekai_http_request_duration_seconds- Request duration histogramisekai_active_connections- Current active connectionsisekai_cache_hits_total- Cache hit counterisekai_cache_misses_total- Cache miss counterisekai_proxy_errors_total- Proxy error counter by backendisekai_database_query_duration_seconds- Database query durationisekai_circuit_breaker_state- Circuit breaker states by backend
See OBSERVABILITY.md for detailed monitoring guide.
The gateway is designed for high performance:
- β‘ Async Request Logging: Non-blocking database writes
- πΎ Connection Pooling: Configurable pool sizes for optimal resource usage
- π In-Memory Caching: Sub-millisecond cache lookups
- π Load Balancing: Efficient traffic distribution
β οΈ Circuit Breaker: Fast-fail for unhealthy backends- π Optimized Metrics: Low-overhead instrumentation
Run benchmarks:
go test -bench=. ./internal/integration/...Before deploying to production, ensure:
# Security
β AUTH_ENABLED=true
β JWT_SECRET=<strong-random-secret>
β DB_SSL_MODE=require
β GATEWAY_RATE_LIMIT_ENABLED=true
# Performance
β DB_MAX_OPEN_CONNS=25 (adjust based on load)
β CACHE_ENABLED=true
β GATEWAY_REQUEST_TIMEOUT=30s
# Observability
β TRACING_ENABLED=true (if using)
β Prometheus scraping configured
β Grafana dashboards imported
β Jaeger collector running (if using tracing)MIT License