Scrivio Interview library
CodingFoundations6 min read · updated 13 November 2026

A Java client calls a list of service instances directly and needs a simple balancer that sends each request to a lightly loaded instance. Each instance object tracks its number of in-flight requests in an AtomicInteger.

Write a power-of-two-choices picker in Java and explain why it beats picking the least loaded instance from the whole list.

The picker chooses two different instances at random with ThreadLocalRandom and returns the one with fewer in-flight requests; the caller increments that instance's counter before sending and decrements it in a finally block. It beats scanning for the least loaded instance because the scan costs O(n) per request and makes every client pick the same 'best' instance at once, overloading it, while two random choices cost O(1), avoid that herding and still steer away from busy instances.

Why this question is asked

Client-side load balancing is common in Java services: Spring Cloud LoadBalancer, gRPC clients and many internal libraries pick an instance themselves instead of going through a proxy. Power of two choices is one of the best simple algorithms for this, and writing it is a nice small coding question because the obvious code has two subtle bugs. Interviewers ask it to see whether we write the picking logic correctly, manage the counters safely, and can explain why random beats 'always the best'. In this answer, we will recap the setup, write a first naive version and see what goes wrong, then write the correct picker, add the counting around the call, handle edge cases, and explain why it works.

1A Quick Recap of the Setup

Each Instance object holds an AtomicInteger called inFlight, the number of requests this client has sent to that instance and not yet finished. An AtomicInteger is a thread-safe integer that many request threads can increment and decrement without locks.

Power of two choices works like this: pick two different instances at random, compare their inFlight values, and send the request to the one with fewer. Our job is to write that picker and the code that keeps inFlight accurate.

Java
record Instance(String address, AtomicInteger inFlight, boolean healthy) {}

2A Naive Version and Its Bugs

A first attempt usually looks like the code below. It compiles and seems to work in a quick test.

Java
Instance pick(List<Instance> list) {
Random rnd = new Random(); // new object per call, shared seed issues
Instance x = list.get(rnd.nextInt(list.size()));
Instance y = list.get(rnd.nextInt(list.size())); // may be the same as x
return x.inFlight().get() < y.inFlight().get() ? x : y;
}

There are two problems. First, the two picks can be the same instance, about one time in n, and then we have effectively made one random choice, losing the benefit exactly when it matters most with few instances. Second, creating a Random per call is wasteful, and sharing one Random across threads causes contention; ThreadLocalRandom.current() gives each thread its own fast generator. The code also ignores an empty list, a single instance and unhealthy instances.

3A Correct Picker

To pick two distinct indexes without retrying, we choose a in [0, n) and b in [0, n - 1), and if b is at or after a we shift it up by one. That maps b onto every index except a, with equal probability.

Java
final class PowerOfTwoPicker {
Instance pick(List<Instance> all) {
List<Instance> list = all.stream().filter(Instance::healthy).toList();
int n = list.size();
if (n == 0) throw new IllegalStateException("no healthy instances");
if (n == 1) return list.get(0); // nothing to compare
ThreadLocalRandom rnd = ThreadLocalRandom.current();
int a = rnd.nextInt(n); // e.g. 3
int b = rnd.nextInt(n - 1); // e.g. 3
if (b >= a) b++; // b becomes 4: never equal to a
Instance x = list.get(a), y = list.get(b);
return x.inFlight().get() <= y.inFlight().get() ? x : y; // 4 in flight vs 11 -> x
}
}

Notice that the comparison reads two counters at slightly different moments, so it is a snapshot that may be a little stale. That is fine: the algorithm only needs a rough sense of which instance is busier. Filtering healthy instances on every call copies the list; in a hot path we would keep a pre-filtered list that is updated when health changes.

4Counting In-Flight Requests Correctly

The picker is only as good as the counters. We increment inFlight right before sending, so concurrent picks see the new request, and decrement in a finally block, so a failure, timeout or exception never leaves the count inflated. A counter that only goes up would make an instance look permanently busy, and it would gradually stop receiving traffic.

