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

What are Load Balancers?

The traffic police that shares requests between many servers.

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

01Quick Summary

A load balancer sits in front of many servers. It takes every incoming request and sends it to one healthy server. This way no single server gets too busy.

  • It spreads the work, so the system can handle more users.
  • It checks which servers are healthy and skips the broken ones.
  • It hides the servers. Users see only one address.
  • The load balancer can fail too. So we usually run two of them.

02Concept: What is it?

A load balancer (LB) is a server, a device or a cloud service that receives traffic and shares it among a group of servers. That group is called a server pool (or backend pool).

Without and with a load balancer
Without
πŸ‘₯All users
↓everything
πŸ–₯️One serveroverloaded
With a load balancer
πŸ‘₯All users
↓
βš–οΈLoad balancer
↓
πŸ–₯️
πŸ–₯️
πŸ–₯️
Without an LB, every user must know a server and one server takes all the load. With an LB, users see one address.

What a load balancer does

πŸ”€Distributes traffic
Shares requests across servers with a rule (an algorithm).
🩺Health checks
Asks each server β€œare you OK?” again and again. Stops sending traffic to a sick one.
🎭Hides servers
Users see one address. You can add or remove servers behind it.
πŸ”’Optional extras
Can also handle HTTPS (TLS), compress data and block bad traffic.

03Real-Life Example

🍡The bank with many counters
A bank has 5 counters. One person at the door looks at the queue and tells each customer, β€œGo to counter 3.” If counter 2 is closed, the person at the door stops sending people there. The customers never choose a counter on their own.
Bank
Software system
Customers
Users and requests
Person at the door
Load balancer
Counters
Servers in the pool
Counter is closed, so skip it
Health check removes the server
Open a new counter at rush hour
Add a server to the pool
Two door-persons, in case one is sick
Two load balancers (active-passive)
One request, step by step
πŸ§‘Usershop.com
→↓1. request
βš–οΈLoad balancer2. picks a healthy server
→↓3. forward
πŸ–₯️Server 24. does the work
↑5. reply goes back the same way

04Why Do We Need It?

πŸ“ˆHandle more users
One server has a limit. Many servers behind an LB can grow without a limit.
πŸ›‘οΈStay available
If a server dies, the LB sends traffic to the others. Users do not notice.
⚑Faster replies
No server is overloaded, so each request waits less.
πŸ”§Easy upgrades
Take one server out, update it, put it back. No downtime.
🀫Hide your servers
Servers can sit in a private network. Only the LB is public.
πŸ’°Save money
Add servers at rush hour only, then remove them.
A load balancer turns many small servers into one big, strong and reliable service.

05Where Do We Use It?

Almost every website or app with more than one server has a load balancer.

πŸ›’Shopping sites
Share sale-day traffic across web servers.
πŸ”ŒAPI gateways
Spread API calls across service copies.
🧩Microservices
Each service has many copies behind its own LB.
πŸ—„οΈDatabase read replicas
Spread read queries across replicas.
🎬Video and chat apps
Many persistent connections shared across servers.
☁️Cloud and Kubernetes
Cloud LBs and Services front every app by default.

Where does the LB sit?

LBs can be at many places
πŸ‘₯Users
→↓
βš–οΈLB 1in front of web servers
→↓
🌐Web servers
→↓
βš–οΈLB 2in front of app servers
→↓
βš™οΈApp servers
→↓
βš–οΈLB 3in front of DB replicas
→↓
πŸ—„οΈDB replicas
Big systems often have an LB between every two layers.

06Types / Parts / How It Works

1. Layer 4 vs Layer 7

These numbers come from the OSI model. A Layer 4 LB looks only at IP addresses and ports. A Layer 7 LB reads the actual request, like the URL, headers and cookies.

