Deque Rotate Drives Round-Robin Selection

deque.rotate(-1) slides the chosen head item to the tail in one in-place step, turning a fixed list of endpoints into a fair round-robin selector.

PythonResilience

Code

pythonsnippet
17 lines
from collections import deque

endpoints = deque(["api-1", "api-2", "api-3"])

def next_endpoint() -> str:
    # Round-robin pick: read the head, then rotate one step left so it queues at the tail
    chosen = endpoints[0]
    endpoints.rotate(-1)
    return chosen

for turn in range(6):
    print(f"turn {turn}: {next_endpoint()}")

# After 6 picks (a multiple of 3) the order is restored; rotate(1) turns the other way
print("cycle restored:", list(endpoints) == ["api-1", "api-2", "api-3"])
endpoints.rotate(1)
print("after rotate(1):", list(endpoints))

Output

Captured from a sandboxed run of this snippet in the build pipeline.

turn 0: api-1
turn 1: api-2
turn 2: api-3
turn 3: api-1
turn 4: api-2
turn 5: api-3
cycle restored: True
after rotate(1): ['api-3', 'api-1', 'api-2']

What the demo rotates

next_endpoint reads endpoints[0] and calls rotate(-1), moving the chosen head to the tail in one in-place step. Six turns print api-1, api-2 and api-3 twice, so the fixed list becomes a fair round-robin selector with no reordering code.

After six picks, a multiple of three, the list order is restored and the cycle restored check prints True. rotate(1) then turns the opposite direction, printing the list shifted one step the other way.

Points to remember

  • rotate is O(k) for k steps and never rebuilds the deque.
  • Negative rotates left; positive rotates right.

Interactive Tools for This Topic

FAQ

Why rotate instead of popping and appending?
rotate(-1) moves every element one slot in a single deque operation; pop-plus-append on a list does the same, but rotate keeps the structure and the round-robin intent explicit.