Round-Robin Load Balancer with Capacity and Shutdown
Data Structure DesignAuto-graded · 16 test casesLast updated
Tests stateful system simulation with round-robin target selection, connection lifecycle tracking, capacity enforcement, and target shutdown with eviction ordering.
You are building a load balancer that distributes client connections across multiple backend servers.
The system manages N backend servers, numbered from 0 to N - 1. Each server can handle at most max_capacity simultaneous connections.
Your task is to process a sequence of commands that modify the load balancer's state. All commands execute in order on a single thread.
Commands
connect
["connect", connection_id]
Assign a new connection to a backend server using round-robin selection, or return the existing assignment if this connection is already active.
Behavior:
- If
connection_idis already assigned to a server, return that server's index without changing any state - Otherwise, starting from the current round-robin position, search in circular order for the first server that:
- Has not been shut down
- Has fewer than
max_capacityactive connections
- If such a server is found:
- Assign the connection to that server
- Move the round-robin pointer to the next position (wrapping around to 0 after N-1)
- Return the server's index
- If no server can accept the connection, return
-1without changing any state
disconnect
["disconnect", connection_id]
Remove an active connection.
Behavior:
- If
connection_idis currently assigned to a server:- Remove the connection
- Free up one slot on that server
- Return
true
- Otherwise, return
false
The round-robin pointer is never affected by disconnect operations.
shutdown
["shutdown", server_index]
Take a server offline and evict all its active connections.
Behavior:
- If the server is already shut down, return an empty list
- Otherwise:
- Mark the server as unavailable for future connections
- Collect all connection IDs currently on that server
- Remove all those connections from the system
- Return the list of evicted connection IDs in the order they were originally connected to that server
Once a server is shut down, it remains unavailable for the rest of the simulation.
Output
Return a list containing one result per command:
connectreturns an integer (server index or-1)disconnectreturns a booleanshutdownreturns a list of connection IDs
Constraints
- 1 ≤ N ≤ 10,000
- 0 ≤ max_capacity ≤ 1,000
- 1 ≤ number of operations ≤ 50,000
- Connection IDs are strings or integers, unique per logical connection
- All operations are processed sequentially
Examples
Example 1
Input: process_load_balancer_commands(3, 2, [['connect', 'a'], ['connect', 'b'], ['connect', 'c'], ['connect', 'd'], ['connect', 'e'], ['disconnect', 'b'], ['connect', 'f'], ['shutdown', 0], ['connect', 'g']])
Output: [0, 1, 2, 0, 1, True, 2, ['a', 'd'], 1]
Hints
Hint 1
Use a hash map to track which server each connection is assigned to for O(1) duplicate detection
Hint 2
Maintain an insertion-ordered collection per server to support eviction in connection-creation order
Hint 3
Consider a segment tree or similar structure to efficiently find the next available server in round-robin order, avoiding O(N) scans when most servers are full or shut down
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This problem requires maintaining several coordinated pieces of state to simulate a stateful load balancer:
- Connection tracking: A hash map from connection ID to assigned server enables O(1) duplicate detection and disconnect lookup
- Per-server connection lists: Each server maintains connections in insertion order using Python's dict (which preserves insertion order), allowing efficient eviction ordering during shutdown
- Capacity and availability: Arrays track active connection counts and shutdown status per server
- Efficient server selection: A segment tree accelerates the round-robin search by storing availability counts, avoiding O(N) scans when many servers are full or offline
Round-Robin with Segment Tree
The naive approach scans from the current pointer forward (wrapping around) until finding an available server. This costs O(N) per connect and degrades when most servers are unavailable.
Instead, we use a segment tree where each leaf represents whether a server is available (not shut down and below capacity). Each internal node stores the count of available servers in its range.
To find the next available server:
- Query range
[pointer, n-1]for the first available index - If not found, query
[0, pointer-1]to handle wraparound - If both fail, return
-1and leave all state unchanged
The segment tree query runs in O(log N) because we prune branches with zero available servers.
Operation Details
connect: Check if the connection already exists (return existing server). Otherwise, use the segment tree to find an available server. On success, record the assignment, increment the server's count, update the tree, and advance the pointer. On failure, return -1 without side effects.
disconnect: Look up the connection. If found, remove it from both the global map and the server's connection dict, decrement the count, and update the tree. The pointer never changes.
shutdown: If already shut down, return empty list. Otherwise, mark as unavailable, snapshot all connection IDs in insertion order, remove them from the global map, clear the server's connections, and update the tree.
Correctness
The invariant is maintained: a connection ID appears in connection_map if and only if it appears in exactly one server's connection dict, and each server's count equals the size of its dict. The segment tree leaf accurately reflects availability. Every operation either returns early with no changes or updates all structures consistently.
Eviction order is guaranteed because Python dicts preserve insertion order, and connections are only inserted on successful connect operations.
Complexity
Time:
connect: O(log N) for segment tree search and updatedisconnect: O(log N) for tree updateshutdown: O(k + log N) where k is evicted connections; amortized O(log N) per operation since each connection is evicted at most once
Space: O(N + C) where C is the number of live connections; segment tree uses O(N) space
from typing import List
def process_load_balancer_commands(num_servers, max_capacity, commands):
n = num_servers
capacity = max_capacity
connection_map = {}
server_connections = [dict() for _ in range(n)]
active_counts = [0] * n
is_shutdown = [False] * n
round_robin_pos = 0
# Segment tree to efficiently find available servers
tree_size = 1
while tree_size < n:
tree_size *= 2
segment_tree = [0] * (2 * tree_size)
def is_available(server):
return int(not is_shutdown[server] and active_counts[server] < capacity)
def update_tree(server):
pos = tree_size + server
segment_tree[pos] = is_available(server)
pos //= 2
while pos:
segment_tree[pos] = segment_tree[2 * pos] + segment_tree[2 * pos + 1]
pos //= 2
def find_available(node, left, right, query_left, query_right):
if right < query_left or left > query_right or segment_tree[node] == 0:
return -1
if left == right:
return left if left < n else -1
mid = (left + right) // 2
result = find_available(2 * node, left, mid, query_left, query_right)
if result != -1:
return result
return find_available(2 * node + 1, mid + 1, right, query_left, query_right)
for server in range(n):
update_tree(server)
output = []
for command in commands:
operation = command[0]
params = command[1:]
if operation == "connect":
conn_id = params[0]
if conn_id in connection_map:
output.append(connection_map[conn_id])
continue
server = find_available(1, 0, tree_size - 1, round_robin_pos, n - 1)
if server == -1:
server = find_available(1, 0, tree_size - 1, 0, round_robin_pos - 1)
if server == -1:
output.append(-1)
continue
connection_map[conn_id] = server
server_connections[server][conn_id] = None
active_counts[server] += 1
update_tree(server)
round_robin_pos = (server + 1) % n
output.append(server)
elif operation == "disconnect":
conn_id = params[0]
if conn_id not in connection_map:
output.append(False)
continue
server = connection_map.pop(conn_id)
del server_connections[server][conn_id]
active_counts[server] -= 1
update_tree(server)
output.append(True)
elif operation == "shutdown":
server = params[0]
if is_shutdown[server]:
output.append([])
continue
is_shutdown[server] = True
evicted_connections = list(server_connections[server])
for conn_id in evicted_connections:
del connection_map[conn_id]
server_connections[server].clear()
active_counts[server] = 0
update_tree(server)
output.append(evicted_connections)
return output