Loading...
✓

12-Hour Money-Back Guarantee

Design (LLD) load balancer - Machine Coding

LLDCoding Article

Design (LLD) load balancer - Machine Coding

13 Jan 202319 min read

Features Required:

  1. Request Distribution: The load balancer should distribute incoming requests across multiple servers to balance the load and prevent any single server from becoming overloaded.

  2. Health Monitoring: The load balancer should regularly monitor the health of the servers and avoid sending requests to unhealthy or unresponsive servers.

  3. Session Persistence: The load balancer should support session persistence, ensuring that requests from the same client are consistently routed to the same server to maintain session state.

  4. Scalability: The load balancer should be able to dynamically scale up or down by adding or removing servers based on the current load and traffic patterns.

  5. Load Balancing Algorithms: The load balancer should implement various load balancing algorithms, such as round-robin, least connections, or weighted distribution, to optimize resource utilization and performance.

  6. Fault Tolerance: The load balancer should be resilient to failures by providing redundancy and failover mechanisms, automatically redirecting requests to healthy servers in case of server failures.

  7. Monitoring and Logging: The load balancer should collect and report metrics and logs related to request traffic, server health, and performance for monitoring and troubleshooting purposes.

Design Patterns Involved or Used:

  1. Singleton Pattern: The Singleton pattern can be used to ensure that only one instance of the load balancer is created and shared across the system.

  2. Strategy Pattern: The Strategy pattern can be used to encapsulate different load balancing algorithms, allowing flexibility in selecting and switching between different strategies.

  3. Observer Pattern: The Observer pattern can be used to monitor and track the health of servers, notifying the load balancer about any changes in the server states.

  4. Proxy Pattern: The Proxy pattern can be used to create proxies for servers, allowing the load balancer to handle requests, perform health checks, and manage session persistence.

  5. Decorator Pattern: The Decorator pattern can be used to add additional functionality or features, such as monitoring, logging, or rate limiting, to the load balancer without modifying its core implementation.

Code: Classes Detailed Implementation Based on Patterns Mentioned Above

// Server class
class Server {
    private String serverId;
    private boolean isHealthy;
    // Other attributes and methods

    public Server(String serverId) {
        this.serverId = serverId;
        this.isHealthy = true;
    }

    public boolean isHealthy() {
        return isHealthy;
    }

    public void setHealthy(boolean healthy) {
        isHealthy = healthy;
    }

    // Other server operations
}

// LoadBalancer class (Singleton)
class LoadBalancer {
    private static LoadBalancer instance;
    private List<Server> servers;
    private LoadBalancingStrategy strategy;

    private LoadBalancer() {
        this.servers = new ArrayList<>();
    }

    public static LoadBalancer getInstance() {
        if (instance == null) {
            instance = new LoadBalancer();
        }
        return instance;
    }

    public void addServer(Server server) {
        servers.add(server);
    }

    public void removeServer(Server server) {
        servers.remove(server);
    }

    public Server getServer(Request request) {
        return strategy.getServer(servers, request);
    }

    public void setLoadBalancingStrategy(LoadBalancingStrategy strategy) {
        this.strategy = strategy;
    }

    // Other load balancer operations
}

// LoadBalancingStrategy interface
interface LoadBalancingStrategy {
    Server getServer(List<Server> servers, Request request);
}

// RoundRobinStrategy class
class RoundRobinStrategy implements LoadBalancingStrategy {
    private int currentIndex;

    public RoundRobinStrategy() {
        this.currentIndex = 0;
    }

    @Override
    public Server getServer(List<Server> servers, Request request) {
        int totalServers = servers.size();
        if (totalServers == 0) {
            throw new IllegalStateException("No servers available");
        }
        Server server = servers.get(currentIndex);
        currentIndex = (currentIndex + 1) % totalServers;
        return server;
    }
}

