Nextgen Blog
HomeLearnAIQuantumRoboticsSecuritySpaceAbout
Nextgen Blog

By Anubhav — full stack engineer, IIT Mandi CSE. Deep dives into AI, software engineering, and the technologies shaping the next generation of tech.

Navigate

  • Home
  • Learn
  • Blog
  • Archive
  • About

Topics

  • Artificial Intelligence
  • Quantum Computing
  • Robotics
  • Cybersecurity
  • Space Tech

Connect

Built with ❤️ & By - Anubhav

© 2026 Nextgen Blog by Anubhav. All rights reserved.

Privacy PolicyTerms of Service
Phase 02 · Scaling, Traffic & Data StoresChapter 9 of 33
08.
Phase 02Read time ~28 minDifficulty advanced

Load Balancers

In this chapter
  • 01Chapter Overview
  • 02What Is a Load Balancer?
  • 03Why Do We Need Load Balancers?
  • 04Load Balancer as a Traffic Director
  • 05Load Balancer vs Reverse Proxy
  • 06Where Does a Load Balancer Sit?
  • 07Types of Load Balancing
  • 08Layer 4 Load Balancing
  • 09Advantages of L4 Load Balancing
  • 10L4 Example
  • 11Layer 7 Load Balancing
  • 12L7 Routing Example
  • 13L4 vs L7
  • 14Load Balancing Algorithms
  • 15Round Robin
  • 16Advantages of Round Robin
  • 17Problem With Simple Round Robin
  • 18Weighted Round Robin
  • 19Least Connections
  • 20Problem With Least Connections
  • 21Weighted Least Connections
  • 22Random Selection
  • 23IP Hash
  • 24Why Use IP Hash?
  • 25Problems With IP Hash
  • 26Sticky Sessions
  • 27Why Sticky Sessions Can Be Useful
  • 28Why Sticky Sessions Can Be a Problem
  • 29Consistent Hashing
  • 30Why Consistent Hashing Matters
  • 31Virtual Nodes
  • 32Health Checks
  • 33Active Health Checks
  • 34Passive Health Checks
  • 35Liveness vs Readiness
  • 36Liveness
  • 37Readiness
  • 38Health Check Pitfall
  • 39Health Check Types
  • 40Connection Draining
  • 41Why Connection Draining Matters
  • 42Session Affinity vs Statelessness
  • 43Design A
  • 44Design B
  • 45Load Balancer and TLS
  • 46TLS Passthrough
  • 47TLS Termination vs Passthrough
  • 48Layer 7 Routing
  • 49Header-Based Routing
  • 50Canary Deployment
  • 51Blue-Green Deployment
  • 52Weighted Routing
  • 53Active-Active Architecture
  • 54Active-Passive Architecture
  • 55High Availability for the Load Balancer
  • 56Load Balancer Failure
  • 57Global Load Balancing
  • 58DNS + Load Balancer
  • 59DNS Load Balancing vs Load Balancer
  • 60DNS-based distribution
  • 61Application load balancer
  • 62Load Balancer as a Failure Boundary
  • 63What If All Servers Are Unhealthy?
  • 64Retry at the Load Balancer
  • 65Retry Amplification
  • 66Connection Reuse
  • 67Load Balancer Resource Limits
  • 68Connection Explosion
  • 69Load Balancing and Backpressure
  • 70Circuit Breaker and Load Balancing
  • 71Load Balancer and Service Discovery
  • 72Kubernetes Example
  • 73Load Balancing Across Availability Zones
  • 74Failure Domain
  • 75Load Balancing and Capacity
  • 76N+1 Capacity
  • 77Load Balancing Case Study — E-Commerce API
  • 78Load Balancing Decision Framework
  • 79Are servers equal?
  • 80Are servers different?
  • 81Are request durations highly variable?
  • 82Do we need affinity?
  • 83Does the backend set change frequently?
  • 84Do we need HTTP-aware routing?
  • 85Common Mistakes
  • 86Mistake 1 — Assuming load balancing means equal traffic
  • 87Mistake 2 — Ignoring unhealthy instances
  • 88Mistake 3 — Depending heavily on sticky sessions
  • 89Mistake 4 — Forgetting LB high availability
  • 90Mistake 5 — Assuming the LB solves database scaling
  • 91Mistake 6 — Ignoring connection draining
  • 92Mistake 7 — Adding retries everywhere
  • 93Mistake 8 — Confusing L4 and L7
  • 94Mistake 9 — Poor health checks
  • 95Interview Questions
  • 96Q1. What is a load balancer?
  • 97Q2. L4 vs L7?
  • 98Q3. Round Robin vs Least Connections?
  • 99Q4. What is sticky session?
  • 100Q5. Why can sticky sessions be problematic?
  • 101Q6. What is connection draining?
  • 102Q7. What is a health check?
  • 103Q8. Why should the load balancer itself be highly available?
  • 104Q9. What is consistent hashing?
  • 105Q10. What is N+1 capacity?
  • 106Practical Exercise
  • 107Mini Project — Highly Available Load-Balanced API
  • 108Scenario A
  • 109Scenario B
  • 110Scenario C
  • 111Scenario D
  • 112Scenario E
  • 113Master Mental Model
  • 114Chapter Summary
  • 115Load Balancer Fundamentals
  • 116Load-Balancing Layers
  • 117Algorithms
  • 118Health and Failure
  • 119Traffic Management
  • 120High Availability
  • 121Scaling
  • 122Chapter 07 Master Checklist
  • 123What Comes Next?
  • 124Chapter 08 — CDN & Edge Computing
