LB - s50600822/Notes GitHub Wiki

Algo

Round robin:

This is the simplest and most common load balancing algorithm. It simply distributes requests evenly across all available servers.

def round_robin(servers):
  """Round robin load balancer.

  Args:
    servers: A list of servers.

  Returns:
    The next server in the round robin rotation.
  """

  current_server = 0
  while True:
    try:
      return servers[current_server]
    except IndexError:
      current_server = 0
    else:
      current_server = (current_server + 1) % len(servers)

Least connections:

This algorithm sends requests to the server with the fewest active connections.

Least response time:

This algorithm sends requests to the server with the fastest response time.

Weighted round robin:

This algorithm is similar to round-robin, but it allows you to assign weights to each server. This means that you can prioritize certain servers over others.

def weighted_round_robin(servers, weights):
    """Weighted round robin load balancer.

    Args:
        servers: A list of servers.
        weights: A list of weights, one for each server.

    Returns:
        The next server in the weighted round robin rotation.
    """

    total_weight = sum(weights)
    current_weight = 0

    while True:
        server_index = current_weight // total_weight
        yield servers[server_index]
        current_weight += weights[server_index]


servers = ['Server 1', 'Server 2', 'Server 3']
weights = [1, 2, 3]

load_balancer = weighted_round_robin(servers, weights)

for _ in range(10):
    next_server = next(load_balancer)
    print(next_server)  

Hashing:

This algorithm distributes requests based on a hash of the request data. This can be useful for ensuring that requests are distributed evenly across servers, even if the number of servers changes.