Core Interfaces
Selector
selector/selector.go:13-19
Rebalancer
selector/selector.go:22-25
Node
selector/selector.go:33-53
Built-in Selectors
Weighted Round Robin (WRR)
Default load balancing strategy:- Weighted distribution based on node weights
- Smooth weighted round-robin algorithm
- No starvation of low-weight nodes
Random
Random selection:- Simple random selection
- Weighted random based on node weights
- Good for simple use cases
P2C (Power of Two Choices)
Latency-aware load balancing:- Selects two random nodes and picks the better one
- Considers latency and success rate
- Better load distribution under varying latencies
- Uses EWMA (Exponentially Weighted Moving Average)
Using Selectors
Global Selector
Set once at application startup:Client Integration
Selectors are automatically used with service discovery:Node Filtering
Filter by Version
Custom Node Filter
selector/filter.go
Multiple Filters
Chain multiple filters:Weighted Nodes
Setting Weights
Set weights via service metadata:Weight Distribution
With WRR selector:- Node A: weight 100 → receives ~66% of traffic
- Node B: weight 50 → receives ~33% of traffic
Peer Context
Access selected node information:Subset Selection
Limit the number of nodes to reduce connection overhead:- Reduces connection overhead for large clusters
- Maintains good load distribution
- Default: 25 nodes
Done Callback
Provide feedback for adaptive load balancing:selector/selector.go:56-66
DoneFunc is automatically called after each request to provide feedback for future selections.
Balancer Interface
Low-level balancer interface:selector/balancer.go:9-11
Weighted Node
selector/balancer.go:19-33
Custom Selector
Implement a custom selector:EWMA Node
Exponentially Weighted Moving Average for latency tracking:Best Practices
Choose Right Selector
Choose Right Selector
- Use WRR for general purpose load balancing
- Use P2C for latency-sensitive applications
- Use Random for simple scenarios
Set Appropriate Weights
Set Appropriate Weights
Weight nodes based on capacity (CPU, memory, network) not just equally.
Use Node Filters
Use Node Filters
Filter by version, region, or environment to control traffic routing.
Enable Subset Selection
Enable Subset Selection
Use subset for large clusters (>25 nodes) to reduce connection overhead.
Monitor Selection
Monitor Selection
Track which nodes are selected to ensure even distribution.
Handle No Available Nodes
Handle No Available Nodes
Always handle
ErrNoAvailable when all nodes are filtered out.Selection Strategies Comparison
| Strategy | Best For | Complexity | Latency Aware |
|---|---|---|---|
| WRR | General purpose, weighted distribution | Low | No |
| Random | Simple scenarios, quick decisions | Very Low | No |
| P2C | Latency-sensitive, uneven load | Medium | Yes |
Complete Example
Related Components
Registry
Service discovery
HTTP Client
HTTP client integration
gRPC Client
gRPC client integration
Metadata
Node metadata