In this chapter (124 sections)
01Chapter Overview02What Is a Load Balancer?03Why Do We Need Load Balancers?04Load Balancer as a Traffic Director05Load Balancer vs Reverse Proxy06Where Does a Load Balancer Sit?07Types of Load Balancing08Layer 4 Load Balancing09Advantages of L4 Load Balancing10L4 Example11Layer 7 Load Balancing12L7 Routing Example13L4 vs L714Load Balancing Algorithms15Round Robin16Advantages of Round Robin17Problem With Simple Round Robin18Weighted Round Robin19Least Connections20Problem With Least Connections21Weighted Least Connections22Random Selection23IP Hash24Why Use IP Hash?25Problems With IP Hash26Sticky Sessions27Why Sticky Sessions Can Be Useful28Why Sticky Sessions Can Be a Problem29Consistent Hashing30Why Consistent Hashing Matters31Virtual Nodes32Health Checks33Active Health Checks34Passive Health Checks35Liveness vs Readiness36Liveness37Readiness38Health Check Pitfall39Health Check Types40Connection Draining41Why Connection Draining Matters42Session Affinity vs Statelessness43Design A44Design B45Load Balancer and TLS46TLS Passthrough47TLS Termination vs Passthrough48Layer 7 Routing49Header-Based Routing50Canary Deployment51Blue-Green Deployment52Weighted Routing53Active-Active Architecture54Active-Passive Architecture55High Availability for the Load Balancer56Load Balancer Failure57Global Load Balancing58DNS + Load Balancer59DNS Load Balancing vs Load Balancer60DNS-based distribution61Application load balancer62Load Balancer as a Failure Boundary63What If All Servers Are Unhealthy?64Retry at the Load Balancer65Retry Amplification66Connection Reuse67Load Balancer Resource Limits68Connection Explosion69Load Balancing and Backpressure70Circuit Breaker and Load Balancing71Load Balancer and Service Discovery72Kubernetes Example73Load Balancing Across Availability Zones74Failure Domain75Load Balancing and Capacity76N+1 Capacity77Load Balancing Case Study — E-Commerce API78Load Balancing Decision Framework79Are servers equal?80Are servers different?81Are request durations highly variable?82Do we need affinity?83Does the backend set change frequently?84Do we need HTTP-aware routing?85Common Mistakes86Mistake 1 — Assuming load balancing means equal traffic87Mistake 2 — Ignoring unhealthy instances88Mistake 3 — Depending heavily on sticky sessions89Mistake 4 — Forgetting LB high availability90Mistake 5 — Assuming the LB solves database scaling91Mistake 6 — Ignoring connection draining92Mistake 7 — Adding retries everywhere93Mistake 8 — Confusing L4 and L794Mistake 9 — Poor health checks95Interview Questions96Q1. What is a load balancer?97Q2. L4 vs L7?98Q3. Round Robin vs Least Connections?99Q4. What is sticky session?100Q5. Why can sticky sessions be problematic?101Q6. What is connection draining?102Q7. What is a health check?103Q8. Why should the load balancer itself be highly available?104Q9. What is consistent hashing?105Q10. What is N+1 capacity?106Practical Exercise107Mini Project — Highly Available Load-Balanced API108Scenario A109Scenario B110Scenario C111Scenario D112Scenario E113Master Mental Model114Chapter Summary115Load Balancer Fundamentals116Load-Balancing Layers117Algorithms118Health and Failure119Traffic Management120High Availability121Scaling122Chapter 07 Master Checklist123What Comes Next?124Chapter 08 — CDN & Edge Computing

1. Chapter Overview#

In Chapter 06, we learned horizontal scaling.

Instead of:

Client
  ↓
App Server

we can have:

             ┌── App 1
             ├── App 2
Client → ??? ├── App 3
             └── App 4

The missing component is usually a load balancer.

A load balancer sits between clients and backend servers and decides where traffic should go.

Clients
   ↓
Load Balancer
   ├── App 1
   ├── App 2
   ├── App 3
   └── App 4

But a load balancer does much more than simply "split traffic."

A production load-balancing system may need to handle:

  • health checks
  • failures
  • connection management
  • TLS
  • routing
  • retries
  • session affinity
  • traffic weighting
  • draining
  • failover
  • high availability
  • regional traffic distribution

This chapter builds the complete mental model.


2. What Is a Load Balancer?#

A load balancer is a system that distributes incoming traffic across multiple backend instances.

For example:

             4,000 requests/sec
                     │
                     ▼
               Load Balancer
              /      |      \
             ↓       ↓       ↓
          App 1    App 2    App 3

