SDSystem DesignConcepts to case studies
System DesignDSA
x
0/311
Part 1: Foundations
  • What are Load Balancers?
  • Load Balancing Algorithms
  • DNS Load Balancing
  • Anycast Routing
  • Layer 4 vs Layer 7 Load Balancers
  • Health Checks
  • Sticky Sessions
  • Global Load Balancing
  • Nginx and HAProxy
Part 2: APIs and Communication
Part 3: Caching
Part 4: Data and Storage
Part 5: Architecture
Part 6: Distributed Systems
Part 7: Advanced Data Topics
Part 8: Operations and Security
Part 9: Estimation and Interview Method
Part 10: Case Studies
System Design/Foundations/Load Balancing

Load Balancing Algorithms

Round robin, least connections, hashing: how a load balancer picks a server.

⏱ 14 min readIntermediateMust KnowInterview FavouriteHas visualizer
SummaryConceptReal-Life ExampleWhy?Where?How It WorksStepsKey TermsPros & ConsMistakesReal WorldRead NextInterview Q&ACheat-Sheet

01Quick Summary

A load balancing algorithm is the rule a load balancer uses to pick a server for each request.

  • Simple rules: round robin, random.
  • Smart rules: weighted, least connections, least response time.
  • Sticky rules: IP hash, consistent hash (same client, same server).
  • There is no best one. Pick by the kind of traffic and servers you have.

02Concept: What is it?

The load balancer has a list of healthy servers. For every request it must answer one question: “Which server gets this?” The algorithm is the answer.

The decision
📨New request
→↓
🧠Algorithmthe rule
→↓
🖥️Server A
🖥️Server B
🖥️Server C
The same request, but a different rule can give a different server.

Two families

Static algorithms
Ignore the live state of servers
  • Round robin
  • Weighted round robin
  • IP hash
  • Random
Dynamic algorithms
Look at the live state
  • Least connections
  • Weighted least connections
  • Least response time
  • Resource-based (CPU, memory)

03Real-Life Example

🍵The supermarket billing counters
A supermarket has 3 billing counters. The guard at the entrance sends customers. He can use different rules:
Supermarket guard
Algorithm
“You go to 1, you to 2, you to 3, you to 1...”
Round robin
“Counter 1 has the fastest cashier, send 3 people there for each 1 to counter 3”
Weighted round robin
“Go to the counter with the shortest queue”
Least connections
“Regular customers always go to their favourite counter”
IP hash (sticky)
“Close your eyes and point”
Random
Why 'shortest queue' beats 'take turns' sometimes
Take turns
🧍🧍Counter 12 waiting
🧍🧍Counter 22 waiting
🧍🧍🧍🧍Counter 3 (slow)4 waiting
Shortest queue
🧍🧍🧍Counter 13 waiting
🧍🧍🧍Counter 23 waiting
🧍Counter 3 (slow)1 waiting
Round robin keeps sending people to counter 3, even though that cashier is slow and the queue is long.

04Why Do We Need It?

The right algorithm decides if the load is shared fairly. A wrong one can overload one server while others sit idle.

⚖️Fair sharing
No server is overloaded, no server is idle.
🐢Handle slow servers
Mixed servers (big and small) need weights.
🔗Keep users together
Some apps need the same user on the same server.
⚡Lower latency
Sending to the least busy server gives faster replies.

05Where Do We Use It?

🌐Web servers
Short, equal requests: round robin works well.
💬Chat and WebSocket
Long connections: least connections works better.
🎥Video uploads
Some requests are huge: least connections or response time.
🗄️Caches (Redis, Memcached)
Same key to same cache: hash based.
🧮Mixed hardware fleets
Old and new machines: weighted.
🎮Game sessions
Keep a player on one server: IP hash or sticky.

06Types / Parts / How It Works

1. Round robin

Go through the servers in a circle: A, B, C, A, B, C... Simple and fair if servers and requests are about equal.

Req 1
Req 2
Req 3
Req 4
→↓
🖥️Server AReq 1, Req 4
🖥️Server BReq 2
🖥️Server CReq 3
Good
  • Very simple
  • No state to keep
  • Fair for equal servers and equal requests
Weak
  • Ignores how busy a server is
  • Ignores server power
  • A slow request can pile up on one server

2. Weighted round robin

Give each server a weight (its power). A server with weight 3 gets 3 turns for every 1 turn of a weight-1 server.

🖥️A: weight 3big
Traffic share50%
🖥️B: weight 2medium
Traffic share33%
🖥️C: weight 1small
Traffic share17%
💡Tip
Use it when servers have different power, or when you slowly move traffic to a new version (a “canary”: 95% old, 5% new).

3. Least connections

Send the request to the server with the fewest open connections right now. A busy or slow server has more open connections, so it gets fewer new ones. The weighted version divides open connections by the weight.

💡Tip
Best when requests take very different times (uploads, reports, WebSockets).

4. Least response time

Pick the server that answers fastest (and has few connections). It needs the LB to measure the response time of each server.

5. IP hash (and other hashes)

Take the client IP (or a header, or the URL), run it through a hash function to get a number, and use number % server_count to pick a server. The same client gives the same number, so it always lands on the same server.

⚠️The big problem
If you add or remove a server, % server_count changes and almost every client moves to a different server. For caches, this is a disaster. The fix is Consistent Hashing.

6. Random (and power of two choices)

Pick a server at random. It is simple and works fine at large scale. A clever version, “power of two choices”, picks two random servers and sends the request to the less busy one. This gives a very good spread with little work.

Quick comparison

