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.

Easy Python 3.9+ Aug 9, 2026 System design patterns 13 views 0 copies

Python code

14 lines
Python 3.9+
def 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

stdout
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

  1. Use `itertools.cycle` and `zip` to pair requests with servers in a more functional style
  2. 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

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from System design patterns

Related tutorials and quizzes for this topic.