If each instance can safely handle approximately:

1,500 req/sec

the load balancer can distribute traffic across them.

The objective is not necessarily equal distribution.

The objective is:

Route traffic safely and efficiently to healthy backend capacity.


3. Why Do We Need Load Balancers?#

Without a load balancer, clients need some way to discover individual application servers.

Imagine:

Client
  ↓
App 1

Now App 1 becomes overloaded.

Adding App 2 does not automatically help:

Client
  ↓
App 1
App 2

The client still needs to know when and how to use App 2.

A load balancer provides a stable entry point:

Client
  ↓
Load Balancer
  ├── App 1
  ├── App 2
  └── App 3

The client does not need to know the individual backend addresses.


4. Load Balancer as a Traffic Director#

Think of the load balancer as a traffic controller.

                  ┌── App 1
                  │
Internet → LB ────┼── App 2
                  │
                  └── App 3

The LB decides:

Which backend?
When?
Based on what information?
What if the backend is unhealthy?

These decisions are the core of load balancing.


5. Load Balancer vs Reverse Proxy#

These concepts overlap.

A reverse proxy:

Client
  ↓
Reverse Proxy
  ↓
Backend

A load balancer:

Client
  ↓
Load Balancer
  ├── Backend 1
  ├── Backend 2
  └── Backend 3

A reverse proxy can perform load balancing.

For example, Nginx can act as:

  • reverse proxy
  • load balancer
  • TLS terminator
  • cache
  • static file server

Therefore:

"Reverse proxy" describes a role, while "load balancer" describes a traffic-distribution function.

Modern infrastructure components can perform both.


6. Where Does a Load Balancer Sit?#

A common architecture:

Internet
   ↓
DNS
   ↓
Load Balancer
   ↓
Application Servers
   ↓
Cache / Database

A more advanced architecture:

Internet
   ↓
CDN / Edge
   ↓
Load Balancer
   ↓
API Gateway
   ↓
Application Cluster

The exact ordering depends on the system.


7. Types of Load Balancing#

There are two major categories to understand:

Layer 4 Load Balancing
Layer 7 Load Balancing

The distinction comes from the networking layers.


8. Layer 4 Load Balancing#

Layer 4 operates primarily using transport-level information.

Typical information includes:

  • source IP
  • destination IP
  • source port
  • destination port
  • TCP/UDP connection information

It does not need to understand the full HTTP request.

Conceptually:

Client
 ↓ TCP
L4 Load Balancer
 ↓ TCP
Backend

9. Advantages of L4 Load Balancing#

L4 load balancing can be:

  • fast
  • efficient
  • protocol-agnostic at the application layer
  • useful for TCP/UDP services

It can handle protocols other than HTTP.

Examples:

TCP
UDP
TLS pass-through
Database connections
Other network protocols

10. L4 Example#

Suppose:

Client IP: 10.0.0.10
Destination: 203.0.113.10:443

The L4 load balancer can choose:

Backend 1 → 10.0.1.10:443

It does not necessarily need to inspect:

GET /users/123

11. Layer 7 Load Balancing#

Layer 7 load balancing operates at the application layer.

For HTTP traffic, it can inspect:

  • HTTP method
  • URL
  • headers
  • cookies
  • host
  • query parameters
  • sometimes request metadata

Example:

GET /api/users

could be routed to:

User Service

while:

GET /api/orders

could go to:

Order Service

12. L7 Routing Example#

                    L7 Load Balancer
                           │
             ┌─────────────┼─────────────┐
             ↓             ↓             ↓
        /users          /orders       /payments
             ↓             ↓             ↓
       User Service   Order Service  Payment Service

This is much more application-aware than simple connection-level routing.


13. L4 vs L7#

L4 L7
Transport-level Application-level
TCP/UDP aware HTTP-aware
Less request inspection Can inspect HTTP details
Often lower overhead More processing
Protocol-agnostic at app layer Application-specific
Good for raw TCP/UDP Good for HTTP routing

Neither is universally better.

The choice depends on requirements.


14. Load Balancing Algorithms#

Once a load balancer receives a request, it needs a routing strategy.

Common algorithms include:

  1. Round Robin
  2. Weighted Round Robin
  3. Least Connections
  4. Weighted Least Connections
  5. IP Hash
  6. Consistent Hashing
  7. Random
  8. Least Response Time

Different algorithms solve different problems.


15. Round Robin#

The simplest algorithm.

Suppose:

Servers:
A
B
C

Requests:

Request 1 → A
Request 2 → B
Request 3 → C
Request 4 → A
Request 5 → B
Request 6 → C

Pattern:

A → B → C → A → B → C

16. Advantages of Round Robin#

It is:

  • simple
  • predictable
  • easy to implement

It works well when backend servers have approximately equal capacity and requests have similar cost.


17. Problem With Simple Round Robin#

Suppose:

Server A → powerful
Server B → medium
Server C → weak

Round robin still sends:

A = 1/3
B = 1/3
C = 1/3

This may be inefficient.

Another issue:

Request 1 → 1 ms
Request 2 → 10 seconds