What each LB can see
7Layer 7: ApplicationURL, headers, cookies. L7 LB sees this.
4Layer 4: TransportIP + port (TCP/UDP). L4 LB sees this.
3Layer 3: NetworkIP packets
PointLayer 4 LBLayer 7 LB
Decides usingIP address and portURL path, host, headers, cookies
SpeedVery fast, simpleSlower, does more work
Smart routingNo. Cannot tell /images from /loginYes. /api to one pool, /images to another
Can do TLS (HTTPS) offloadUsually noYes
Good forRaw TCP/UDP, games, databases, huge trafficWebsites, APIs, microservices
ExamplesAWS NLB, HAProxy (tcp mode)AWS ALB, NGINX, HAProxy (http mode)
Layer 7 routing by URL
πŸ§‘User
→↓
βš–οΈL7 load balancerreads the URL
→↓
πŸ–ΌοΈ/images/*image servers
πŸ”Œ/api/*API servers
πŸ’³/pay/*payment servers

2. Hardware vs software vs cloud

πŸ“¦Hardware LB
A special box (like F5). Very fast but costly. Used in old or very large data centres.
🧰Software LB
A program on normal servers: NGINX, HAProxy, Envoy. Cheap and flexible.
☁️Cloud LB
Managed service: AWS ELB (ALB/NLB), Google Cloud LB, Azure LB. No servers to run.

3. Health checks

The LB sends a small test request to every server, every few seconds. For example GET /health. If a server fails a few checks in a row, the LB stops sending users to it. When it passes again, the LB adds it back.

Health check loop
βš–οΈLoad balancer
⇒⇣GET /health
βœ…Server 1: 200 OK
βœ…Server 2: 200 OK
❌Server 3: no replyremoved from pool

4. Sticky sessions

Normally each request can go to any server. With sticky sessions (session affinity), the LB sends the same user to the same server every time. It uses a cookie or the client IP.

Use sticky sessions when
  • The server keeps the user session in its own memory
  • You cannot change the app quickly
  • A WebSocket or upload must stay on one server
Avoid them because
  • One server may get more users than others
  • If that server dies, the user loses the session
  • Harder to scale and to upgrade
πŸ’‘Better idea
Keep servers stateless and store sessions in a shared place like Redis. Then you do not need sticky sessions.
VisualizerSend traffic and crash a serverPress Play, then crash a server. Watch the health check remove it.
πŸ‘₯Users2 requests per second
↓
βš–οΈLoad balancernext health check in 4 requests
↓
πŸ–₯️Server 10 served
πŸ–₯️Server 20 served
πŸ–₯️Server 30 served
Served
0
Failed
0
Healthy now
3/3
in the LB pool
Press Play, or send one request. (To keep the demo quick, the health check runs every 4 requests. Real ones run every few seconds.)

07How to Use It / Steps / Implementation

Steps to put a load balancer in front of your app

  1. 1
    Make servers stateless
    Any server should be able to answer any request. Move sessions to Redis or a database.
  2. 2
    Create a server pool
    List the servers (or their IPs) that will receive traffic.
  3. 3
    Add a health check
    Pick a path like /health. It should return 200 only if the server is really OK.
  4. 4
    Pick an algorithm
    Round robin is a good start. See β€œLoad Balancing Algorithms”.
  5. 5
    Choose L4 or L7
    Websites and APIs: L7. Raw TCP or very high speed: L4.
  6. 6
    Add HTTPS
    Put the TLS certificate on the LB (TLS termination). Traffic inside can be plain or encrypted again.
  7. 7
    Make the LB itself highly available
    Run two LBs, or use a cloud LB that is already spread across zones.
  8. 8
    Watch it
    Track requests, errors, latency and healthy server count.

Who watches the watcher? The LB is a SPOF

If we have only one load balancer and it dies, the whole site goes down, even if all servers are fine. So we use a pair.

Active-passive pair
πŸ‘₯Usersone public IP
→↓
βš–οΈLB 1 (active)
↕heartbeat
βš–οΈLB 2 (passive)waiting
→↓
πŸ–₯️
πŸ–₯️
πŸ–₯️
Doing the work Standby Health signal
The active LB works. The passive one waits and checks it with heartbeats. If the active one stops, the passive one takes over the shared address (a floating or virtual IP).
  • Active-passive: one works, one waits. Simple.
  • Active-active: both work and share traffic. Better use of money, but more complex.
  • Cloud LBs (ALB, NLB) already run on many machines in many zones for you.

A tiny NGINX example

upstream my_app {
    server 10.0.0.1:8080;
    server 10.0.0.2:8080;
    server 10.0.0.3:8080;
}

server {
    listen 80;
    location / {
        proxy_pass http://my_app;   # round robin by default
    }
}

08Key Terms to Know

TermMeaning in easy words
Server pool / backendThe group of servers behind the load balancer
Health checkA small test request that tells the LB if a server is OK
Layer 4 / Layer 7The LB decides by IP+port (L4), or by the full request such as URL and headers (L7)
Sticky sessionSame user always goes to the same server
TLS terminationThe LB decrypts HTTPS, so servers do less work
FailoverSwitching to a standby (server or LB) when the main one fails
Active-passiveOne LB works, the other waits as a backup
Virtual IP (VIP)A shared address that moves to the backup LB when needed
Connection drainingBefore removing a server, let its current requests finish
Reverse proxyA server in front of other servers. A load balancer is a reverse proxy that also shares load

09Pros, Cons and Trade-offs

βœ… Pros
  • More capacity: add servers any time
  • Better availability: dead servers are skipped
  • Zero-downtime updates
  • Hides internal servers and gives one address
  • Can handle HTTPS and security tasks in one place
⚠️ Cons
  • Extra part to run and pay for
  • Can become a single point of failure if not doubled
  • Adds a small delay for each request
  • Sticky sessions can make load uneven
  • Wrong health check can remove good servers

Trade-offs

ChoiceWe gainWe lose
L4 instead of L7Speed, simplicitySmart routing by URL
L7 instead of L4Smart routing, HTTPS handlingA bit more delay and cost
Hardware LBVery high speedHigh cost, hard to scale
Software / cloud LBCheap, flexibleYou tune or pay per use
Sticky sessionsWorks with stateful appsUneven load, harder failover
Active-activeNo idle LBMore complex setup

10Common Problems and Mistakes

Common mistakes

  1. Only one load balancer. It becomes the new single point of failure.
  2. A weak health check. β€œIs the port open?” says OK even when the app is broken. Check the real app, and its database link.
  3. A health check that is too hard. If it fails for slow reasons, the LB removes all servers and the site goes down.
  4. Using sticky sessions by habit. Load becomes uneven.
  5. No connection draining. Users get errors when you remove a server.
  6. Forgetting the real client IP. The server sees the LB’s IP. Read the X-Forwarded-For header instead.
  7. Not testing failover. You find out it does not work during a real outage.
πŸ”₯Hot server
One server gets far more traffic. Check the algorithm and sticky sessions.
⛓️Cascading failure
A server dies, the others get more load and die too. Keep spare capacity.
🧊Cold servers
A new server gets full traffic at once. Slowly ramp up (slow start).

11Real-World Examples

☁️AWS
Elastic Load Balancing: ALB for HTTP (L7), NLB for fast TCP/UDP (L4).
🧰NGINX and HAProxy
Popular free software LBs. Used by many companies, big and small.
πŸ›‘οΈCloudflare
Global load balancing and CDN in front of websites.
☸️Kubernetes
A Service and an Ingress share traffic across pods (app copies).
🎬Streaming and shopping sites
Many LB layers between users and thousands of servers.
🏦Banks and payments
LB pairs with health checks keep payment APIs up.
πŸ“Note
These are the general ideas. Each company has its own detailed setup.

12Related Topics to Read Next

Load Balancing Algorithms→

How the LB picks a server for each request.

DNS Load Balancing→

Share traffic using DNS before it reaches an LB.

Anycast Routing→

Share traffic across the world with one IP.

Single Point of Failure (SPOF)β†’

Why one LB is not enough.

Proxy vs Reverse Proxy→

An LB is a type of reverse proxy.

Scalability→

Load balancers are the main tool to scale out.

OSI Model→

To understand Layer 4 and Layer 7.

13Interview Questions with Short Answers

14Quick Revision Cheat-Sheet

  • βœ”What: spreads requests across a pool of servers and skips unhealthy ones.
  • βœ”Why: more capacity, higher availability, easy upgrades, one address for users.
  • βœ”L4: IP + port, fast. L7: reads URL and headers, smart routing.
  • βœ”Health checks remove broken servers. Use a real check like /health.
  • βœ”Sticky sessions: same user, same server. Avoid if you can. Use stateless servers.
  • βœ”Types: hardware, software (NGINX, HAProxy), cloud (AWS ALB/NLB).
  • βœ”The LB can fail too. Run a pair with a virtual IP, or a managed cloud LB.
  • βœ”One line: β€œA load balancer is the traffic police that shares requests among healthy servers.”
← Previous
Ports and Sockets
Next β†’
Load Balancing Algorithms