AlgorithmLooks atBest for
Round robinNothingEqual servers, short equal requests
Weighted round robinServer weightDifferent server sizes, canary release
Least connectionsOpen connectionsLong or uneven requests
Least response timeSpeed and connectionsLatency sensitive apps
IP / URL hashClient or URLSticky users, caches
Consistent hashClient or key, on a ringCaches and sharded data with changing servers
Random / 2 choicesNothing / 2 loadsVery large, simple fleets
VisualizerTry every algorithmServer C is small and slow. See who gets the load under each rule.
Algorithm
⚖️Load balancerpicks a server
↓
🖥️A: Bigweight 3 · each request takes 2 ticks
0 open now
Share0 total
🖥️B: Mediumweight 2 · each request takes 3 ticks
0 open now
Share0 total
🖥️C: Smallweight 1 · each request takes 5 ticks
0 open now
Share0 total
Requests
0
Busiest server
0 open
most connections at once
Round robin: A, B, C, A, B, C... Everyone gets the same number of requests, even the small server.

07How to Use It / Steps / Implementation

How to choose

  1. 1
    Are servers equal and requests short?
    Start with round robin. It is enough for most small systems.
  2. 2
    Are servers different in power?
    Use weighted round robin (or weighted least connections).
  3. 3
    Do requests take very different time?
    Use least connections or least response time.
  4. 4
    Must the same user or key hit the same server?
    Use IP hash, cookie stickiness, or consistent hashing for caches.
  5. 5
    Huge fleet, no shared state?
    Random or power of two choices keeps the LB simple.
  6. 6
    Measure and adjust
    Watch per-server load and latency. Change the rule if one server is always hot.
Decision map
❓Servers equal?
→↓yes
❓Requests equal?
→↓yes
🔄Round robin
❓Servers equal?
→↓no
⚖️Weighted
❓Requests equal?
→↓no
📉Least connections
❓Need same server?
→↓yes
#️⃣Hash

Tiny code idea: round robin and least connections

# round robin
i = 0
def pick(servers):
    global i
    s = servers[i % len(servers)]
    i += 1
    return s

# least connections
def pick(servers):
    return min(servers, key=lambda s: s.open_connections)

08Key Terms to Know

TermMeaning in easy words
AlgorithmThe rule that picks a server for a request
WeightA number showing how strong a server is. Higher weight, more traffic
Open connectionA request that the server is still working on
Static vs dynamicStatic ignores live load. Dynamic looks at it
Hash functionTurns text (like an IP) into a number
Sticky / affinityThe same client keeps going to the same server
Hot spotOne server that gets far more load than the others
Slow startA new server gets traffic slowly, not all at once
Canary releaseSend a small share of traffic to a new version to test it
Power of two choicesPick two random servers, send to the less busy one

09Pros, Cons and Trade-offs

✅ Pros
  • Simple rules are fast and need no state
  • Weights use mixed hardware well
  • Least connections adapts to slow requests
  • Hashing keeps a user or key on one server
⚠️ Cons
  • Simple rules ignore live load
  • Smart rules need extra data and work
  • Hashing breaks when servers change (unless consistent hashing)
  • Sticky rules can make hot spots

Trade-offs

ChoiceWe gainWe lose
Round robinSimplicity, no stateNo awareness of load
Least connectionsBetter balanceLB must track connections
IP hashSame client, same serverUneven load, remap on change
WeightedUses big servers wellYou must set and update weights

10Common Problems and Mistakes

  1. Round robin with uneven requests. One server gets all the heavy ones and slows down.
  2. Forgetting weights. A small old server gets the same load as a new big one.
  3. IP hash behind a big NAT or proxy. Thousands of users share one IP, so one server gets all of them.
  4. Plain hash and then scaling. Adding one server remaps almost all keys. Use consistent hashing.
  5. Least connections with a brand new server. It has 0 connections, so it gets flooded. Use slow start.
  6. Not looking at per-server metrics. You never see the hot spot.
🚫Thundering herd
If a server comes back after a crash and has 0 connections, “least connections” sends it every request at once, and it may crash again. Ramp up slowly.

11Real-World Examples

🧰NGINX
Default is round robin. Also has weights, least_conn and ip_hash.
🛠️HAProxy
Offers roundrobin, leastconn, source (IP hash) and more.
☁️AWS ALB / NLB
ALB: round robin or least outstanding requests. NLB: flow hash.
☸️Kubernetes
Services spread traffic across pods. Service meshes add least-request.
🗄️Cache clusters
Use hashing (often consistent hashing) to find which cache holds a key.
🚀Canary deploys
Weights send 5% of users to a new version first.
Simple Dynamic Hash based

12Related Topics to Read Next

What are Load Balancers?→

The component that runs these algorithms.

Consistent Hashing→

The smart hash that survives adding or removing servers.

DNS Load Balancing→

A simple round robin done by DNS.

Latency vs Throughput vs Bandwidth→

Measure whether the balance is really helping.

Scalability→

Why we balance load at all.

13Interview Questions with Short Answers

14Quick Revision Cheat-Sheet

  • ✔Algorithm = the rule to pick a server per request.
  • ✔Round robin: take turns. Good default.
  • ✔Weighted: stronger server, more turns.
  • ✔Least connections: pick the least busy. Best for long or uneven requests.
  • ✔IP / URL hash: same key, same server. Breaks when servers change, so use consistent hashing.
  • ✔Random / two choices: simple and works on a big scale.
  • ✔Add slow start for new servers.
  • ✔One line: “Pick the simplest rule that keeps every server about equally busy.”
← Previous
What are Load Balancers?
Next →
DNS Load Balancing