All requests are not equally expensive.

Round robin does not know this.


18. Weighted Round Robin#

Assign weights:

A → weight 5
B → weight 3
C → weight 2

Approximate distribution:

A → 50%
B → 30%
C → 20%

Useful when servers have different capacities.


19. Least Connections#

Route the new connection/request to the backend with the fewest active connections.

Example:

App 1 → 100 connections
App 2 → 40 connections
App 3 → 70 connections

New request:

→ App 2

This can work better when requests have significantly different durations.


20. Problem With Least Connections#

The number of connections is not always the same as actual workload.

For example:

App 1 → 10 expensive requests
App 2 → 30 cheap requests

App 1 has fewer connections but may be more CPU-intensive.

Therefore connection count is only an approximation of load.


21. Weighted Least Connections#

Combines:

Current connections
+
Server capacity

A more powerful server can receive more traffic while still considering active connections.


22. Random Selection#

The load balancer randomly chooses a backend.

Request 1 → B
Request 2 → A
Request 3 → C
Request 4 → B

With enough requests, traffic can approach a balanced distribution.

Randomization is useful in many distributed systems, especially when combined with other strategies.


23. IP Hash#

The load balancer hashes the client's IP.

Conceptually:

hash(client_ip) % N

Example:

User A → hash → Server 1
User B → hash → Server 3
User C → hash → Server 2

This can provide a form of session affinity.


24. Why Use IP Hash?#

Suppose an application has local session state.

You might want:

User A → App 1
User A → App 1
User A → App 1

IP hashing can provide approximate affinity.

But it has limitations.


25. Problems With IP Hash#

Users may appear behind the same NAT.

Example:

Office
 ├── User A
 ├── User B
 ├── User C
 └── User D
        ↓
   Same public IP

They may all hash to the same backend.

Also, when servers are added or removed:

N changes

and many users may map to different servers.


26. Sticky Sessions#

Sticky sessions mean the load balancer attempts to keep a client associated with the same backend.

Example:

User A
  ↓
App 1
 
Later:
User A
  ↓
App 1

This can be implemented using:

  • cookies
  • client IP
  • generated affinity identifiers
  • load-balancer-specific mechanisms

27. Why Sticky Sessions Can Be Useful#

Suppose:

Session stored in App 1 memory

Sticky sessions ensure:

User
 ↓
App 1

instead of:

User
 ↓
App 2

where the session does not exist.


28. Why Sticky Sessions Can Be a Problem#

They create dependency on specific instances.

If:

User → App 1

and App 1 crashes:

User → App 1
        X

the user may lose local state.

They can also cause uneven load:

App 1 → 80%
App 2 → 10%
App 3 → 10%

Therefore a shared session store is often preferable when possible.


29. Consistent Hashing#

Consistent hashing is useful when we want stable mapping between keys and backend nodes while allowing the node set to change.

Instead of:

hash(key) % N

which can remap many keys when N changes, consistent hashing uses a logical hash ring.

Conceptually:

             Hash Ring
 
          A
      /         \
    D             B
      \         /
          C

Keys are mapped to positions on the ring and assigned to the next appropriate node.


30. Why Consistent Hashing Matters#

Suppose:

Server A
Server B
Server C

A new server is added:

Server D

With simple modulo hashing:

hash(key) % N

many keys may move.

With consistent hashing:

Ideally, only a subset of keys needs to move.

This is particularly useful for:

  • distributed caches
  • sharded systems
  • partition ownership
  • some routing architectures

We will revisit consistent hashing later.


31. Virtual Nodes#

Consistent hashing can use virtual nodes.

Instead of one position per physical server:

Server A → A1, A2, A3...
Server B → B1, B2, B3...

This improves distribution around the ring.

Conceptually:

A1
B1
A2
C1
B2
A3
C2
...

If a physical server is removed, its virtual-node ranges can be reassigned.


32. Health Checks#

A load balancer should not route traffic to an unhealthy backend.

Example:

App 1 → healthy
App 2 → unhealthy
App 3 → healthy

Traffic:

             Load Balancer
              /          \
             ↓            ↓
           App 1        App 3

App 2 is temporarily removed from rotation.


33. Active Health Checks#

The load balancer periodically checks the backend.

For example:

GET /health

Response:

200 OK

means the server is considered healthy according to that check.

If:

timeout
500
connection refused

the backend may be marked unhealthy.


34. Passive Health Checks#

The load balancer can also observe actual traffic.

For example:

Backend returns repeated 503s

The load balancer may temporarily reduce or stop sending traffic to it.

Passive and active health mechanisms can be combined.


35. Liveness vs Readiness#

These are especially important in modern application platforms.

Liveness#

"Is the process alive?"

Readiness#

"Can this instance safely receive traffic?"

Example:

Process = running
Database = unavailable

The process is alive.

But it may not be ready to serve requests.

Therefore:

Liveness → yes
Readiness → no

The load balancer/orchestrator can use readiness to control traffic.


36. Health Check Pitfall#

Do not make a health endpoint unnecessarily dependent on every downstream service.

Bad:

