The user wants a "load balancer that distributes requests across multiple servers." This is a classic system design or programming interview question, or a practical devops task.
1. Understand the Scope and Requirements:
What is a load balancer? A device (software or hardware) that acts as a reverse proxy and distributes network or application traffic across a number of servers.
Goal: High availability, reliability, efficiency.
Algorithms: Round Robin, Least Connections, IP Hash, etc.
Implementation: Needs a server (to receive requests) and a pool of backend servers (to handle requests).
Language: Python is usually the most accessible for examples, but I should mention it can be done in Go, Node.js, etc.
2. Determine the Level of Abstraction:
Option A: High-level architecture description. Good for system design interviews.
Option B: Concrete code implementation. Good for "show me how" requests.
Decision: Provide a concrete, working code example (Python) but explain the concepts first. This makes it practical and educational.
3. Designing the Solution (Code Example):
Language: Python (using http.server and requests or aiohttp is standard). Let's stick to standard library where possible or common ones like requests for simplicity. Actually, using socket or http.server manually is good for understanding, but aiohttp or a reverse proxy approach is more realistic. Let's go with a simple threaded HTTP server using Python's http.server for the load balancer and requests to forward the traffic.
Components:
Backend Servers: Need dummy servers to prove it works. I can simulate these in the same script or ask the user to run them. Let's create a script that spins up a few dummy backend servers and the load balancer itself for a complete demo.
The Load Balancer:
Needs a list of backend URLs.
Needs an algorithm (Round Robin is easiest to implement and understand).
Needs to handle incoming requests and forward them.
Needs to handle responses and send them back to the client.
Health Checks: (Advanced feature, maybe add a simple version or just mention it).
4. Step-by-Step Implementation Plan:
Concepts: Briefly explain what it is and the algorithms (Round Robin, Weighted Round Robin, Least Connections).
The Code (Python):
Part 1: The Algorithm. A class to manage server selection.
Part 2: The Proxy Logic. A handler that intercepts the request, picks a backend, sends the request to the backend, gets the response, and sends it back.
Part 3: The Simulation. Creating dummy servers so the user can actually run the script and test it.
5. Refining the Code (Self-Correction during thought process):
Issue: Forwarding HTTP requests isn't just about the URL. We need to forward headers and body (POST/PUT data).
Library:requests is great, but for a proxy, we need to be careful not to hang. ThreadedHTTPServer is essential so the LB can handle multiple clients.
Safety: What if a server is down? The code should ideally try the next one or return an error. For a simple example, a basic try/except block is sufficient.
6. Structuring the Response:
Introduction: Definition and purpose.
Core Algorithms: Brief explanation of strategies.
Implementation (Python):
Prerequisites (pip install requests).
The Load Balancer Class (Round Robin logic).
The Proxy Handler (Forwarding logic).
The Test Setup (Mock backends).
Running the Code: Instructions.
Production considerations: Mention Nginx/HAProxy as the industry standard (don't reinvent the wheel for prod).
7. Drafting the Python Code:
Imports:http.server, requests, threading, time.
Class LoadBalancer: Maintains an index current_index. Method get_server() increments and wraps around.
Class ProxyHandler: Inherits from SimpleHTTPRequestHandler (actually BaseHTTPRequestHandler is cleaner).
Send response code, headers, content back to client.
8. Adding the "Simulation" aspect:
To make this answer truly useful, I should write a script that creates three servers on different ports (8001, 8002, 8003) and then starts the Load Balancer on port 8000. This allows a "copy-paste-run" experience.
9. Final Polish:
Check for edge cases. What about relative vs absolute URLs? The requests library handles this well usually. What about encoding? requests usually handles content-type well enough for a demo.
Let's refine the logic for the simulation. Threads are needed to run the backends and the LB in the same terminal window/process for the demo.
Summary of Output:
Concept: Round Robin.
Code: A single Python file containing:
Backend simulation logic.
Load Balancer logic (Threading + Proxying).
Main execution block.
This looks solid. It answers the prompt directly, provides working code, and adds context.
Here is a complete, working example of a Round-Robin Load Balancer written in Python.
This script creates a Load Balancer server that listens for traffic on port 8080 and distributes incoming requests to a pool of backend servers (ports 8081, 8082, 8083).
1. The Architecture
The Load Balancer: Accepts HTTP requests from a client (like your browser).
The Strategy (Round Robin): Keeps a counter and forwards the first request to Server A, the second to Server B, the third to Server C, and then loops back to A.
Reverse Proxy: It fetches the response from the backend server and passes it back to the client.
2. The Python Code
Save this code in a file named load_balancer.py.
python
3. How to Run It
Prerequisites: You need Python installed and the requests library.
bash
pip install requests
Run the script:
bash
python load_balancer.py
Test it:
Open your web browser.
Visit http://localhost:8080.
Refresh the page 3 or 4 times.
You will see the text change from "Response from Backend Server on Port 8081" to "8082" to "8083" and back to "8081".
4. Explanation of Logic
RoundRobinLoadBalancer Class: This is the "brain". It holds an index (0, 1, 2...). Every time get_next_backend is called, it returns the server at the current index and increments the counter. The % (modulo) operator ensures that once it hits the end of the list, it wraps around to the beginning.
ProxyHandler Class: This intercepts the HTTP request from the user. instead of processing it, it uses the requests library to forward that exact same request to the backend server chosen by the RoundRobin logic.
Threading: We use ThreadingTCPServer for the Load Balancer. This is crucial. If 100 people connect at once, we don't want the 100th person to wait for the first 99 to finish. Threads allow the Load Balancer to handle multiple connections simultaneously.
Other Load Balancing Algorithms
In a production environment (like Nginx or AWS ALB), you might use different strategies than Round Robin:
Least Connections: Send traffic to the server handling the fewest active requests (better when some requests take a long time).
IP Hash: Hash the client's IP address. This ensures a specific user always gets sent to the same server (useful for session persistence).
Random: Pick a random server.
import http.server
import socketserver
import requests
import threading
import time
import sys
# --- Configuration ---
LOAD_BALANCER_PORT = 8080
BACKEND_SERVERS = [
"http://localhost:8081",
"http://localhost:8082",
"http://localhost:8083"
]
class RoundRobinLoadBalancer:
def __init__(self, backend_urls):
self.backend_urls = backend_urls
self.current_index = 0
self.lock = threading.Lock() # To ensure thread safety
def get_next_backend(self):
"""
Selects the next server in the list using Round Robin algorithm.
"""
with self.lock:
target_url = self.backend_urls[self.current_index]
self.current_index = (self.current_index + 1) % len(self.backend_urls)
return target_url
# Global instance of our load balancing logic
lb_logic = RoundRobinLoadBalancer(BACKEND_SERVERS)
class ProxyHandler(http.server.BaseHTTPRequestHandler):
def do_GET(self):
# 1. Select a backend server
target_url = lb_logic.get_next_backend()
full_url = target_url + self.path
print(f"[LB] Routing request to -> {full_url}")
try:
# 2. Forward the request to the backend
# We use the 'requests' library to act as a client to the backend
resp = requests.get(full_url, timeout=5)
# 3. Send the backend's response back to the original client
self.send_response(resp.status_code)
# Forward headers (Content-Type, etc.)
for key, value in resp.headers.items():
# Avoid hop-by-hop headers like 'Transfer-Encoding' if necessary
if key.lower() not in ['content-encoding', 'transfer-encoding', 'connection']:
self.send_header(key, value)
self.end_headers()
# Forward body
self.wfile.write(resp.content)
except requests.exceptions.RequestException as e:
self.send_response(502) # Bad Gateway
self.end_headers()
self.wfile.write(b"Backend server error")
def log_message(self, format, *args):
# Suppress default logging to keep console clean
pass
# --- Helper Functions to Simulate Backend Servers ---
# (In a real scenario, these would be separate applications/machines)
def start_mock_backend(port):
"""
Creates a simple server that returns its own port number.
This proves the load balancer is switching servers.
"""
class MockHandler(http.server.BaseHTTPRequestHandler):
def do_GET(self):
self.send_response(200)
self.send_header('Content-type', 'text/plain')
self.end_headers()
message = f"Response from Backend Server on Port {port}"
self.wfile.write(message.encode())
def log_message(self, format, *args):
pass # Suppress logging
with socketserver.TCPServer(("", port), MockHandler) as httpd:
# Allow address reuse to prevent "Address already in use" errors on restart
httpd.allow_reuse_address = True
httpd.serve_forever()
if __name__ == "__main__":
# 1. Start the Mock Backend Servers in separate threads
print("Initializing mock backend servers...")
for port in [8081, 8082, 8083]:
t = threading.Thread(target=start_mock_backend, args=(port,), daemon=True)
t.start()
print(f" - Mock server running on port {port}")
# 2. Start the Load Balancer
print(f"\nLoad Balancer listening on port {LOAD_BALANCER_PORT}")
print("Open http://localhost:8080 in your browser multiple times to see it switch servers.")
with socketserver.ThreadingTCPServer(("", LOAD_BALANCER_PORT), ProxyHandler) as lb:
try:
lb.serve_forever()
except KeyboardInterrupt:
print("\nShutting down...")
lb.shutdown()