Problem: Build a simple load balancer
Implement a minimal in-memory load balancer that routes each incoming request to one backend node chosen uniformly at random.
Requirements
-
The load balancer maintains a
set of backend nodes
(e.g., strings or IDs).
-
The number of nodes is bounded by a fixed maximum capacity
K
.
-
Support these operations:
-
addNode(nodeId)
-
Adds a node if it is not already present.
-
If the load balancer is at capacity
K
, define and document what happens (e.g., reject the add / throw).
-
removeNode(nodeId)
-
Removes the node if present; otherwise no-op.
-
route()
(or
getNodeForRequest()
)
-
Returns a node chosen
uniformly at random
from the currently active nodes.
-
If there are
no nodes
, define and document what happens (e.g., return null / throw).
Constraints / Edge cases to handle
-
Adding duplicates.
-
Removing a non-existent node.
-
Routing when empty.
-
Keeping
route()
efficient (ideally O(1)).
Deliverable
Describe the data structures and implement the API (language-agnostic or Java-style).