How Load Balancing Works
The gateway uses weighted random selection to distribute requests:- Assign weights to each target (default: 1)
- Calculate total weight across all targets
- Generate random value between 0 and total weight
- Select target by iterating and subtracting weights
Configuration
Basic Load Balancing
Distribute requests equally across targets:Weighted Load Balancing
Control the distribution with explicit weights:- OpenAI: 70% of requests
- Anthropic: 20% of requests
- Groq: 10% of requests
Cross-Provider Load Balancing
Balance across different providers:When load balancing across providers, ensure the models have similar capabilities to maintain consistent user experience.
Weight Selection Algorithm
The gateway implements weighted random selection:src/handlers/handlerUtils.ts:204-231
Weight Normalization
Weights don’t need to sum to 1.0 - they can be any positive numbers:Use Cases
Rate Limit Management
Distribute load across multiple API keys to avoid rate limits:Cost Optimization
Route to cheaper providers while maintaining a fallback:A/B Testing Models
Test different models with controlled traffic splits:Geographic Distribution
Route to region-specific endpoints:Combining with Other Strategies
Load Balance + Fallback
Balance across primary keys, fallback to secondary provider:- Load balance between sk-1 and sk-2
- If both fail, fall back to Anthropic
Load Balance + Retry
Add retries to each load-balanced target:Load Balance + Cache
Implementation Details
Weight Processing
When entering loadbalance mode:src/handlers/handlerUtils.ts:693-712
Request Flow
Circuit Breaker Integration
Load balancing integrates with circuit breakers to exclude unhealthy targets:src/handlers/handlerUtils.ts:646-658
Unhealthy targets are automatically removed from the load balancing pool.
Monitoring and Metrics
Request Distribution
With proper weights, distribution should match configured percentages over time:Actual Distribution
Monitor actual distribution to ensure weights are working:Small sample sizes may show variance from expected distribution. Statistical convergence occurs over hundreds or thousands of requests.
Best Practices
Start with Equal Weights
Begin with equal distribution and adjust based on performance data.
Monitor Provider Health
Track error rates and latency per provider to inform weight adjustments.
Use Fallbacks Too
Combine load balancing with fallbacks for maximum reliability.
Test Weight Changes
Gradually adjust weights and monitor impact before large changes.
Performance Characteristics
Selection Overhead
- Weight calculation: O(n) where n = number of targets
- Random selection: O(n) worst case
- Total overhead: < 0.1ms for typical configs
Memory Usage
Minimal per-request overhead:- Weight array: 8 bytes per target
- Random value: 8 bytes
- Selected index: 4 bytes
Distribution Quality
The gateway usesMath.random() which provides:
- Uniform distribution
- Sufficient randomness for load balancing
- Fast execution (< 0.01ms)
Common Patterns
Primary-Secondary Split
Multi-Key Rate Limit Avoidance
Cost-Performance Trade-off
Next Steps
Routing
Learn about other routing strategies like fallback and conditional.
Configs
Master the complete configuration system.
Retries
Add retries to load-balanced requests.
Providers
Understand provider capabilities for load balancing.