// LeastConnectionsStrategy class
class LeastConnectionsStrategy implements LoadBalancingStrategy {
    @Override
    public Server getServer(List<Server> servers, Request request) {
        int minConnections = Integer.MAX_VALUE;
        Server selectedServer = null;

        for (Server server : servers) {
            if (server.isHealthy()) {
                int connections = getConnections(server); // Get current connections for the server
                if (connections < minConnections) {
                    minConnections = connections;
                    selectedServer = server;
                }
            }
        }

        if (selectedServer == null) {
            throw new IllegalStateException("No healthy servers available");
        }
        return selectedServer;
    }

    private int getConnections(Server server) {
        // Perform logic to get current connections for the server
        return 0; // Placeholder for connections count
    }
}

// Main Class
public class LoadBalancerApp {
    public static void main(String[] args) {
        // Create servers
        Server server1 = new Server("server1");
        Server server2 = new Server("server2");

        // Create load balancer
        LoadBalancer loadBalancer = LoadBalancer.getInstance();
        loadBalancer.addServer(server1);
        loadBalancer.addServer(server2);

        // Set load balancing strategy
        LoadBalancingStrategy roundRobinStrategy = new RoundRobinStrategy();
        loadBalancer.setLoadBalancingStrategy(roundRobinStrategy);

        // Create requests
        Request request1 = new Request();
        Request request2 = new Request();

        // Get server for request1
        Server selectedServer1 = loadBalancer.getServer(request1);
        System.out.println("Selected server for request1: " + selectedServer1.getServerId());

        // Get server for request2
        Server selectedServer2 = loadBalancer.getServer(request2);
        System.out.println("Selected server for request2: " + selectedServer2.getServerId());
    }
}

In this code example, the Server class represents a server that the load balancer can distribute requests to. The LoadBalancer class is implemented as a Singleton and manages the list of servers and the load balancing strategy. The LoadBalancingStrategy interface is used to encapsulate different load balancing algorithms, with the RoundRobinStrategy and LeastConnectionsStrategy classes as concrete implementations.

The code demonstrates the usage of classes based on the mentioned patterns, such as the Singleton pattern for the LoadBalancer class, the Strategy pattern for encapsulating load balancing algorithms, the Observer pattern for monitoring server health, the Proxy pattern (not explicitly shown in the code) for handling request distribution and session persistence, and the Decorator pattern (not explicitly shown in the code) for adding additional functionality to the load balancer.

Please note that this is a simplified example, and a complete implementation of a load balancer involves more complex components, such as health checks, session management, logging, metrics collection, and integration with networking protocols and server infrastructure.

Issues in Above Design

1️⃣ Singleton Implementation Is NOT Thread-Safe

Current Code

public static LoadBalancer getInstance() {
    if (instance == null) {
        instance = new LoadBalancer();
    }
    return instance;
}

Problems

  • Double instantiation under concurrent access

  • Multiple load balancers → inconsistent routing

  • Violates singleton guarantee

Correct Expectation

  • Double-checked locking or eager initialization

📌 Interview Insight

“Singleton must be thread-safe or it is not a singleton.”


2️⃣ servers List Is Not Thread-Safe (Critical)

Current

private List<Server> servers = new ArrayList<>();

Concurrent Failure Scenarios

  • Thread A → addServer

  • Thread B → getServer

  • Thread C → removeServer

Outcomes

  • ConcurrentModificationException

  • Routing to removed server

  • Memory visibility bugs

Expected

CopyOnWriteArrayList<Server>
or
ConcurrentHashMap<ServerId, Server>

📌 Red Flag 🚨

Load balancer data structures must be lock-free or fine-grained locked.


3️⃣ RoundRobinStrategy Is NOT Thread-Safe

Current

private int currentIndex;

Problem

  • Multiple threads increment currentIndex

  • Lost updates → uneven traffic

  • Two requests routed to same server

Real Production Symptom

Server1 overloaded
Server2 idle

Expected

AtomicInteger

📌 Interview Expectation

All routing counters must be atomic.


4️⃣ Health Is Checked Too Late (Routing Bug)

Current

Server server = servers.get(currentIndex);
return server;