XML
<T> T call(Function<Instance, T> request) {
Instance target = picker.pick(instances);
target.inFlight().incrementAndGet(); // 4 -> 5
try {
return request.apply(target);
} finally {
target.inFlight().decrementAndGet(); // 5 -> 4, even on a timeout
}
}
Step throughOne request through the picker
CallerPickerInstance 3Instance 4
pick()
read inFlight: 4
read inFlight: 11
instance 3
inFlight 4 -> 5, send request
response or error
finally: inFlight 5 -> 4

7 messages in order. Play them, or step through them one at a time.

For asynchronous clients, such as WebClient or a CompletableFuture-based call, the decrement belongs in the completion callback, for example whenComplete, because the method returns before the request finishes.

5Why Two Random Choices Beat the Least Loaded

Scanning the whole list for the minimum costs O(n) per request, which adds up with hundreds of instances and thousands of requests per second. The bigger problem is herding. Many client instances run this code independently, and if they all scan and see that instance 7 has the lowest count, they all send to it at once. Because each client only sees its own in-flight counts, and they all react to the same signals, instance 7 receives a burst and becomes the busiest, then they all move to the next 'best' one.

Two random choices cost O(1), and different clients pick different random pairs, so their choices spread out. Yet each choice still avoids the busier of two candidates, which is enough to cut the worst-case load dramatically. In the classic balls-into-bins analysis, the most loaded bin with one random choice grows like log n / log log n, while with two choices it drops to about log log n, an exponential improvement from one extra comparison.

Ways to pick an instance
MethodCost per requestBehaviour with many clients
One random choiceO(1)spreads, but some instances get unlucky
Scan for least loadedO(n)herding: all clients pick the same one
Power of two choicesO(1)spreads and avoids busy instances

6Follow-up questions

How would you add weights for instances of different sizes?

Compare load relative to capacity instead of raw counts. Give each instance a weight, for example 2 for an instance with twice the cores, and compare inFlight divided by weight, so an instance with weight 2 and 8 in flight counts as 4. To make larger instances also appear more often as candidates, we can pick the two candidates with probability proportional to weight, for example by sampling from a cumulative weight array with a binary search, which is O(log n).

Why use <= rather than < in the comparison?

Either works; with <= ties go to the first candidate, which is random anyway, so there is no bias toward any instance. What matters is that the two candidates are distinct and randomly chosen.

What about instances that are slow but have few requests?

In-flight counts already capture slowness, since a slow instance keeps requests longer. For finer control, some balancers use a latency-weighted score, such as an exponentially weighted moving average of response time multiplied by in-flight count.

7Conclusion

In this answer, we wrote a power of two choices picker that chooses two distinct random instances with ThreadLocalRandom, compares their in-flight counts and returns the lighter one, handling empty, single and unhealthy cases. We kept the counts accurate by incrementing before the call and decrementing in finally, and we saw why it beats scanning for the least loaded instance: O(1) cost and no herding, while still steering work away from busy instances.

What to say in the interviewAbout 80 seconds aloud

Open with

I would write it so the two choices are always distinct. I filter to healthy instances, throw if there are none, and return the only one if there is one.

Then, if they want more

Otherwise I take ThreadLocalRandom.current(), pick a as nextInt(n) and b as nextInt(n minus 1), and if b is greater than or equal to a I add one, so b covers every index except a. Then I compare the two instances' inFlight values and return the one with fewer.

Around the call, I increment inFlight on the chosen instance before sending and decrement it in a finally block, or in the completion callback for async calls, so timeouts and errors never leave the count inflated. The reason it beats scanning for the least loaded instance is twofold.

Scanning costs O(n) per request, and more importantly, many independent clients scanning the same information all pick the same best instance at the same moment and overload it, which is herding.

Two random choices cost O(1), different clients choose different pairs so they spread out, and still each request avoids the busier of two candidates, which in theory reduces the maximum load from about log n over log log n to about log log n.

About this answer

Last updated
13 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the official documentation for the version you use. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Write a power-of-two-choices picker in Java and explain why it beats picking the least...": https://scrivio-interview-library.netlify.app/architecture/load-balancing-networking/d4beac8958/