A load balancer built from scratch in Python using asyncio and aiohttp. Inspired by John Crickett's Coding Challenges.
- Round-Robin routing across multiple backend servers
- Health Checks — periodic pings to backends, automatically removes unhealthy servers and re-adds them when they recover
- Async I/O — handles concurrent connections efficiently using
asyncio - Fault Tolerance — returns 502 on backend failure, 503 when no healthy backends available
Client Request
│
▼
┌─────────────┐
│Load Balancer│ (port 8080)
└─────┬───────┘
│ Round Robin
├──────────────┬──────────────┐
▼ ▼ ▼
┌──────────┐ ┌──────────┐ ┌──────────┐
│Backend :1│ │Backend :2│ │Backend :3│
│ (8081) │ │ (8082) │ │ (8083) │
└──────────┘ └──────────┘ └──────────┘
- Python 3.8+
- pip
git clone https://github.com/<your-username>/LoadBalancer.git
cd LoadBalancer
pip install -r requirements.txt1. Start backend servers (each in a separate terminal):
python backend.py 8081
python backend.py 8082
python backend.py 80832. Start the load balancer:
# Basic (round-robin only)
python load_balancer.py
# With health checks
python health_check.py3. Send requests:
curl http://localhost:8080/
curl http://localhost:8080/
curl http://localhost:8080/Each request will be routed to a different backend in round-robin order.
- Start all backends and
health_check.py - Kill one backend (e.g., Ctrl+C on port 8082)
- Wait ~10 seconds — the load balancer will detect it's down and stop routing to it
- Restart the backend — it will be automatically added back to the pool
├── backend.py # Simple HTTP backend server
├── load_balancer.py # Basic load balancer with round-robin
├── health_check.py # Load balancer with health checks
├── requirements.txt # Python dependencies
└── README.md
- The load balancer listens on port 8080 for incoming HTTP requests
- For each request, it selects the next backend using round-robin
- It forwards the request (method, headers, body) to the chosen backend
- The backend's response is returned to the client
- (With health checks) A background task pings each backend every 10 seconds and updates the healthy pool
- Python
asyncio— asynchronous I/O aiohttp— async HTTP client/server framework