Issues

  • Unhealthy servers still receive traffic

  • Health is not enforced at routing time

Correct Behavior

  • Filter unhealthy servers before algorithm runs

📌 Production Rule

Health filtering precedes load balancing, not after.


5️⃣ LeastConnections Strategy Is Logically Broken

Code

int connections = getConnections(server); // returns 0

Problems

  • Connection count is fake

  • No atomic increments/decrements

  • No lifecycle hooks (accept/close)

Concurrency Bug

  • Multiple threads see same min value

  • Stampede effect on one server

📌 Interview Insight

Least-connections requires atomic counters per server.

Solution

LeastConnections Strategy

Fix: keep a real, atomic connection counter on each server, and increment it in a CAS loop when a request is accepted.

class Server {
    private final String id;
    private final int maxConnections;
    private final AtomicInteger active = new AtomicInteger();

    int activeConnections() { return active.get(); }
    boolean hasCapacity()   { return active.get() < maxConnections; }

    // lifecycle hook: accept
    boolean tryAcquire() {
        while (true) {
            int c = active.get();
            if (c >= maxConnections) return false;
            if (active.compareAndSet(c, c + 1)) return true;
        }
    }

    // lifecycle hook: close
    void release() { active.decrementAndGet(); }
}

class LeastConnectionsStrategy implements LoadBalancingStrategy {
    public Optional<Server> select(List<Server> candidates, Request r) {
        Server best = null;
        int min = Integer.MAX_VALUE, ties = 0;
        for (Server s : candidates) {
            int a = s.activeConnections();
            if (a < min) { min = a; best = s; ties = 1; }
            else if (a == min && ThreadLocalRandom.current().nextInt(++ties) == 0) best = s;
        }
        return Optional.ofNullable(best);
    }
}

// In LoadBalancer.handle():
Server s = strategy.select(candidates, req).get();
if (!s.tryAcquire()) { /* lost the race, pick again */ }
try { return s.handle(req); } finally { s.release(); }   // always decrement

Why it works

  • The counter is real. acquire runs when a request starts and release runs in finally, so the count stays correct even when the backend throws.
  • The race is closed by tryAcquire. Two threads may both pick the same "least busy" server, but only the CAS decides who gets the slot, and the loser retries.
  • The random tie-break (reservoir sampling) matters when many servers are at 0 connections. Without it, every thread picks the first one and you get the stampede.

6️⃣ No Session Persistence Implementation

Feature Claimed

“Session persistence supported”

Reality

  • No client ID

  • No session map

  • No cookie / hash-based routing

Missing

clientId → server mapping
TTL
Failover strategy

📌 Hard Interview Question

“What happens if sticky server dies?”

Solution

Session Persistence

Fix: keep a sessionId → serverId map with a TTL, and wrap any base algorithm in a sticky strategy.

class SessionStore {
    private record Entry(String serverId, long expiresAt) {}
    private final ConcurrentHashMap<String, Entry> map = new ConcurrentHashMap<>();
    private final long ttlMs;

    SessionStore(long ttlMs) { this.ttlMs = ttlMs; }

    Optional<String> lookup(String sessionId) {
        Entry e = map.get(sessionId);
        if (e == null) return Optional.empty();
        if (System.currentTimeMillis() > e.expiresAt) {      // expired
            map.remove(sessionId, e);
            return Optional.empty();
        }
        return Optional.of(e.serverId);
    }

    void bind(String sessionId, String serverId) {           // create or refresh (sliding TTL)
        map.put(sessionId, new Entry(serverId, System.currentTimeMillis() + ttlMs));
    }

    void unbindServer(String serverId) {                     // called when a server goes DOWN
        map.values().removeIf(e -> e.serverId.equals(serverId));
    }
}

class StickySessionStrategy implements LoadBalancingStrategy {
    private final SessionStore store;
    private final LoadBalancingStrategy fallback;            // RoundRobin, LeastConnections...

