Design an API Gateway
HardDesign PatternsRate LimitingAuthenticationLoad BalancingCircuit BreakerRouting
Problem Statement
Design an API Gateway that acts as a single entry point for microservices — handling request routing, authentication, rate limiting, load balancing, and circuit breaking.
Requirements
Functional Requirements
- Route incoming HTTP requests to appropriate backend services based on URL path and method
- Authentication: validate API keys or JWT tokens before forwarding requests
- Rate limiting: per-client throttling (pluggable algorithm — token bucket default)
- Load balancing: distribute requests across multiple instances of a service (ROUND_ROBIN, WEIGHTED, LEAST_CONNECTIONS)
- Circuit breaker: stop routing to a failing service after N consecutive failures; retry after timeout
- Request/response transformation: add/remove headers, modify path
- Request logging and metrics collection (latency, error rate per route)
- Health checks: periodically probe backend instances; remove unhealthy ones
Non-Functional Requirements
- Thread-safe routing and load balancing state
- Pluggable strategy for rate limiting and load balancing
- Singleton APIGateway
Key Entities
- Route: path pattern, method, targetService, middleware chain
- ServiceRegistry: Map<serviceName, List<ServiceInstance>>
- ServiceInstance: host, port, weight, healthy, activeConnections
- LoadBalancer (interface):
selectInstance(serviceName)— RoundRobin, Weighted, LeastConnections - CircuitBreaker: per-service; states: CLOSED, OPEN, HALF_OPEN
- RateLimiter: per-client (reuse design from rate limiter problem)
- APIGateway: Singleton; request pipeline
Constraints
- Circuit breaker opens after 5 consecutive failures; retries after 30 seconds in HALF_OPEN
- Rate limiting checked before routing (fail fast)
- Authentication checked before rate limiting
- Health checks run every 30 seconds
!Constraints
- Authentication → Rate Limiting → Circuit Breaker → Load Balancing → Forward (strict pipeline order)
- Circuit breaker: OPEN after 5 consecutive failures, HALF_OPEN after 30s, CLOSED after successful probe
- Health check interval: 30 seconds; unhealthy instances removed from rotation
- Thread-safe load balancer state (round-robin counter, connection counts)
- Request timeout: configurable per route (default 5 seconds)
Output
Run or submit your code to see output here.