Smooth weighted round robin
A load balancer picker that shares requests across backends in proportion to integer weights without bursts, lets a backend go down and come back, and always gives the same sequence.
Statement
A load balancer has backends with integer weights, say a = 5, b = 1 and c = 1. Sending five requests in a row to a and then one each to b and c respects the weights but delivers the traffic in bursts. Implement Balancer(backends) with pick() so that the heavy backend's turns are spread out and the same calls always give the same sequence.
Every backend carries a running score that starts at 0. Each pick() does three things in order: it adds each live backend's weight to that backend's score, chooses the live backend with the highest score (the one listed first on a tie), and subtracts the sum of all live weights from the chosen backend's score. It returns the chosen name, or None when no backend is live.
mark_down(name) takes a backend out: it is not picked, its weight is no longer part of the sum, and its score is left alone. mark_up(name) brings a down backend back with a score of 0. Calling mark_down on a backend that is already down, or mark_up on one that is live, changes nothing.
Examples
Balancer([("a", 5), ("b", 1), ("c", 1)])
seven picks → a a b a c a a # then the cycle repeats
scores (a, b, c) at each pick; the live weights sum to 7
after adding chosen after subtracting 7
( 5, 1, 1) a (-2, 1, 1)
( 3, 2, 2) a (-4, 2, 2)
( 1, 3, 3) b ( 1, -4, 3) # b and c tie; b is listed first
( 6, -3, 4) a (-1, -3, 4)
( 4, -2, 5) c ( 4, -2, -2)
( 9, -1, -1) a ( 2, -1, -1)
( 7, 0, 0) a ( 0, 0, 0)
mark_down("c")
six picks → a a a b a a # the live weights now sum to 6Constraints
backends is a list of (name, weight) with unique names and integer weights of at least 1; raise ValueError otherwise. An empty list is allowed, and pick() then returns None. mark_down and mark_up raise KeyError for a name that is not a backend.
Up to 100 backends and 10⁶ picks. O(n) work per pick is fine.