Round Robin Load Balancer in Python
This code simulates round robin load balancing by distributing a list of requests evenly across a list of servers.
Python code
14 linesdef round_robin_servers(requests: list[str], servers: list[str]) -> dict[str, list[str]]:
assignments = {server: [] for server in servers}
for idx, request in enumerate(requests):
server = servers[idx % len(servers)]
assignments[server].append(request)
return assignments
if __name__ == "__main__":
servers = ["server-a", "server-b", "server-c"]
requests = ["req1", "req2", "req3", "req4", "req5", "req6", "req7"]
result = round_robin_servers(requests, servers)
for server, assigned in result.items():
print(f"{server}: {assigned}")
Output
server-a: ['req1', 'req4', 'req7']
server-b: ['req2', 'req5']
server-c: ['req3', 'req6']
How it works
The round_robin_servers function uses the modulo operator (%) to cycle through the server list as it iterates over requests. For each request index, idx % len(servers) gives the next server in rotation, ensuring an even distribution. The function builds a dictionary where each server maps to a list of its assigned requests. This pattern is a simple yet effective way to understand core load balancing logic without external dependencies.
Common mistakes
- Forgetting to handle an empty servers list, which would cause a ZeroDivisionError
- Assuming the function mutates the input lists instead of returning a new dictionary
- Not preserving the order of requests when grouping by server
- Hard-coding the server count instead of computing it with len(servers)
Variations
- Use `itertools.cycle` and `zip` to pair requests with servers in a more functional style
- Weighted round robin where each server gets a different number of requests based on capacity
Real-world use cases
- Distributing inbound HTTP requests to a pool of backend instances for even load
- Assigning tasks to worker processes in a queue-consumer system
- Balancing database read replicas based on query volume
Sponsored
More from System design patterns
- Build a BFF (Backend for Frontend) Mock Aggregator in Python medium
- Builder pattern for mocking complex objects in Python easy
- Circuit Breaker Pattern in Python: Closed, Open, and Half-Open States medium
- Create a Data Helper Class in Python easy
- Domain Driven Design Aggregate Root Example in Python medium
- Facade Pattern in Python with Mock Simplification medium
Keep learning
Related tutorials and quizzes for this topic.