Skip to content
BytePatterns

Least-Connections Load Balancer

MediumSystem Design#least-connections#min-heap#event-simulation~25m

Problem

A load balancer routes each request to the server with the fewest requests in flight, breaking ties by the order the servers are listed. Requests arrive as (arrive, duration) pairs sorted by arrival time, and a request that finishes at time t has already left before one arriving at time t is routed. Return the server chosen for each request, and the peak number of requests each server held at once. There are up to 100,000 requests and a handful of servers.

Examples

Input:  servers = ["a", "b"], requests = [(0, 10), (1, 2), (2, 5), (3, 1), (4, 1)]
Output: (['a', 'b', 'a', 'b', 'b'], {'a': 2, 'b': 1})
Why:    the long request pins a; b keeps emptying just in time for the next short one
Input:  servers = ["a", "b", "c"], requests = [(0, 1), (1, 1), (2, 1)]
Output: (['a', 'a', 'a'], {'a': 1, 'b': 0, 'c': 0})
Why:    each request is gone before the next arrives, so the tie always goes to a
Input:  servers = ["x"], requests = [(0, 5), (1, 5), (2, 5)]
Output: (['x', 'x', 'x'], {'x': 3})
Why:    edge case, with one server the balancer has no choice

Hints

0 / 3

Stuck on the idea rather than the code? Load Balancing covers it.