/health
 ↓
Database
 ↓
Redis
 ↓
External API
 ↓
Queue

If any dependency fails, the whole instance may be declared unhealthy.

Sometimes that causes a large-scale failure:

Database temporary issue
       ↓
All instances fail health checks
       ↓
All instances removed
       ↓
No traffic served

Health checks should reflect the intended readiness semantics carefully.


37. Health Check Types#

A system may have:

/health/live
/health/ready

For example:

live:
  Process running
 
ready:
  Application initialized
  Required dependencies available

The exact readiness requirements depend on the service.


38. Connection Draining#

Suppose:

App 1
App 2
App 3

We want to remove App 2 for deployment.

Bad:

Remove App 2
 ↓
Immediately terminate
 ↓
Active requests fail

Connection draining:

Stop new requests → App 2
         ↓
Existing requests finish
         ↓
Close connections
         ↓
Terminate App 2

This is also called:

Connection draining / graceful deregistration


39. Why Connection Draining Matters#

It is important during:

  • deployments
  • autoscaling
  • instance replacement
  • maintenance
  • failure handling

Without draining, users can experience unnecessary request failures.


40. Session Affinity vs Statelessness#

Two designs:

Design A#

Sticky Sessions
+
Local session memory

Design B#

Stateless Apps
+
Shared Session Store

Design B usually provides more flexibility for horizontal scaling.

Example:

App 1 ─┐
App 2 ─┼──→ Redis
App 3 ─┘

Now any backend can handle a request.


41. Load Balancer and TLS#

HTTPS can be terminated at the load balancer.

Client
  ↓ HTTPS
Load Balancer
  ↓ HTTP/internal TLS
Application

This is called:

TLS termination

Benefits:

  • centralized certificate management
  • reduced TLS work on application servers
  • simpler application infrastructure

42. TLS Passthrough#

Alternatively:

Client
  ↓ HTTPS
Load Balancer
  ↓ HTTPS
Application

The load balancer forwards encrypted traffic without terminating TLS.

The backend handles TLS.

This may be useful when end-to-end encryption requirements or application-level certificate handling require it.


43. TLS Termination vs Passthrough#

Termination Passthrough
LB decrypts traffic LB does not decrypt
Easier centralized certificate management Backend handles TLS
LB can inspect HTTP if L7 Cannot inspect encrypted HTTP content
Can reduce backend TLS work End-to-end encryption remains intact to backend

Some systems use re-encryption:

Client
 ↓ HTTPS
LB
 ↓ HTTPS
Backend

The LB terminates the first TLS connection and establishes another TLS connection to the backend.


44. Layer 7 Routing#

An L7 load balancer can route based on hostname.

Example:

api.example.com
    ↓
API Cluster
 
admin.example.com
    ↓
Admin Cluster

It can also route by path:

/api/users
    ↓
User Service
 
/api/orders
    ↓
Order Service

This is often called:

Content-based routing


45. Header-Based Routing#

For example:

X-Region: IN

could influence routing.

Or:

X-Experiment: A

could route users to a particular deployment.

This can support:

  • experiments
  • canary deployments
  • tenant routing
  • regional routing

Routing policies must be carefully controlled because headers may be client-controlled unless added or validated by trusted infrastructure.


46. Canary Deployment#

Suppose:

Version A → 95%
Version B → 5%

The load balancer can send a small percentage of traffic to Version B.

                 Load Balancer
                 /           \
                ↓             ↓
          Version A        Version B
             95%              5%

If metrics are healthy, traffic can gradually increase:

95/5
 ↓
90/10
 ↓
75/25
 ↓
50/50
 ↓
100/0

Canary deployment reduces blast radius.


47. Blue-Green Deployment#

Two environments:

Blue  → Current
Green → New

Traffic initially goes to Blue.

LB
 ↓
Blue

After Green is validated:

LB
 ↓
Green

Rollback can potentially switch traffic back to Blue.

This requires both environments to be maintained during the transition.


48. Weighted Routing#

A load balancer can distribute traffic by weights.

Example:

Version A → 90
Version B → 10

Approximately:

90% → A
10% → B

Weights can be used for:

  • canaries
  • gradual migration
  • heterogeneous servers
  • regional balancing

49. Active-Active Architecture#

Multiple backend clusters actively serve traffic.

                 Traffic
                /       \
               ↓         ↓
           Region A    Region B
             Active      Active

Advantages:

  • better utilization
  • regional distribution
  • failover capacity

Challenges:

  • data consistency
  • routing
  • cross-region latency
  • deployment coordination

50. Active-Passive Architecture#

One environment serves traffic.

Another is ready for failover.

Primary → Active
Secondary → Standby

During failure:

Primary fails
      ↓
Traffic → Secondary

This can be simpler but may leave standby capacity underutilized.


51. High Availability for the Load Balancer#

A load balancer itself cannot become a single point of failure.

Bad:

             Single LB
                X
                ↓
            All traffic

If the LB fails:

Entire application unreachable

Therefore production load-balancing infrastructure is usually redundant.