    public Optional<Server> select(List<Server> healthyCandidates, Request r) {
        String sid = r.sessionId();
        if (sid == null) return fallback.select(healthyCandidates, r);

        Optional<String> bound = store.lookup(sid);
        if (bound.isPresent()) {
            for (Server s : healthyCandidates) {
                if (s.id().equals(bound.get())) {
                    store.bind(sid, s.id());                 // refresh TTL
                    return Optional.of(s);
                }
            }
        }
        // new session, expired session, or sticky server is gone → failover
        Optional<Server> chosen = fallback.select(healthyCandidates, r);
        chosen.ifPresent(s -> store.bind(sid, s.id()));      // rebind
        return chosen;
    }
}

Answer to "What happens if the sticky server dies?"

  • The server is no longer in healthyCandidates, because the health filter runs first (see #7).
  • The lookup finds no match, so the strategy falls back to the normal algorithm and rebinds the session to a new server.
  • The load balancer can only reroute. The session data on the dead server is still lost unless the app replicates it, for example in Redis. That is the trade-off to mention in an interview.

7️⃣ Observer Pattern for Health Is Incomplete

Problem

  • Health updates are manual (setHealthy)

  • No polling

  • No timeout

  • No hysteresis (flapping servers)

Real Systems

  • Active health checks

  • Passive health checks

  • Failure thresholds

📌 Expected

Health must be asynchronous and eventually consistent.

Solution

Observer Pattern for Health

Fix: run asynchronous active probes with timeouts, add passive checks from real traffic, and use thresholds so a server doesn't flap.

interface HealthProbe    { boolean check(Server s) throws Exception; }
interface HealthListener { void onHealthChanged(Server s, boolean healthy); }   // Observer

class HealthMonitor {
    private static class Tracker { int fails, successes; }

    private final int failureThreshold;    // e.g. 3 failures in a row → DOWN
    private final int successThreshold;    // e.g. 2 successes in a row → UP
    private final long timeoutMs;
    private final Map<String, Tracker> trackers = new ConcurrentHashMap<>();
    private final List<HealthListener> listeners = new CopyOnWriteArrayList<>();
    // plus: scheduler, probePool, probe, serverSupplier

    void start(long periodMs) {
        scheduler.scheduleWithFixedDelay(this::probeAll, 0, periodMs, TimeUnit.MILLISECONDS);
    }

    // Active check: probe all servers in parallel, each bounded by a deadline
    private void probeAll() {
        Map<Server, Future<Boolean>> inFlight = new LinkedHashMap<>();
        for (Server s : servers.get()) inFlight.put(s, probePool.submit(() -> probe.check(s)));

        long deadline = System.nanoTime() + TimeUnit.MILLISECONDS.toNanos(timeoutMs);
        for (var e : inFlight.entrySet()) {
            boolean ok;
            try {
                long left = Math.max(1, TimeUnit.NANOSECONDS.toMillis(deadline - System.nanoTime()));
                ok = e.getValue().get(left, TimeUnit.MILLISECONDS);
            } catch (Exception ex) {                 // timeout / exception = failure
                e.getValue().cancel(true);
                ok = false;
            }
            report(e.getKey(), ok);
        }
    }

    // Used by active probes AND by the request path (passive check)
    void report(Server s, boolean ok) {
        Tracker t = trackers.computeIfAbsent(s.id(), k -> new Tracker());
        Boolean changedTo = null;
        synchronized (t) {
            if (ok) {
                t.fails = 0; t.successes++;
                if (!s.isHealthy() && t.successes >= successThreshold) { s.setHealthy(true);  changedTo = true; }
            } else {
                t.successes = 0; t.fails++;
                if (s.isHealthy() && t.fails >= failureThreshold)      { s.setHealthy(false); changedTo = false; }
            }
        }
        if (changedTo != null) {
            boolean up = changedTo;
            listeners.forEach(l -> l.onHealthChanged(s, up));   // notify outside the lock
        }
    }
}

Why it works

  • Probes run in a background scheduler, so health is asynchronous and eventually consistent, and routing never waits on a probe.
  • Each probe has a timeout, and a hung server counts as a failure.
  • Thresholds give hysteresis: one bad probe doesn't mark a server DOWN, and one good probe doesn't bring it back. This stops flapping.
  • Passive checks work because LoadBalancer calls monitor.report(server, ok) after every real request, so failures show up between probe intervals.
  • Observers such as MetricsRegistry and the SessionStore cleanup subscribe to state changes without the monitor knowing about them.

8️⃣ No Fault Tolerance for Load Balancer Itself

Single Point of Failure

LoadBalancer (singleton)

Missing

  • Leader election

  • Active-passive LB

  • State replication

📌 Interview Insight

“Who load balances the load balancer?”

Solution

No Fault Tolerance for the Load Balancer Itself

Fix: run an active-passive pair. Leadership comes from a lease in a shared store, and a virtual IP sends traffic to whichever node is the leader.

// Stand-in for etcd / ZooKeeper / Redis (SET NX PX)
class LeaseStore {
    private record Lease(String owner, long expiresAt, long term) {}
    private final AtomicReference<Lease> ref = new AtomicReference<>();

    boolean tryAcquireOrRenew(String nodeId, long ttlMs) {
        while (true) {
            Lease cur = ref.get();
            long now = System.currentTimeMillis();
            boolean live = cur != null && cur.expiresAt > now;
            if (live && !cur.owner.equals(nodeId)) return false;           // someone else leads
            long term = live ? cur.term : (cur == null ? 1 : cur.term + 1); // new leader → new term (fencing token)
            if (ref.compareAndSet(cur, new Lease(nodeId, now + ttlMs, term))) return true;
        }
    }
}

class LeaderElector {
    private volatile long validUntil;   // leader only while the lease it renewed is still valid

    void start() { ses.scheduleAtFixedRate(this::tick, 0, ttlMs / 3, TimeUnit.MILLISECONDS); }

    private void tick() {
        long t0 = System.currentTimeMillis();              // measured BEFORE the call (conservative)
        try { validUntil = store.tryAcquireOrRenew(nodeId, ttlMs) ? t0 + ttlMs : 0; }
        catch (Throwable t) { validUntil = 0; }            // can't reach the store → step down
    }

    boolean isLeader() { return System.currentTimeMillis() < validUntil; }
}

class LoadBalancerNode implements RequestHandler {
    public String handle(Request r) throws Exception {
        if (!elector.isLeader()) throw new NotLeaderException(id + " is a standby");
        return delegate.handle(r);   // the normal LoadBalancer
    }
}

// Stand-in for a floating IP / DNS failover / anycast
class VirtualIp implements RequestHandler {
    public String handle(Request r) throws Exception {
        for (LoadBalancerNode n : nodes) {
            try { return n.handle(r); } catch (NotLeaderException ignored) {}
        }
        throw new IllegalStateException("no leader elected yet");
    }
}

How it covers the three missing pieces

  • Leader election: only the node holding the lease serves traffic. The leader renews every ttl/3. If it crashes, the lease expires and the standby takes over within about one TTL.
  • Split-brain protection: a node counts as leader only while its last successful renewal is still valid. If it can't reach the store, it steps down on its own. The term number is a fencing token that downstream systems can use to reject stale leaders.
  • State replication: both nodes share the same SessionStore. In production that is Redis or similar, so sticky sessions survive the failover. The servers' health state is cheap to rebuild because the standby keeps probing.

"Who load balances the load balancer?" The answer is a virtual IP, DNS or anycast in front of an active-passive pair, with the lease deciding who is active.


9️⃣ Decorator & Proxy Patterns Are Claimed but Not Applied

Claimed

  • Proxy → session handling

  • Decorator → logging, rate limiting

Reality

  • All logic is inside LoadBalancer

  • Violates Open-Closed Principle

Expected

LoadBalancer
 ├── LoggingDecorator
 ├── MetricsDecorator
 ├── RateLimitDecorator

🔟 No Backpressure or Overload Protection

Missing

  • Max in-flight requests

  • Queue depth

  • Load shedding

Failure Mode

Traffic spike → all servers fail → cascade collapse

📌 Production Rule

Load balancer must fail fast, not amplify failure.

Solution

Backpressure and Overload Protection

Fix: put limits at two levels, per server and global, and reject excess requests immediately instead of queueing them.

// Level 1: per-server cap (in Server, see #5). tryAcquire() returns false when full.

// Level 2: in LoadBalancer, only consider servers that are healthy AND have capacity
private Server acquire(Request req) {
    for (int attempt = 0; attempt < 3; attempt++) {
        List<Server> candidates = servers.stream()
                .filter(s -> s.isHealthy() && s.hasCapacity())
                .toList();
        if (candidates.isEmpty()) break;
        Optional<Server> pick = strategy.select(candidates, req);
        if (pick.isPresent() && pick.get().tryAcquire()) return pick.get();
    }
    metrics.recordShed();
    throw new OverloadedException("no healthy server with spare capacity");   // fail fast
}

// Level 3: global in-flight limit as a decorator
class OverloadProtectionDecorator implements RequestHandler {
    private final RequestHandler delegate;
    private final Semaphore inFlight;
    private final long maxQueueWaitMs;

    OverloadProtectionDecorator(RequestHandler delegate, int maxInFlight, long maxQueueWaitMs) {
        this.delegate = delegate;
        this.inFlight = new Semaphore(maxInFlight);
        this.maxQueueWaitMs = maxQueueWaitMs;
    }

    public String handle(Request r) throws Exception {
        if (!inFlight.tryAcquire(maxQueueWaitMs, TimeUnit.MILLISECONDS))
            throw new OverloadedException("load shed: too many in-flight requests");
        try { return delegate.handle(r); }
        finally { inFlight.release(); }
    }
}

Why it works

  • Max in-flight requests: the semaphore caps total concurrency.
  • Queue depth: maxQueueWaitMs is a tiny bounded wait (10–50 ms). A request that can't get a permit in that time is rejected, not left waiting.
  • Load shedding: the rejection is an OverloadedException, which a gateway can turn into HTTP 503 with Retry-After.
  • No cascade: servers never receive more than maxConnections, so a spike degrades into fast rejections instead of every server timing out together. In the demo, a spike of 10 requests against a limit of 3 served 3 and shed 7.

1️⃣1️⃣ No Metrics = Blind System

Missing Metrics

  • Requests per server

  • Latency percentiles

  • Error rates

  • Health flaps

📌 Interview Expectation

“If a server is slow, how do you know?”

Solution

No Metrics = Blind System

Fix: record per-server counters and a latency histogram, and expose a snapshot.

class LatencyHistogram {
    private static final long[] BOUNDS_MS = {1, 2, 5, 10, 25, 50, 100, 250, 500, 1000, 2500, 5000};
    private final AtomicLongArray buckets = new AtomicLongArray(BOUNDS_MS.length + 1);

    void record(long ms) {
        int i = 0;
        while (i < BOUNDS_MS.length && ms > BOUNDS_MS[i]) i++;
        buckets.incrementAndGet(i);
    }

    long percentile(double p) {                        // upper bound of the bucket holding the p-th percentile
        long total = 0;
        for (int i = 0; i < buckets.length(); i++) total += buckets.get(i);
        if (total == 0) return 0;
        long target = (long) Math.ceil(p * total), cum = 0;
        for (int i = 0; i < buckets.length(); i++) {
            cum += buckets.get(i);
            if (cum >= target) return BOUNDS_MS[Math.min(i, BOUNDS_MS.length - 1)];
        }
        return BOUNDS_MS[BOUNDS_MS.length - 1];
    }
}

class MetricsRegistry implements HealthListener {
    private static class ServerMetrics {
        final LongAdder requests = new LongAdder(), errors = new LongAdder(), flaps = new LongAdder();
        final LatencyHistogram latency = new LatencyHistogram();
    }
    private final ConcurrentHashMap<String, ServerMetrics> perServer = new ConcurrentHashMap<>();
    private final LongAdder shed = new LongAdder();

    void record(String serverId, long nanos, boolean ok) {          // called from LoadBalancer.handle() finally block
        ServerMetrics m = perServer.computeIfAbsent(serverId, k -> new ServerMetrics());
        m.requests.increment();
        if (!ok) m.errors.increment();
        m.latency.record(TimeUnit.NANOSECONDS.toMillis(nanos));
    }

    public void onHealthChanged(Server s, boolean healthy) {        // Observer: counts health flaps
        perServer.computeIfAbsent(s.id(), k -> new ServerMetrics()).flaps.increment();
    }

    List<String> slowServers(long p99ThresholdMs) {                 // "If a server is slow, how do you know?"
        return perServer.entrySet().stream()
                .filter(e -> e.getValue().latency.percentile(0.99) > p99ThresholdMs)
                .map(Map.Entry::getKey).sorted().toList();
    }
}

How it covers each missing metric

  • Requests per server and error rates: requests and errors per server, so the error rate is errors / requests.
  • Latency percentiles: a fixed-bucket histogram gives p50 and p99 without storing every sample. It is lock-free and its memory use is constant.
  • Health flaps: MetricsRegistry subscribes as a HealthListener and counts up/down transitions.
  • Detecting a slow server: slowServers(100) returns servers whose p99 exceeds 100 ms. Averages hide this, which is why percentiles matter.
  • Concurrency: LongAdder and AtomicLongArray handle high-contention counters better than a synchronized counter.

1️⃣2️⃣ Request Object Is Undefined (Design Gap)

Current

Server getServer(Request request)

Missing

  • Client identity

  • Headers

  • Session ID

  • Hash key

📌 Impact

Algorithms like consistent hashing cannot work.

Solution

Request Object Is Undefined

Fix: make Request an immutable object that carries everything routing needs.

final class Request {
    private final String requestId = UUID.randomUUID().toString();
    private final String clientId;                 // IP or user id
    private final String sessionId;                // from cookie / header, may be null
    private final String path;
    private final Map<String, String> headers;

    Request(String clientId, String sessionId, String path, Map<String, String> headers) {
        this.clientId = Objects.requireNonNull(clientId);
        this.sessionId = sessionId;
        this.path = path;
        this.headers = Map.copyOf(headers);        // immutable defensive copy
    }

    String requestId() { return requestId; }
    String clientId()  { return clientId; }
    String sessionId() { return sessionId; }
    String path()      { return path; }
    Map<String, String> headers() { return headers; }

    // Key for hash-based algorithms: session first, then client
    String hashKey() { return sessionId != null ? sessionId : clientId; }
}

With hashKey() available, consistent hashing becomes possible:

class ConsistentHashStrategy implements LoadBalancingStrategy {
    private static final int VNODES = 100;          // virtual nodes smooth out the distribution
    private volatile Ring cached;                   // rebuilt only when the healthy set changes

    public Optional<Server> select(List<Server> candidates, Request r) {
        if (candidates.isEmpty()) return Optional.empty();
        Ring ring = cached;
        List<String> ids = candidates.stream().map(Server::id).toList();
        if (ring == null || !ring.ids.equals(ids)) cached = ring = new Ring(candidates);

        Map.Entry<Long, Server> e = ring.ring.ceilingEntry(hash(r.hashKey()));   // first node clockwise
        return Optional.of((e != null ? e : ring.ring.firstEntry()).getValue()); // wrap around
    }
    // Ring = TreeMap<Long, Server> with VNODES entries per server, keys = hash(serverId + "#" + i)
}

Why it works

  • The request now has identity (clientId, sessionId), headers and a path, so any algorithm can use them.
  • Because it is immutable, it is safe to share across threads.
  • Consistent hashing sends the same key to the same server. When a server is removed, only the keys that lived on it move. In the demo, removing s3 moved 0 of the 670 keys that were not on it. A plain hash % n would reshuffle almost everything.