This project implements a simple round-robin load balancer in Go. It distributes incoming HTTP requests across multiple backend servers, handles server health checks, and simulates server downtime for testing purposes.
- Round-robin load balancing
- Dynamic health checking of backend servers
- Graceful handling of server downtime
- Simulation of random server outages for testing
- Concurrent operation using goroutines
- Go 1.15 or higher
-
Clone the repository:
git clone https://github.com/yourusername/go-load-balancer.git cd go-load-balancer -
Build the project:
go build -o load-balancer
-
Start the load balancer:
./load-balancer -
The load balancer will start on port 8080, and four backend servers will be started on ports 8081, 8082, 8083, and 8084.
-
Send requests to the load balancer:
curl http://localhost:8080 -
Observe the console output to see how requests are distributed and how the system handles simulated server downtime.
The main configuration is done in the main() function:
- Backend servers are defined in the
serversslice. - Health check interval is set to 5 seconds.
- Server downtime simulation occurs every 60 seconds and lasts for 60 seconds.
You can modify these values to suit your testing needs.
main.go: Contains the entire implementation of the load balancer.Serverstruct: Represents a backend server.RoundRobinServerPoolstruct: Manages the pool of servers and implements the load balancing logic.LoadBalancerfunction: Handles incoming requests and forwards them to the next available server.simulateServerDowntimefunction: Simulates random server outages.
- The load balancer initializes a pool of backend servers.
- It starts each backend server and begins health checks.
- When a request comes in, the load balancer selects the next healthy server in a round-robin fashion.
- If a server is down, it's skipped, and the next healthy server is selected.
- Periodically, the
simulateServerDowntimefunction will randomly stop a server and restart it after a delay.
To test the load balancer:
- Start the load balancer.
- Send multiple requests to
http://localhost:8080. - Observe the console output to see how requests are distributed.
- Wait for the downtime simulation to occur and observe how the system handles server outages.
- The current implementation uses a simple round-robin algorithm. More sophisticated algorithms could be implemented.
- The project could benefit from more comprehensive logging and metrics.
- Configuration is currently hardcoded. Adding a configuration file or command-line flags would improve flexibility.