Conceptually:

             LB Cluster
            /          \
           LB1         LB2
            \           /
             Backend Pool

Managed cloud load balancers typically hide much of this infrastructure.


52. Load Balancer Failure#

Suppose:

LB
 ↓
App 1
App 2
App 3

If the LB crashes, application servers may still be healthy but unreachable.

Therefore high-availability design must consider:

DNS
Load Balancer
Application
Database

not just the application servers.


53. Global Load Balancing#

For global systems:

Users
 ├── India
 ├── Europe
 ├── USA
 └── Asia

we may route users to nearby regions.

                 Global Routing
               /       |       \
              ↓        ↓        ↓
           India     Europe     USA
           Region    Region    Region

Routing can consider:

  • geography
  • latency
  • health
  • capacity
  • policy

DNS, Anycast, CDN, and global load-balancing services can participate in this architecture.


54. DNS + Load Balancer#

A simplified architecture:

User
 ↓
DNS
 ↓
Load Balancer
 ↓
Application Servers

DNS chooses the destination infrastructure.

The load balancer chooses the backend instance.

This creates two different routing layers.


55. DNS Load Balancing vs Load Balancer#

DNS-based distribution#

DNS
 ↓
Region A
or
Region B

Application load balancer#

LB
 ↓
App A
App B
App C

DNS usually operates at a coarser level.

The load balancer can make much more frequent backend-level decisions.


56. Load Balancer as a Failure Boundary#

Consider:

App 1 → unhealthy
App 2 → healthy
App 3 → healthy

The LB can remove App 1.

Therefore:

One instance failure
        ↓
Traffic redirected
        ↓
Service continues

This is a major availability benefit.


57. What If All Servers Are Unhealthy?#

Then the load balancer cannot manufacture capacity.

LB
 ├── App 1 X
 ├── App 2 X
 └── App 3 X

Possible behavior:

503 Service Unavailable

The load balancer should fail clearly rather than pretending the service is healthy.


58. Retry at the Load Balancer#

Some load balancers can retry failed upstream connections.

Potential flow:

Request
 ↓
App 1 → failure
 ↓
Retry
 ↓
App 2
 ↓
Success

This can improve resilience for transient failures.

But retries can also amplify load.

Therefore:

Load-balancer retries must be bounded and carefully coordinated with application-level retries.


59. Retry Amplification#

Suppose:

Client retry = 2 attempts
LB retry = 2 attempts
Service retry = 2 attempts

One logical request can potentially create many physical attempts.

A simplified worst-case multiplication can become:

2 × 2 × 2 = 8 attempts

Actual behavior depends on implementation and where failures occur.

This is why retry ownership should be designed explicitly.


60. Connection Reuse#

For HTTP systems, connection reuse can reduce overhead.

Instead of:

Request
 ↓
New TCP connection
 ↓
Request
 ↓
Close

persistent connections can be reused.

The load balancer may maintain:

Client connections

and separately:

Backend connections

This allows it to manage frontend and backend connection lifecycles independently.


61. Load Balancer Resource Limits#

A load balancer can itself be constrained by:

  • connections
  • packets/sec
  • requests/sec
  • bandwidth
  • TLS handshakes
  • CPU
  • memory
  • routing rules
  • connection tracking state

Large-scale systems must monitor these limits.


62. Connection Explosion#

Suppose:

100,000 clients

and the load balancer maintains backend connections.

If backend connection pooling is poorly configured, the number of connections can become enormous.

Therefore:

Client connections
        ↓
Load Balancer
        ↓
Backend connection pools

must be designed together.


63. Load Balancing and Backpressure#

The load balancer can help enforce capacity boundaries.

Example:

Traffic
  ↓
LB
  ↓
Healthy backends

If all backends are overloaded, additional mechanisms may be needed:

Rate limiting
Queueing
Load shedding
Circuit breakers

The LB is not a substitute for end-to-end overload protection.


64. Circuit Breaker and Load Balancing#

Suppose:

Service B

is failing.

Service A keeps sending requests.

A circuit breaker can stop repeated calls temporarily.

Service A
   ↓
Circuit Breaker
   ↓
Service B

This is different from load balancing.

Load balancing chooses:

Which healthy backend?

A circuit breaker decides:

Should we call this dependency at all?

We will study circuit breakers in the distributed-systems section.


65. Load Balancer and Service Discovery#

In dynamic environments, backend instances can change.

Example:

App 1
App 2
App 3

App 3 is replaced:

App 4

The load balancer needs current backend information.

This can come from:

  • service discovery
  • orchestrators
  • cloud control planes
  • DNS
  • static configuration

Kubernetes, for example, provides service discovery and routing mechanisms.


66. Kubernetes Example#

Conceptually:

Client
  ↓
Ingress / Load Balancer
  ↓
Kubernetes Service
  ↓
Pods
 ├── Pod 1
 ├── Pod 2
 └── Pod 3

Pods can be created or removed dynamically.

The service layer abstracts changing pod IPs.

We will study Kubernetes system design later.


67. Load Balancing Across Availability Zones#

Cloud systems commonly spread application instances across failure domains.

