README
ΒΆ
Balance
βοΈ A High-Performance Load Balancer Written in Go
Distribute traffic efficiently with intelligent load balancing algorithms
Features β’ Installation β’ Quick Start β’ Documentation β’ Contributing
π Features
Balance is a production-ready load balancer that offers:
π― Load Balancing Algorithms
- Round Robin - Distribute requests evenly across all servers
- Weighted Round Robin - Assign different weights to servers based on capacity
- Least Connections - Route to server with fewest active connections
- Weighted Least Connections - Combine connection count with server weights
- Consistent Hashing - Session persistence through hash-based routing
- Bounded Consistent Hashing - Consistent hashing with configurable virtual nodes
- Session Affinity - Sticky sessions based on client IP or cookies
π₯ Health Checking
-
Active Health Checks - Periodic probing of backend servers
- Configurable intervals and timeouts
- HTTP/TCP health check support
- Worker pool-based concurrent checking
- Automatic unhealthy node removal
-
Passive Health Checks - Monitor real traffic patterns
- Failure tracking and circuit breaking
- Configurable failure thresholds
- Automatic recovery mechanisms
- Time-bucketed failure analysis
π Security Features
- Rate Limiting - Token bucket algorithm for request throttling
- IP Whitelisting/Blacklisting - Control access by IP address
- TLS/SSL Support - Secure connections with certificate management
- Security Manager - Centralized security policy enforcement
π Protocol Support
- HTTP/HTTPS - Full HTTP reverse proxy with header manipulation
- TCP - Raw TCP connection forwarding
- HTTP/2 - Modern protocol support
βοΈ Advanced Features
- Dynamic Configuration - YAML-based configuration with hot reload support
- Connection Pooling - Efficient connection reuse
- Graceful Shutdown - Clean termination without dropping connections
- Metrics & Monitoring - Built-in observability
- Cross-Platform - Linux, macOS, Windows support
π Table of Contents
- Installation
- Quick Start
- Configuration
- Load Balancing Algorithms
- Health Checking
- Security
- Development
- Architecture
- Benchmarks
- Roadmap
- Contributing
- License
π¦ Installation
Using Go Install
go install github.com/utkarsh5026/balance/cmd/balance@latest
Build from Source
# Clone the repository
git clone https://github.com/utkarsh5026/balance.git
cd balance
# Build using Makefile
make build
# Or build manually
go build -o balance ./cmd/balance
Pre-built Binaries
Download the latest release for your platform from the Releases page.
π Quick Start
1. Create a Configuration File
Create a config.yaml file:
mode: http
listen: :8080
balance:
strategy: round-robin
nodes:
- address: localhost:8081
weight: 1
- address: localhost:8082
weight: 2
- address: localhost:8083
weight: 1
health:
active:
enabled: true
interval: 10s
timeout: 5s
unhealthy_threshold: 3
passive:
enabled: true
max_failures: 5
failure_window: 60s
2. Run Balance
./balance -config config.yaml
3. Test It Out
# Send requests to your load balancer
curl http://localhost:8080
# Requests will be distributed across your backend servers
βοΈ Configuration
Balance uses YAML configuration files. Here's a comprehensive example:
# Server mode: "http" or "tcp"
mode: http
# Address to listen on
listen: :8080
# Load balancing configuration
balance:
strategy: weighted-round-robin # round-robin, least-connections, consistent-hash, etc.
# Backend nodes
nodes:
- address: backend1:8081
weight: 3
max_connections: 1000
- address: backend2:8082
weight: 2
max_connections: 500
- address: backend3:8083
weight: 1
max_connections: 250
# Session affinity (optional)
affinity:
enabled: true
cookie_name: BALANCEID
ttl: 3600s
# Health check configuration
health:
active:
enabled: true
interval: 10s
timeout: 5s
healthy_threshold: 2
unhealthy_threshold: 3
path: /health # For HTTP health checks
passive:
enabled: true
max_failures: 5
failure_window: 60s
recovery_time: 30s
# Security configuration
security:
rate_limit:
enabled: true
requests_per_second: 100
burst: 200
ip_filter:
enabled: true
whitelist:
- 192.168.1.0/24
- 10.0.0.0/8
blacklist:
- 203.0.113.0/24
# TLS configuration (optional)
tls:
enabled: true
cert_file: /path/to/cert.pem
key_file: /path/to/key.pem
min_version: TLS12
Configuration Examples
Check the config/examples/ directory for more configuration examples:
round-robin.yaml- Basic round-robinweighted-round-robin.yaml- Weighted distributionleast-connections.yaml- Connection-based routingconsistent-hash.yaml- Hash-based routingsession-affinity.yaml- Sticky sessionstls.yaml- TLS/SSL configuration
π― Load Balancing Algorithms
Round Robin
Distributes requests evenly across all healthy backend servers.
balance:
strategy: round-robin
Best for: Servers with similar capacity and uniform request patterns.
Weighted Round Robin
Routes requests based on assigned weights, sending more traffic to higher-capacity servers.
balance:
strategy: weighted-round-robin
nodes:
- address: powerful-server:8080
weight: 5
- address: standard-server:8080
weight: 1
Best for: Heterogeneous server configurations.
Least Connections
Routes to the server with the fewest active connections.
balance:
strategy: least-connections
Best for: Long-lived connections or varying request durations.
Consistent Hashing
Uses consistent hashing for session persistence and cache efficiency.
balance:
strategy: consistent-hash
hash_key: client_ip # or cookie, header, etc.
virtual_nodes: 150
Best for: Stateful applications and caching scenarios.
Session Affinity
Binds client sessions to specific backend servers.
balance:
strategy: round-robin # Base strategy
affinity:
enabled: true
cookie_name: SESSION_ID
ttl: 3600s
Best for: Applications requiring session state.
π₯ Health Checking
Active Health Checks
Balance periodically probes backend servers to verify availability.
health:
active:
enabled: true
interval: 10s # Check every 10 seconds
timeout: 5s # Timeout after 5 seconds
healthy_threshold: 2 # 2 successes to mark healthy
unhealthy_threshold: 3 # 3 failures to mark unhealthy
path: /health # HTTP path to check
expected_status: 200 # Expected HTTP status
Features:
- π Concurrent health checking with worker pools
- π Configurable thresholds
- π¦ Automatic node state management
- β‘ Non-blocking health checks
Passive Health Checks
Monitors real traffic to detect failures.
health:
passive:
enabled: true
max_failures: 5 # Max failures before marking unhealthy
failure_window: 60s # Time window for failure counting
recovery_time: 30s # Time before retry
Features:
- π― Real-time failure detection
- π Time-bucketed failure tracking
- π Automatic recovery
- π‘ Circuit breaker pattern
π Security
Rate Limiting
Protect your backend from overload with token bucket rate limiting.
security:
rate_limit:
enabled: true
requests_per_second: 100 # Sustained rate
burst: 200 # Burst capacity
IP Filtering
Control access with IP whitelists and blacklists.
security:
ip_filter:
enabled: true
whitelist:
- 192.168.1.0/24
- 10.0.0.0/8
blacklist:
- 198.51.100.0/24
TLS/SSL
Secure connections with TLS termination.
tls:
enabled: true
cert_file: /path/to/cert.pem
key_file: /path/to/key.pem
min_version: TLS12
cipher_suites:
- TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256
- TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384
π» Development
Prerequisites
- Go 1.25.1 or higher
- Make (optional, for using Makefile)
Development Setup
# Clone the repository
git clone https://github.com/utkarsh5026/balance.git
cd balance
# Install development tools
make install-tools
# Run tests
make test
# Run with race detector
make test-race
# Check code quality
make check
# Run security scans
make security
Makefile Commands
Balance includes a comprehensive Makefile for development:
make help # Show all available commands
make build # Build the binary
make test # Run all tests
make run # Run with example config
make ci # Run full CI pipeline locally
make pre-commit # Pre-commit checks
make security # Security scans
See MAKEFILE_GUIDE.md for detailed documentation.
Running Tests
# All tests with coverage
make test
# Short tests (skip integration)
make test-short
# Integration tests only
make test-integration
# Benchmarks
make bench
# Coverage report
make coverage
Code Quality
# Format code
make fmt
# Run linters
make lint
# Static analysis
make staticcheck
# All quality checks
make check
ποΈ Architecture
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β Balance β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β β
β ββββββββββββββββ ββββββββββββββββ ββββββββββββββββ β
β β Security β β Router β β Health β β
β β Manager βββββΆβ ββββββ Checker β β
β ββββββββββββββββ ββββββββββββββββ ββββββββββββββββ β
β β β β β
β β β β β
β ββββββββΌβββββββββββββββββββββΌβββββββββββββββββββββΌβββββββ β
β β Load Balancer Engine β β
β β ββββββββββββββββββββββββββββββββββββββββββββββββββ β β
β β β Strategy: RR / LeastConn / Hash / Affinity β β β
β β ββββββββββββββββββββββββββββββββββββββββββββββββββ β β
β ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β
β β β
β βββββββββββββββββββΌββββββββββββββββββ β
β β β β β
β ββββββββΌβββββββ ββββββββΌβββββββ ββββββββΌβββββββ β
β β Backend 1 β β Backend 2 β β Backend 3 β β
β β (Healthy) β β (Healthy) β β (Unhealthy) β β
β βββββββββββββββ βββββββββββββββ βββββββββββββββ β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
Key Components
- Router - Request routing and distribution
- Load Balancer - Algorithm implementation
- Health Checker - Active and passive health monitoring
- Security Manager - Rate limiting and IP filtering
- Connection Pool - Efficient connection management
- Node Manager - Backend server lifecycle management
β‘ Benchmarks
Performance benchmarks on a standard development machine:
goos: windows
goarch: amd64
pkg: github.com/utkarsh5026/balance/pkg/balance
BenchmarkRoundRobin-8 1000000 1045 ns/op 0 B/op 0 allocs/op
BenchmarkWeightedRR-8 500000 2134 ns/op 16 B/op 1 allocs/op
BenchmarkLeastConn-8 300000 3876 ns/op 32 B/op 2 allocs/op
BenchmarkConsistentHash-8 200000 6542 ns/op 64 B/op 3 allocs/op
Run benchmarks locally:
make bench
πΊοΈ Roadmap
Balance is under active development. Planned features:
v0.2.0 (Next Release)
- π Prometheus metrics exporter
- π Enhanced observability and tracing
- π gRPC support
- π Access logging with rotation
- π Dynamic backend registration/removal
v0.3.0
- ποΈ Admin API for runtime configuration
- π Real-time dashboard
- π³ Kubernetes service discovery
- π OAuth2/OIDC authentication
- π Geo-routing capabilities
Future
- WebSocket support
- Layer 4 (TCP/UDP) load balancing enhancements
- Machine learning-based routing
- Multi-region support
- Plugin system for custom algorithms
See ROADMAP.md for detailed plans.
π Status
β οΈ Development Status: Balance is currently in active development and not yet recommended for production use. APIs may change between versions.
Current Version: v0.1.0-alpha Go Version: 1.25.1 License: MIT
What's Working
β All load balancing algorithms β Active and passive health checks β Security features (rate limiting, IP filtering) β HTTP and TCP modes β TLS support β Configuration management
In Progress
π§ Metrics and monitoring π§ Admin API π§ Documentation completion π§ Production hardening
π€ Contributing
Contributions are welcome! Please read our Contributing Guide for details.
How to Contribute
- Fork the repository
- Create a feature branch (
git checkout -b feature/amazing-feature) - Make your changes
- Run tests (
make test) - Run CI locally (
make ci) - Commit your changes (
git commit -m 'Add amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
Development Workflow
# Before committing
make pre-commit
# Before pushing
make pre-push
# Run full CI pipeline
make ci
Code of Conduct
This project adheres to the Contributor Covenant Code of Conduct. By participating, you are expected to uphold this code.
π License
This project is licensed under the MIT License - see the LICENSE file for details.
π Acknowledgments
- Built with β€οΈ using Go
- Inspired by industry-standard load balancers (HAProxy, NGINX)
- Thanks to all contributors
π Contact & Support
- Issues: GitHub Issues
- Discussions: GitHub Discussions
- Security: Report security issues to security@example.com
β Star History
If you find Balance useful, please consider giving it a star! β
Made with βοΈ by utkarsh5026