Design an In-Memory Load Balancer with Round Robin, Weighted Round Robin and Least Connections
Quick Overview
Design and implement an in-memory load balancer that registers backend instances by IP and weight and routes requests with round robin, weighted round robin or least connections. It tests rotation state, connection accounting, tie-breaking, and how removals and weight changes affect the rotation.
Design an In-Memory Load Balancer with Round Robin, Weighted Round Robin and Least Connections
Role: Software Engineer
Category: Software Engineering Fundamentals
Difficulty: medium
Interview Round: Other
Design and implement an in-memory load balancer that manages backend server instances and distributes incoming requests across them using configurable strategies.
The load balancer should support registering and deregistering backend instances identified by their IP addresses, each with an associated weight. It must support three distribution strategies: Round Robin, Weighted Round Robin, and Least Connections. The strategy is chosen when the load balancer is created.
Round Robin cycles through registered instances in registration order. Weighted Round Robin serves each instance a number of times equal to its weight before advancing to the next instance. Least Connections selects the instance with the fewest active connections, breaking ties by earliest registration order.
The load balancer tracks active connections per instance. Each call to `get_next_instance` increments the selected instance's connection count. Connections can be released explicitly via `release_connection`.
Implement a class `LoadBalancer(strategy: str)` with the following methods:
- `register(ip: str, weight: int)`: Register a backend instance with the given IP address and weight. If the IP is already registered, update its weight.
- `deregister(ip: str) -> bool`: Deregister a backend instance by IP. Returns `True` if the instance was removed, `False` if it was not found.
- `get_next_instance() -> str`: Get the next backend instance according to the configured strategy. Returns an empty string if no instances are registered.
- `release_connection(ip: str) -> bool`: Release one active connection for the given IP. Returns `True` if successful, `False` if the IP is not found or has no active connections.
- `get_connection_count(ip: str) -> int`: Return the number of active connections for the given IP. Returns -1 if the IP is not registered.
- `get_instance_count() -> int`: Return the total number of currently registered backend instances.
Example 1, weighted round robin:
```text
lb = LoadBalancer("weighted_round_robin")
lb.register("10.0.0.1", 2)
lb.register("10.0.0.2", 1)
lb.get_next_instance() # -> "10.0.0.1" (1st of its 2 turns)
lb.get_next_instance() # -> "10.0.0.1" (2nd of its 2 turns)
lb.get_next_instance() # -> "10.0.0.2" (its only turn)
lb.get_next_instance() # -> "10.0.0.1" (the cycle starts again)
lb.get_connection_count("10.0.0.1") # -> 3
lb.release_connection("10.0.0.2") # -> True (1 active connection becomes 0)
lb.release_connection("10.0.0.2") # -> False (no active connections left)
lb.get_connection_count("10.0.0.9") # -> -1 (not registered)
```
Weight 2 gives `10.0.0.1` two requests in a row before `10.0.0.2` gets its single request. Every selection adds an active connection, so `10.0.0.1` has 3 after its third selection.
Example 2, least connections (the comments show the active counts just before each call):
```text
lb = LoadBalancer("least_connections")
lb.register("10.0.0.1", 1)
lb.register("10.0.0.2", 1)
lb.register("10.0.0.3", 1)
lb.get_next_instance() # -> "10.0.0.1" (counts 0, 0, 0)
lb.get_next_instance() # -> "10.0.0.2" (counts 1, 0, 0)
lb.get_next_instance() # -> "10.0.0.3" (counts 1, 1, 0)
lb.release_connection("10.0.0.2") # -> True
lb.get_next_instance() # -> "10.0.0.2" (counts 1, 0, 1)
lb.get_next_instance() # -> "10.0.0.1" (counts 1, 1, 1)
lb.deregister("10.0.0.1") # -> True
lb.get_next_instance() # -> "10.0.0.2" (counts 1, 1 for .2 and .3)
lb.get_instance_count() # -> 2
lb.deregister("10.0.0.1") # -> False (already removed)
```
Every tie goes to the instance registered first, and an IP that is already gone cannot be deregistered a second time.
Example 3, round robin:
```text
lb = LoadBalancer("round_robin")
lb.get_next_instance() # -> "" (nothing registered)
lb.register("10.0.0.1", 1)
lb.register("10.0.0.2", 1)
lb.get_next_instance() # -> "10.0.0.1"
lb.get_next_instance() # -> "10.0.0.2"
lb.get_next_instance() # -> "10.0.0.1"
lb.register("10.0.0.1", 5) # already registered: weight updated, order unchanged
lb.get_instance_count() # -> 2
lb.get_next_instance() # -> "10.0.0.2"
lb.get_connection_count("10.0.0.1") # -> 2
```
With no instances the call returns an empty string. Re-registering an existing IP only changes its weight, so plain round robin keeps the same order and the same connection count.
```hint Data layout
All three strategies depend on registration order. Pick structures that keep that order and still let you look up an IP's weight and connection count in constant time.
```
```hint What the pointers mean
Write down exactly what each rotation index refers to. Then check what should happen to it when an instance before it, at it, or after it is deregistered, and when the current instance's weight changes in the middle of its turn.
```
### Constraints & Assumptions
- `1 <= weight <= 100`
- IP addresses are non-empty strings.
- Strategy is one of `'round_robin'`, `'weighted_round_robin'`, `'least_connections'`.
- At most `10^4` total operations.
- `get_next_instance` returns `''` if no instances are registered.
### Clarifying Questions to Ask
- When an instance is deregistered in the middle of a rotation, should the rotation continue with the instance that would have come next?
- If an instance's weight changes while it is in the middle of its weighted turn, does the new weight apply right away?
- Does an IP that is deregistered and registered again go to the end of the order with zero connections?
- Will several threads call the load balancer at the same time?
### What a Strong Answer Covers
- The data structures for registration order, weights and connection counts, and the cost of each method.
- Correct selection state for round robin and weighted round robin, and the earliest-registration tie rule for least connections.
- How deregistration and weight updates adjust the rotation state so that no instance is skipped or served twice out of turn.
- Connection accounting: a count for every selection under every strategy, no release below zero, and the `-1` and empty-string returns.
### Follow-up Questions
- How would you pick the least-connections instance faster than a linear scan per request?
- Weighted round robin as specified sends a heavy instance its requests in a burst. How would you spread them out?
- How would you add health checks so that a failing instance stops receiving traffic?
- What has to change if many threads call `get_next_instance` and `release_connection` concurrently?
Overview: Design and implement an in-memory load balancer that registers backend instances by IP and weight and routes requests with round robin, weighted round robin or least connections. It tests rotation state, connection accounting, tie-breaking, and how removals and weight changes affect the rotation.
Design and implement an in-memory load balancer that manages backend server instances and distributes incoming requests across them using configurable strategies.
The load balancer should support registering and deregistering backend instances identified by their IP addresses, each with an associated weight. It must support three distribution strategies: Round Robin, Weighted Round Robin, and Least Connections. The strategy is chosen when the load balancer is created.
Round Robin cycles through registered instances in registration order. Weighted Round Robin serves each instance a number of times equal to its weight before advancing to the next instance. Least Connections selects the instance with the fewest active connections, breaking ties by earliest registration order.
The load balancer tracks active connections per instance. Each call to get_next_instance increments the selected instance's connection count. Connections can be released explicitly via release_connection.
Implement a class LoadBalancer(strategy: str) with the following methods:
register(ip: str, weight: int)
: Register a backend instance with the given IP address and weight. If the IP is already registered, update its weight.
deregister(ip: str) -> bool
: Deregister a backend instance by IP. Returns
True
if the instance was removed,
False
if it was not found.
get_next_instance() -> str
: Get the next backend instance according to the configured strategy. Returns an empty string if no instances are registered.
release_connection(ip: str) -> bool
: Release one active connection for the given IP. Returns
True
if successful,
False
if the IP is not found or has no active connections.
get_connection_count(ip: str) -> int
: Return the number of active connections for the given IP. Returns -1 if the IP is not registered.
get_instance_count() -> int
: Return the total number of currently registered backend instances.
Example 1, weighted round robin:
lb = LoadBalancer("weighted_round_robin")
lb.register("10.0.0.1", 2)
lb.register("10.0.0.2", 1)
lb.get_next_instance() # -> "10.0.0.1" (1st of its 2 turns)
lb.get_next_instance() # -> "10.0.0.1" (2nd of its 2 turns)
lb.get_next_instance() # -> "10.0.0.2" (its only turn)
lb.get_next_instance() # -> "10.0.0.1" (the cycle starts again)
lb.get_connection_count("10.0.0.1") # -> 3
lb.release_connection("10.0.0.2") # -> True (1 active connection becomes 0)
lb.release_connection("10.0.0.2") # -> False (no active connections left)
lb.get_connection_count("10.0.0.9") # -> -1 (not registered)
Weight 2 gives 10.0.0.1 two requests in a row before 10.0.0.2 gets its single request. Every selection adds an active connection, so 10.0.0.1 has 3 after its third selection.
Example 2, least connections (the comments show the active counts just before each call):
With no instances the call returns an empty string. Re-registering an existing IP only changes its weight, so plain round robin keeps the same order and the same connection count.
Constraints & Assumptions
1 <= weight <= 100
IP addresses are non-empty strings.
Strategy is one of
'round_robin'
,
'weighted_round_robin'
,
'least_connections'
.
At most
10^4
total operations.
get_next_instance
returns
''
if no instances are registered.
Clarifying Questions to Ask Guidance
When an instance is deregistered in the middle of a rotation, should the rotation continue with the instance that would have come next?
If an instance's weight changes while it is in the middle of its weighted turn, does the new weight apply right away?
Does an IP that is deregistered and registered again go to the end of the order with zero connections?
Will several threads call the load balancer at the same time?
What a Strong Answer Covers Guidance
The data structures for registration order, weights and connection counts, and the cost of each method.
Correct selection state for round robin and weighted round robin, and the earliest-registration tie rule for least connections.
How deregistration and weight updates adjust the rotation state so that no instance is skipped or served twice out of turn.
Connection accounting: a count for every selection under every strategy, no release below zero, and the
-1
and empty-string returns.
Follow-up Questions Guidance
How would you pick the least-connections instance faster than a linear scan per request?
Weighted round robin as specified sends a heavy instance its requests in a burst. How would you spread them out?
How would you add health checks so that a failing instance stops receiving traffic?
What has to change if many threads call
get_next_instance
and
release_connection
concurrently?