Example:

             Load Balancer
             /           \
            ↓             ↓
        Zone A          Zone B
        App 1           App 3
        App 2           App 4

If Zone A fails:

Zone B
  ↓
Continue serving

This improves availability.


68. Failure Domain#

A failure domain is a group of resources that can fail together.

Examples:

  • process
  • machine
  • rack
  • availability zone
  • region

Good architecture avoids placing all capacity in one failure domain.

Load balancers can distribute traffic across multiple domains.


69. Load Balancing and Capacity#

Suppose:

Traffic = 9,000 req/sec

Servers:

App 1 = 3,000
App 2 = 3,000
App 3 = 3,000

Total:

9,000 req/sec

Now App 2 fails.

Remaining capacity:

3,000 + 3,000
= 6,000 req/sec

Traffic:

9,000 req/sec

The system is now overloaded.

Therefore high availability requires failure capacity, not merely multiple instances.


70. N+1 Capacity#

A common resilience concept is N+1 capacity.

If normal required capacity is:

N

provision:

N + 1

so the system can tolerate one failure.

Example:

Required = 3 instances
Provision = 4

If one fails:

4 → 3

and normal capacity remains.

At larger scale, more sophisticated redundancy targets may be used.


71. Load Balancing Case Study — E-Commerce API#

Requirements:

20,000 req/sec peak
99.99% availability
Multiple application servers

Architecture:

                    Internet
                       │
                       ▼
                      DNS
                       │
                       ▼
               Load Balancer Cluster
                  /    |    \
                 ↓     ↓     ↓
               App1  App2   App3
                 │     │     │
                 └─────┼─────┘
                       ▼
                     Redis
                       │
                       ▼
                   Database

LB responsibilities:

  • health checks
  • routing
  • TLS termination
  • connection management
  • traffic distribution

Application responsibilities:

  • business logic
  • authentication
  • validation
  • data access

Database remains a separate scaling concern.


72. Load Balancing Decision Framework#

When choosing a strategy, ask:

1. Are servers equal?#

If yes:

Round Robin

may be sufficient.

2. Are servers different?#

Consider:

Weighted Round Robin

3. Are request durations highly variable?#

Consider:

Least Connections

4. Do we need affinity?#

Consider:

Sticky Sessions
IP Hash

But first ask whether the application can be made stateless.

5. Does the backend set change frequently?#

Consider:

Service Discovery
Consistent Hashing

where appropriate.

6. Do we need HTTP-aware routing?#

Use:

L7

73. Common Mistakes#

Mistake 1 — Assuming load balancing means equal traffic#

The goal is appropriate distribution, not necessarily exact equality.


Mistake 2 — Ignoring unhealthy instances#

Traffic should not continue going to failed backends.


Mistake 3 — Depending heavily on sticky sessions#

They can reduce flexibility and create uneven load.


Mistake 4 — Forgetting LB high availability#

A single LB can become a single point of failure.


Mistake 5 — Assuming the LB solves database scaling#

It only distributes traffic to backends.


Mistake 6 — Ignoring connection draining#

Immediate instance termination can fail active requests.


Mistake 7 — Adding retries everywhere#

Multiple retry layers can amplify traffic.


Mistake 8 — Confusing L4 and L7#

L4 works with transport-level information.

L7 can inspect application-level protocol details.


Mistake 9 — Poor health checks#

A bad health check can either:

send traffic to broken instances

or:

remove healthy instances unnecessarily

74. Interview Questions#

Q1. What is a load balancer?#

A component that distributes incoming traffic among backend instances according to routing and health policies.


Q2. L4 vs L7?#

L4 operates primarily at the transport layer and routes based on connection/network metadata.

L7 understands application-layer protocols such as HTTP and can route based on request properties.


Q3. Round Robin vs Least Connections?#

Round Robin cycles through backends.

Least Connections chooses a backend with fewer active connections.


Q4. What is sticky session?#

A mechanism that attempts to route a client repeatedly to the same backend.


Q5. Why can sticky sessions be problematic?#

They can create uneven load, reduce failover flexibility, and make local state dependencies harder to manage.


Q6. What is connection draining?#

Allowing an instance to finish existing requests before removing it from service.


Q7. What is a health check?#

A mechanism for determining whether a backend should receive traffic.


Q8. Why should the load balancer itself be highly available?#

Because if it becomes a single point of failure, backend redundancy does not help.


Q9. What is consistent hashing?#

A hashing approach that minimizes key remapping when backend nodes are added or removed.


Q10. What is N+1 capacity?#

Provisioning one additional unit beyond the normal required capacity so the system can tolerate one failure.


75. Practical Exercise#

Design the load-balancing layer for:

50,000 requests/sec
20 application servers
99.99% availability

Requirements:

  • servers can fail
  • deployments should not drop active requests
  • traffic should be distributed efficiently
  • new servers can be added dynamically
  • HTTPS is required

Answer:

  1. L4 or L7?
  2. Which algorithm?
  3. How do you perform health checks?
  4. Where does TLS terminate?
  5. How do you drain servers?
  6. How do you avoid a single LB failure?
  7. What happens when one server crashes?
  8. What happens when one availability zone fails?
  9. Should you use sticky sessions?
  10. How would you gradually deploy a new application version?

