NewWork mode: your Claude Code or Codex on work calls, answering from your project's codeSkip to content
Senior1 view

Implement a weighted Round Robin algorithm (distributing requests across arrays according to their weights, for example 30%, 50%, 20%).

Practice

AI answer

For distribution with a specified ratio, smooth weighted round robin is a good choice: rather than simply selecting the pool with the highest weight, it gradually balances the shares. The $current state must be preserved between requests.

function pickPool(array $pools, array $weights, array &$current): string
{
    if ($pools === [] || array_keys($pools) !== array_keys($weights)) {
        throw new InvalidArgumentException('Pools and weights must have the same keys');
    }

    $total = 0;
    $selected = null;
    $max = PHP_INT_MIN;

    foreach ($weights as $key => $weight) {
        if ($weight <= 0) {
            throw new InvalidArgumentException('Weight must be positive');
        }

        $current[$key] = ($current[$key] ?? 0) + $weight;
        $total += $weight;

        if ($current[$key] > $max) {
            $max = $current[$key];
            $selected = $key;
        }
    }

    $current[$selected] -= $total;
    return $selected;
}

$pools = ['a' => ['...'], 'b' => ['...'], 'c' => ['...']];
$weights = ['a' => 30, 'b' => 50, 'c' => 20];
$current = [];

$key = pickPool($pools, $weights, $current);

Over a sufficiently large number of calls, the shares will be close to 30%, 50%, and 20%. With multiple PHP processes, each process has its own local state; if a single global distribution is required, store the state in a shared store, such as Redis, with atomic updates.