This question evaluates implementation skills for stateful simulation and algorithmic reasoning about load balancing, covering connection stickiness, capacity constraints, ordered re-routing on shutdown, and deterministic tie-breaking while testing data structure management and routing logic.
Implement a simulator for a load balancer that routes long-lived WebSocket connections across m backend servers. You receive a sequence of textual requests. The simulator must maintain internal state (active connections) and output a log of successful routings.
You must support these request types (each part includes all prior rules):
connectionId
: which
serverIndex
it is currently on, and its
objectId
.
objectId
must be routed to the same server (details below).
When routing a connection to a server, choose among eligible servers:
serverIndex
.
A server is ineligible if it is at capacity.
Assume servers are indexed 0 .. m-1.
CONNECT connectionId objectId
DISCONNECT connectionId
SHUTDOWN serverIndex
CONNECT only)For each CONNECT, route the new connection using the routing rules above and log the successful routing.
DISCONNECT)DISCONNECT connectionId removes that active connection (if present) and decrements that server’s load.
DISCONNECT
produces
no log entry
.
Each CONNECT includes an objectId.
objectId
, the new connection
must
be routed to the
same server
as those active connections, even if it is not the least loaded.
objectId
, use normal load balancing.
You are given an array capacity[m], where capacity[i] is the maximum allowed active connections on server i.
CONNECT
has
no eligible server
, it is
rejected
:
no log entry
and
no state change
.
CONNECT
is also
rejected
.
SHUTDOWN)SHUTDOWN s temporarily takes server s out of service and evicts all active connections currently on s.
CONNECT
(including stickiness and capacity).
CONNECT
).
s
is considered
unavailable as a target during the re-routing step
, and then becomes
available again immediately after all evictions are processed
, with load 0.
s
(earliest first) to make the outcome deterministic.
Return the list of log entries in order. Each log entry should be:
connectionId serverIndex
Only successful CONNECT and successful re-routes during SHUTDOWN produce log lines.
connectionId
strings are unique among active connections at the time of
CONNECT
.
DISCONNECT
references a non-existent/ inactive
connectionId
, ignore it.
1 <= m <= 1e5
1 <= number of requests <= 2e5
0 <= capacity[i] <= 1e9