76. Mini Project — Highly Available Load-Balanced API#

Design:

                         Internet
                            │
                            ▼
                           DNS
                            │
                            ▼
                 ┌─────────────────────┐
                 │  LB / LB Cluster    │
                 └──────────┬──────────┘
                            │
               ┌────────────┼────────────┐
               ▼            ▼            ▼
             App 1        App 2        App 3
               │            │            │
               └────────────┼────────────┘
                            ▼
                          Redis
                            │
                            ▼
                         Database

Add:

Health Checks
Connection Draining
TLS
Autoscaling
Request IDs
Metrics
Logs

Then simulate:

Scenario A#

App 2 crashes

Scenario B#

App 3 is being deployed

Scenario C#

Traffic doubles

Scenario D#

One availability zone fails

Scenario E#

New version should receive 5% traffic

Explain how the load-balancing layer handles each case.


77. Master Mental Model#

When designing load balancing, think:

                 CLIENTS
                    │
                    ▼
               DNS / EDGE
                    │
                    ▼
             LOAD BALANCER
                    │
        ┌───────────┼───────────┐
        ▼           ▼           ▼
      App 1       App 2       App 3
        │           │           │
        └───────────┼───────────┘
                    │
                 Backend

Then ask:

Are backends healthy?
        ↓
Which backend should receive traffic?
        ↓
How much traffic should it receive?
        ↓
What if it fails?
        ↓
What if it is being deployed?
        ↓
What if traffic increases?
        ↓
What if an entire failure domain fails?
        ↓
What if the load balancer itself fails?

This is the core load-balancing mindset.


78. Chapter Summary#

You should now understand:

Load Balancer Fundamentals#

  • what a load balancer is
  • why it is needed
  • load balancer vs reverse proxy
  • frontend/backend traffic flow

Load-Balancing Layers#

  • L4
  • L7
  • L4 vs L7
  • HTTP-aware routing
  • TCP/UDP routing

Algorithms#

  • round robin
  • weighted round robin
  • least connections
  • weighted least connections
  • random
  • IP hash
  • sticky sessions
  • consistent hashing
  • virtual nodes

Health and Failure#

  • active health checks
  • passive health checks
  • liveness
  • readiness
  • connection draining
  • backend failures
  • LB failures
  • failure domains
  • N+1 capacity

Traffic Management#

  • TLS termination
  • TLS passthrough
  • content-based routing
  • header-based routing
  • weighted routing
  • canary deployments
  • blue-green deployments

High Availability#

  • active-active
  • active-passive
  • redundant load balancers
  • multi-zone architecture
  • global load balancing
  • DNS + load balancer

Scaling#

  • backend capacity
  • connection limits
  • LB resource limits
  • connection reuse
  • autoscaling interaction
  • service discovery

79. Chapter 07 Master Checklist#

Before moving forward, make sure you can explain:

  • What a load balancer is
  • Why load balancers are needed
  • Reverse proxy vs load balancer
  • L4 load balancing
  • L7 load balancing
  • L4 vs L7
  • Round Robin
  • Weighted Round Robin
  • Least Connections
  • Weighted Least Connections
  • Random routing
  • IP Hash
  • Sticky Sessions
  • Consistent Hashing
  • Virtual Nodes
  • Health Checks
  • Active vs passive health checks
  • Liveness vs readiness
  • Connection draining
  • TLS termination
  • TLS passthrough
  • Content-based routing
  • Header-based routing
  • Weighted routing
  • Canary deployments
  • Blue-green deployments
  • Active-active
  • Active-passive
  • Load balancer high availability
  • Global load balancing
  • DNS + load balancer
  • Failure domains
  • N+1 capacity
  • Connection reuse
  • LB resource limits
  • Retry amplification
  • Service discovery
  • Multi-zone load balancing

80. What Comes Next?#

Chapter 08 — CDN & Edge Computing#

We now know how to distribute dynamic requests across application servers.

Next, we ask:

Can we prevent many requests from reaching our application servers in the first place?

That is where CDNs and edge infrastructure become important.

We will learn:

User
 ↓
Nearest Edge Location
 ├── Cache Hit → Response
 └── Cache Miss
        ↓
      Origin
        ↓
   Application

Topics will include:

  • what a CDN is
  • edge locations
  • origin servers
  • CDN caching
  • cache keys
  • TTL
  • cache invalidation
  • cache-control headers
  • stale content
  • cache hit ratio
  • static vs dynamic content
  • CDN for images and videos
  • origin shielding
  • request routing
  • edge computing
  • edge functions
  • geo-routing
  • DDoS protection concepts
  • CDN failure scenarios
  • CDN + load balancer architecture
  • real-world CDN design
  • interview questions
  • practical exercises
  • mini project

Finished this chapter?

Mark it as complete to track your mastery.

Previous ChapterChapter 06 — Scaling ApplicationsNext ChapterChapter 08 — CDN & Edge Computing
PrevNext