System designScalabilityFundamental

Load Balancing in System Design

Why one server is never enough, how a load balancer decides where each request goes, and how to keep the balancer itself from becoming the thing that breaks.

The short answerA load balancer sits between clients and a pool of servers and decides which healthy server gets each new request or connection. It lets you scale horizontally, survive individual server failures and deploy without downtime. Layer 4 balancers route by IP and port; Layer 7 balancers read HTTP and can route by host, path, header or cookie.

HLD book
01Fundamentals

What is a load balancer?

A traffic-distribution layer between clients and a pool of servers. For every new request or connection, it picks one healthy server.

One endpoint, many servers
ClientsWeb, mobile, API consumers
Load balancerHealth checks + routing decision
Server Ahealthy
Server Bhealthy
Server Chealthy

Why one server is not enough

A single server has finite CPU, memory, bandwidth and connections, and however big it gets it is still one failure domain. Horizontal scaling runs many copies; the load balancer is what makes many copies usable.

What the balancer knows

Depending on its type: which backends are healthy, their connection counts and latency, the request's host and path, cookies, headers and server weights. It never sends new traffic to a server marked unhealthy.

The life of one request

  1. The client calls a stable name

    For example api.example.com. It never knows how many servers sit behind it.

  2. The edge receives it

    DNS, a CDN or a WAF may sit before the load balancer.

  3. The balancer filters the pool

    Only healthy, ready, non-draining targets are eligible.

  4. The algorithm picks one

    Round robin, least connections, a hash, and so on.

  5. The backend responds

    Back through the proxy, or straight to the client in some L4 setups.

02Classification

Types of load balancers

“Type” can mean four different things. Interviewers notice when you separate them instead of listing everything in one breath.

Four independent ways to classify a load balancer
Load balancer
Protocol layerL4 / L7
DeploymentHardware / software / managed
Traffic scopeExternal / internal / global
Who decidesClient-side / server-side
  1. Layer 4 load balancer

    Protocol layer
    How it works
    Accepts a TCP/UDP connection and forwards it to a healthy backend by IP and port, without reading HTTP.
    Common use
    Databases, game servers, MQTT, raw TCP/UDP and very high-throughput traffic.
    Strength
    Fast, simple and works for any protocol.
    Trade-off
    Can't route by path, header, cookie or user plan.
  2. Layer 7 load balancer

    Protocol layer
    How it works
    Terminates HTTP (and usually TLS), reads the request, applies routing rules, then forwards to a backend.
    Common use
    Microservices, REST APIs, web apps, canary releases, TLS termination.
    Strength
    Rich routing and per-request control.
    Trade-off
    More processing and config, and it sits in every request's path.
  3. Hardware appliance

    Deployment
    How it works
    A dedicated physical device in the data centre with vendor software for L4/L7, TLS offload and security.
    Common use
    Traditional enterprise and regulated data centres.
    Strength
    Very high, predictable throughput.
    Trade-off
    Expensive, slow to buy, fixed capacity.
  4. Software load balancer

    Deployment
    How it works
    NGINX, HAProxy or Envoy running on VMs, containers or bare metal.
    Common use
    Self-managed infra, Kubernetes ingress, service meshes.
    Strength
    Full control and cheap to scale out.
    Trade-off
    Your team owns upgrades, scaling and its high availability.
  5. Managed cloud load balancer

    Deployment
    How it works
    You configure listeners, rules, certificates and health checks; the provider runs and scales it.
    Common use
    Cloud-native apps that want simple operations and autoscaling.
    Strength
    Little to operate, built-in multi-zone.
    Trade-off
    Provider-specific behaviour, quotas and cost.
  6. External vs internal

    Traffic scope
    External
    Public endpoint for websites, mobile and public APIs. Needs TLS, DDoS protection and a WAF.
    Internal
    Private endpoint inside the VPC for service-to-service traffic. Still needs auth and segmentation.
  7. Client-side vs server-side

    Who decides
    Client-side
    The caller's library picks an instance from service discovery. No extra hop, but every client needs routing logic.
    Server-side
    Clients call one stable endpoint and the proxy picks the backend. Simpler clients; the proxy must be highly available.
  8. DNS / global load balancing

    Global routing
    How it works
    GeoDNS, anycast or a global proxy sends each user to a healthy, nearby region.
    Common use
    Multi-region apps, disaster recovery, lower latency worldwide.
    Strength
    Regional failover and latency gains.
    Trade-off
    DNS caching delays failover; data across regions is the hard part.
03Core interview topic

Layer 4 vs Layer 7 load balancing

Both pick a backend. They differ in how much of the request they can see, and therefore in what they can decide.

Layer 4 · transport

Works with connection metadata only.

  • Routes by source/destination IP, port and protocol
  • Never parses HTTP, so it works for any TCP/UDP service
  • Example: TCP 5432 to a pool of PostgreSQL proxies
  • Can pass TLS through untouched

Layer 7 · application

Understands HTTP and what the request means.

  • Routes by host, path, method, header or cookie
  • One domain: /users, /orders, /payments to different services
  • TLS termination, redirects, header rewrites
  • Canary releases, A/B tests, auth integration
Layer 4Layer 7
SeesIP, port, TCP/UDP connectionHost, path, headers, cookies, method
HTTP-awareNoYes
Path routingNoYes
TLS terminationUsually passes TLS throughCommonly terminates it
ProtocolsAny TCP/UDPHTTP/1.1, HTTP/2, gRPC, WebSocket
Cost per requestLowerHigher (parses every request)
Typical productNetwork load balancerApplication load balancer, ingress

L4: a connection-level decision

ClientOpens a TCP connection
L4 balancerDecides on IP + port
BackendGets the whole connection

L7: path-based routing

api.example.comHTTPS requests
L7 balancerHost / path / header rules
/usersUser service
/ordersOrder service
/paymentsPayment service
04Routing strategy

Load balancing algorithms

Once the balancer knows which servers are eligible, an algorithm picks one. Static algorithms ignore live load; dynamic ones react to it.

  1. Round robin

    Static
    Rule
    S1 → S2 → S3 → S1 → …
    How
    Each healthy server gets the next request in turn.
    Best for
    Equal servers and similar request costs.
    Trade-off
    Blind to load: a server stuck on slow requests still gets its turn.
  2. Weighted round robin

    Static, weighted
    Rule
    S1 weight 5, S2 weight 3, S3 weight 2
    How
    Traffic in proportion to configured weights.
    Best for
    Mixed server sizes and gradual traffic shifts (canaries).
    Trade-off
    Static weights don't follow live CPU or latency.
  3. Least connections

    Dynamic
    Rule
    Pick the server with the fewest active connections
    How
    Tracks open connections per server.
    Best for
    Uneven or long-lived requests, WebSockets.
    Trade-off
    One connection can cost much more than another.
  4. Weighted least connections

    Dynamic, weighted
    Rule
    Connections ÷ capacity weight
    How
    Bigger servers may hold more concurrent connections.
    Best for
    Mixed fleets with varying request duration.
    Trade-off
    Needs sensible weights and accurate counts.
  5. Least response time

    Dynamic
    Rule
    Prefer low latency and low active load
    How
    Uses observed response times, often with connection counts.
    Best for
    Backends whose latency varies at runtime.
    Trade-off
    Noisy measurements can make traffic oscillate.
  6. Random

    Probabilistic
    Rule
    Pick any healthy server
    How
    Over many requests, load evens out.
    Best for
    Large, uniform pools.
    Trade-off
    Short-term imbalance; ignores live load.
  7. Power of two choices

    Probabilistic, dynamic
    Rule
    Sample 2 random servers → pick the less loaded
    How
    Near-optimal balance without scanning every server.
    Best for
    Large pools and many independent balancers.
    Trade-off
    Needs a meaningful load signal.
  8. IP hash

    Hash-based
    Rule
    hash(clientIP) % N
    How
    The same IP usually reaches the same server.
    Best for
    Simple, approximate client affinity.
    Trade-off
    NAT puts many users on one IP; changing N remaps most clients.
  9. URL / key hash

    Hash-based
    Rule
    hash(path or tenant or userId) → server
    How
    Related requests land on the same worker.
    Best for
    Cache locality and tenant affinity.
    Trade-off
    Skewed keys create hot spots.
  10. Consistent hashing

    Hash-based
    Rule
    hash(key) → position on a ring → next server clockwise
    How
    Adding or removing a server remaps only its neighbours' keys.
    Best for
    Distributed caches and partition-aware routing.
    Trade-off
    More complex; needs virtual nodes for even spread.
  11. Adaptive / resource-based

    Dynamic
    Rule
    Score from CPU, memory, queue depth, latency, errors
    How
    Routes on live resource signals.
    Best for
    Workloads where connection count misleads.
    Trade-off
    Delayed telemetry can cause feedback loops.

Round robin, visualised

Request 1
Request 2
Request 3
Round robinCycle through healthy servers
Server A← request 1
Server B← request 2
Server C← request 3
05Reliability

Health checks and backend eligibility

The balancer must know which servers can safely take traffic. Health checking is part of routing correctness, not just monitoring.

Active health checks

The balancer probes each backend on a schedule.

  • TCP connect or GET /health/ready every few seconds
  • Removed after N consecutive failures
  • Re-added only after M successes, to avoid flapping

Passive health signals

The balancer watches real production traffic.

  • Timeouts and connection resets
  • Spikes in 5xx responses
  • Unusually high latency (outlier detection)
A readiness endpointhttp
GET /health/ready

HTTP/1.1 200 OK
Content-Type: application/json

{ "status": "UP", "ready": true, "db": "ok", "cache": "ok" }
The healthy pool
Load balancerKeeps the list of eligible servers
Server Ahealthy: gets traffic
Server Bunhealthy: removed
Server Chealthy: gets traffic

Connection draining

Killing an instance mid-deploy drops whatever it was serving. Instead, mark it draining: stop sending new requests, let in-flight requests and open connections finish within a grace period (say 30 seconds), then terminate it. This is how rolling deploys stay invisible to users.

06Session affinity

Sticky sessions

Sticky sessions send a user's repeated requests to the same server. Useful sometimes, but they tie users to individual machines.

User ASession cookie or affinity key
Load balancerMaps User A → Server 2
Server 1
Server 2User A always lands here
Server 3

Why teams use it

  • Keeps in-memory sessions working
  • Better local cache hit rates
  • Supports legacy apps that aren't stateless

Why it hurts at scale

  • Load becomes uneven
  • A crashed server loses its users' sessions
  • Deploys and autoscaling get harder
07Related concept

Load balancer vs reverse proxy

A reverse proxy stands in for your servers. Load balancing is one of the things it can do, but not the only one.

Load balancer

Defined by its job.

  • Spreads traffic across many eligible backends
  • Health checks and a routing algorithm
  • Often also does TLS and observability

Reverse proxy

Defined by where it sits.

  • Terminates client connections and forwards them
  • Hides the backend topology
  • TLS, compression, caching, redirects, header rewrites, and load balancing
ClientKnows only the public endpoint
Reverse proxy / L7 balancerTLS + routing + balancing + policy
Service A
Service B
Service C
08Security

TLS termination and re-encryption

An L7 balancer can decrypt HTTPS, read the request to route it, and optionally encrypt again on the way to the backend.

ClientHTTPS
L7 load balancerHolds the certificate, terminates TLS
Backend servicePrivate network

Why terminate at the balancer

One place to manage certificates, and the balancer can read paths and headers to route. Backends don't each need certificate configuration.

Why re-encrypt to the backend

Some security and compliance models (PCI DSS, zero-trust networks) require encryption inside the private network too. The balancer opens a second TLS connection.

09No single point of failure

Making the load balancer highly available

If every request goes through one balancer process, you've just moved the single point of failure. The balancing tier must be redundant too.

Stable front endDNS name, anycast IP or virtual IP
Load balancer AZone A
Load balancer BZone B
App 1
App 2
App N

Active-passive

One serves; a standby waits.

  • Simple to reason about
  • Standby capacity sits idle
  • Failover time matters (heartbeats, VIP move)

Active-active

All instances serve at once.

  • Uses all capacity
  • Losing one costs only its share
  • Config and any shared state must stay in sync
10Scale

Handling millions of requests

At high scale, load balancing is one layer of several. You remove unnecessary traffic first, then spread what's left across regions, services and servers.

Traffic, from the edge inwards
Millions of usersWeb, mobile, API
CDN / edge cacheStatic and cacheable content near users
WAF + rate limitingBlock abuse, protect the origin
Global traffic managerPick a healthy region
Regional LB AZone-aware pool
Regional LB BZone-aware pool
App 1
App 2
App N

CDN

Serve static and cacheable responses before they reach your servers.

Autoscaling

Add stateless servers when sustained demand rises.

Caching

Skip repeated database and service work for popular reads.

Rate limiting

Stop abusive or accidental overload.

Queueing

Move non-urgent work off the request path.

Database scaling

Scale reads, partition data, protect the write path.

11Multi-region

Global load balancing

First a global layer picks a region, then that region's balancer picks a server.

Users worldwideIndia, Europe, US…
Global traffic managerLatency + geography + health + policy
India regionRegional LB + servers
Europe regionRegional LB + servers
US regionRegional LB + servers

Routing signals

Proximity, measured latency, region health, data-residency rules, capacity, cost and business policy.

The hard part is data

Sending users to another region is easy. Keeping their data correct there is not: replication lag, write ownership and conflicts dominate multi-region design.

12Long-lived connections

Load balancing WebSockets

A WebSocket stays open for minutes or hours, so balancing is about connections, not individual requests.

ClientHTTP Upgrade: websocket
WebSocket-aware balancerPicks a server when the connection opens
Real-time serverThe connection stays attached here

Count connections, not requests

A server holding 50,000 sockets is busy even if it receives few new requests. Prefer least connections or capacity-aware routing over round robin.

Messages across servers

If User A is on server 1 and User B on server 4, server 1 needs a pub/sub layer (Redis, Kafka, NATS) to reach User B.

13Complete example

Ticket booking: where load balancing fits

A BookMyShow-style platform has two very different traffic patterns: huge read spikes for browsing, and correctness-critical writes when people grab seats.

Tickets for a blockbuster open at 10:00 AM. Hundreds of thousands of people refresh the same movie and showtime pages within seconds. Most of that traffic is reads: posters, theatre lists, timings, seat maps. A small fraction reaches the booking path, where many people want the same seat in the same second.

Read spike

Discovery pages get enormous fan-out. CDN, caching and read replicas protect the origin.

Booking contention

Many users select the same seat. Correctness needs an atomic, expiring lock.

Payment uncertainty

Payment can succeed, fail, time out or arrive late, so booking must be idempotent and recoverable.

High-level traffic architecture

UsersSearch, browse, seat map, booking
CDN / edgeStatic assets, cacheable public pages
WAF + rate limiterProtect high-demand endpoints
L7 load balancerHealth-aware routing by path
SearchMovies, theatres
ShowTimings, seat map
BookingLocks, reservations
PaymentOrchestration
RedisHot reads, short-lived locks
Booking DBSource of truth for seats
QueueNotifications, async work

Seat booking, step by step

  1. User opens a show

    The L7 balancer routes to any healthy Show service; show metadata comes from cache.

  2. Seat map loads

    Seats are available, locked or sold, read from cache with the database behind it.

  3. User picks seat A10

    The request can reach any Booking instance, so the lock can't live in one server's memory.

  4. Acquire an atomic, expiring lock

    AVAILABLE → LOCKED for this booking, with a short TTL. Only one competing request wins.

  5. Create a PENDING booking

    Persist the booking and the locked seats, with an idempotency key so retries don't duplicate it.

  6. Start payment

    The seat stays locked for the booking window only, never forever.

  7. Payment succeeds → confirm

    Seats become BOOKED and the booking CONFIRMED, guarded by a conditional update or unique constraint.

  8. Failure or timeout → release

    The seat returns to AVAILABLE. Late callbacks are reconciled: confirm if still free, otherwise refund.

  9. Publish events

    Emails, SMS, invoices and analytics run from a queue, off the booking path.

Two users, one seat

User Awants A10
User Bwants A10 too
Load balancerMay send them to different booking servers
Booking 1handles A
Booking 2handles B
Shared seat-lock storeA10 can be locked by only one booking
User ALock acquired → payment
User BRejected → pick another seat

Surviving a huge ticket drop

Edge absorbs public content

Posters, JS and CSS never touch booking capacity.

Reads scale independently

Search and Show run many stateless replicas with caches and read replicas.

Admission control protects writes

Above safe booking capacity, a waiting room or queue beats letting everyone hammer the database.

Booking stays correctness-first

Locks, idempotency and database constraints stay authoritative at any scale.

Payment callbacks are idempotent

Duplicate callbacks or retries never confirm twice or charge twice.

Async work is separate

Email, SMS and analytics don't slow the seat confirmation.

Seat states
AVAILABLE
LOCKEDuserId, bookingId, expiresAt
BOOKEDafter verified payment

Lock expires or payment fails: LOCKED → AVAILABLE.

14Production reliability

Failure handling

A load-balancing design isn't complete until you explain what happens when things go wrong.

FailureWhat should happen
A backend crashesHealth checks remove it from rotation. Requests that were in flight may fail and need safe retries at the right layer.
A backend is slow but aliveA shallow /health still returns 200. Use passive signals (latency, timeouts, queue depth) to drain it or send it less traffic.
A load balancer instance failsOthers across zones keep serving, behind a stable VIP, anycast or DNS entry point.
A sudden traffic spikeCDN and caches absorb reads; autoscale stateless services; rate-limit and queue the rest.
A retry stormBounded retries, exponential backoff with jitter, deadlines and retry budgets. Never blindly retry non-idempotent writes.
A deploy drops connectionsDrain first: no new requests, let in-flight work finish, terminate after a deadline.

Timeouts and safe retries

ClientRequest with a deadline
Load balancerConnect and request timeouts
Slow backendTimes out without crashing
Bounded retryBackoff + jitter, idempotent requests only
Exponential backoff with full jitterjs
async function withRetry(fn, { tries = 3, base = 100, cap = 2000 } = {}) {
  for (let attempt = 0; ; attempt++) {
    try {
      return await fn();
    } catch (err) {
      if (attempt + 1 >= tries || !err.retryable) throw err;
      const max = Math.min(cap, base * 2 ** attempt);   // 100, 200, 400 … ms
      const wait = Math.random() * max;                 // full jitter spreads clients out
      await new Promise((r) => setTimeout(r, wait));
    }
  }
}

Metrics to watch

  • Requests / sec
  • p50 / p95 / p99 latency
  • 5xx rate
  • 4xx rate
  • Active connections
  • New connections / sec
  • Healthy hosts
  • Unhealthy hosts
  • Backend queue depth
  • Connection errors
  • Timeout rate
  • TLS errors
Interview prep

Load balancing interview questions, with answers

Say your answer out loud first, then open the card to compare. These are the questions interviewers actually ask.

1

What is a load balancer and why do we need one?

It distributes incoming requests or connections across a pool of servers. One server has finite CPU, memory and connections and is a single point of failure; a load balancer lets you run many identical servers, route around failed ones and add or remove capacity without clients noticing.

2

What are the different types of load balancers?

Classify them on four independent axes: by protocol layer (L4 or L7), by deployment (hardware appliance, software like NGINX/HAProxy/Envoy, or a managed cloud service), by traffic scope (external, internal, global) and by who makes the decision (a central proxy, or client-side load balancing in the caller's library).

3

What is the difference between L4 and L7 load balancing?

L4 works with connection metadata (IP addresses, TCP/UDP ports) and forwards connections without understanding HTTP, so it is fast and protocol-agnostic. L7 terminates HTTP, reads the host, path, headers and cookies, and can route /orders and /payments to different services, terminate TLS, rewrite headers and do canary releases.

4

When would you choose L4 over L7?

For non-HTTP traffic such as databases, game servers, MQTT or raw TCP/UDP; when you need maximum throughput with minimal processing; or when you want end-to-end TLS to the backend without the balancer decrypting it.

5

Round robin vs least connections?

Round robin sends requests to servers in turn and ignores load, which is fine when servers and requests are uniform. Least connections sends the next request to the server with the fewest active connections, which handles uneven request durations and long-lived connections much better.

6

What is weighted round robin used for?

Giving bigger machines proportionally more traffic, or shifting traffic gradually during a migration or canary: for example 95% to the old version and 5% to the new one.

7

What is the power of two choices?

Pick two healthy servers at random and send the request to the less loaded one. It gets close to the balance of checking every server, at a fraction of the cost, and avoids the herd effect where every balancer picks the same 'least loaded' server at once.

8

IP hash vs consistent hashing?

IP hash maps hash(client IP) mod N to a server; when N changes almost every client moves. Consistent hashing places servers and keys on a ring, so adding or removing a server only remaps the keys next to it. Use it where routing stability matters, such as cache shards.

9

What are active and passive health checks?

Active checks probe each backend on a schedule (a TCP connect or GET /health/ready) and remove it after N failures. Passive checks watch real traffic for timeouts, resets and 5xx errors. Use both: a server can pass a shallow probe while failing real requests.

10

Liveness vs readiness?

Liveness asks whether the process is alive or should be restarted. Readiness asks whether it should receive traffic right now. A server warming caches or unable to reach its database is alive but not ready, and the balancer should route on readiness.

11

What is connection draining?

Before removing a server for a deploy or scale-down, the balancer stops sending it new requests but lets in-flight requests and open connections finish, up to a deadline, before the instance is terminated. It prevents dropped requests during rolling deploys.

12

What are sticky sessions and why can they be harmful?

Sticky sessions pin a user to one server, usually through a cookie, so in-memory session data keeps working. They cause uneven load, lose sessions when that server dies and complicate deploys and autoscaling. The better design is stateless servers with session state in Redis or a signed token.

13

Load balancer vs reverse proxy?

A reverse proxy stands in front of servers and forwards requests to them, hiding the backend; it can do TLS, caching, compression and header rewriting. Load balancing is one thing a reverse proxy can do. NGINX, HAProxy and Envoy do both, which is why the terms are often used together.

14

What is TLS termination, and when do you re-encrypt?

The balancer holds the certificate, decrypts HTTPS and can then read the HTTP request to route it. It centralises certificate management. If security or compliance requires encryption inside the network, it opens a new TLS connection to the backend (re-encryption).

15

How do you stop the load balancer from becoming a single point of failure?

Run several balancer instances across availability zones, active-active or active-passive, behind a stable entry point such as a virtual IP, anycast address or DNS name. Managed cloud load balancers do this for you, but you still design for zone and region failure.

16

Active-active vs active-passive?

In active-active every balancer serves traffic, so you use all capacity and lose only a share when one fails. In active-passive a standby waits to take over, which is simpler but wastes capacity and adds failover time.

17

How would you handle millions of requests per second?

Reduce traffic before it reaches the balancer (CDN, caching), filter abuse (WAF, rate limits), pick a region with global load balancing, spread requests across zone-aware regional balancers and autoscaled stateless services, queue non-urgent work and protect the database with caches, replicas and sharding.

18

How does global load balancing work, and why is DNS failover slow?

A global layer (GeoDNS, anycast or a global proxy) picks a region by latency, geography, health and policy; then the regional balancer picks a server. DNS answers are cached by resolvers and clients until their TTL expires, and sometimes longer, so DNS-based failover can take minutes.

19

How do you load balance WebSockets?

The balancer picks a backend when the connection upgrades, and the connection then stays there for minutes or hours. Use least connections or capacity-aware routing rather than round robin, a pub/sub layer so servers can reach users connected elsewhere, and graceful draining with client reconnects for deploys.

20

How do retries cause a retry storm, and how do you prevent it?

When a backend slows down, every client retries, multiplying the load on an already struggling system. Prevent it with bounded retries, exponential backoff with jitter, request deadlines, retry budgets, and never blindly retrying non-idempotent writes.

21

Why doesn't load balancing solve double booking?

Two users can be routed to two different booking servers and compete for the same seat; stickiness can't prevent that. Correctness must live in shared, authoritative state: an atomic seat lock plus a conditional update or unique constraint in the database.

22

What happens if payment succeeds after the seat-lock timeout?

The seat may already be released or sold. The payment callback must be idempotent and run a reconciliation: confirm the booking if the seat is still free, otherwise refund automatically or offer an alternative. The flow should never leave a user charged with no seat.

Check yourself

Quick quiz

6 questions. Pick an answer to see why it's right or wrong.

Question 1 of 60 / 6

You need to route /payments and /orders on the same domain to different services. Which balancer do you need?

Reference

Load balancing glossary

The terms from this guide, in one line each.

Backend pool
The set of servers a load balancer can send traffic to. Also called a target group or upstream.
Layer 4 (L4)
Transport-layer balancing by IP address and TCP/UDP port.
Layer 7 (L7)
Application-layer balancing that reads HTTP host, path, headers and cookies.
Health check
A probe or signal that decides whether a backend may receive traffic.
Readiness
Whether an instance should receive traffic right now, as opposed to just being alive.
Connection draining
Letting in-flight requests finish before removing a server.
Sticky session
Routing a user to the same backend every time. Also: session affinity.
TLS termination
Decrypting HTTPS at the balancer so it can read and route the request.
Anycast
One IP address announced from many locations; the network routes users to the nearest one.
Retry storm
A surge of retries that overloads an already struggling service.
Summary

Key takeaways

  1. A load balancer turns many servers into one stable endpoint. It enables horizontal scaling, failover and zero-downtime deploys.
  2. L4 routes connections by IP and port; L7 reads HTTP and routes by host, path, header or cookie.
  3. Pick the algorithm from the workload: round robin for uniform requests, least connections for uneven ones, consistent hashing when routing must stay stable.
  4. Route on readiness, combine active and passive health checks, and drain connections before removing a server.
  5. Keep servers stateless; put session state in Redis or a token instead of relying on sticky sessions.
  6. The balancer must not be a single point of failure: run it across zones, and use global load balancing across regions.
  7. Load balancing spreads load; it doesn't create capacity or correctness. Caches, queues, rate limits and database design do the rest.
Questions

Load balancing: frequently asked questions

What is a load balancer in simple words?

A load balancer is a traffic manager in front of a group of servers. Each incoming request goes to one healthy server, chosen by a rule such as 'next in line' or 'least busy', so no single server is overloaded and a failed server is skipped automatically.

What is the difference between L4 and L7 load balancers?

A Layer 4 balancer routes by IP address and port without reading the request, which is fast and works for any TCP or UDP protocol. A Layer 7 balancer understands HTTP and can route by URL path, host, header or cookie, terminate TLS and support canary releases.

Which load balancing algorithm is best?

There is no single best one. Round robin suits identical servers and similar requests; least connections suits uneven or long-lived requests; weighted variants handle mixed capacity; consistent hashing suits caches and partitioned data where the same key should reach the same server.

Is a load balancer a single point of failure?

It can be if you run only one. Production setups run several balancer instances across availability zones, active-active or active-passive, behind a virtual IP, anycast address or DNS name. Managed cloud load balancers are built this way.

Are NGINX and HAProxy load balancers?

Yes. NGINX, HAProxy and Envoy are software reverse proxies that also load balance at Layer 4 and Layer 7. Cloud providers offer managed equivalents, such as application and network load balancers.

Do I need a load balancer for a small app?

Not for a single server. You need one as soon as you run two or more instances, want zero-downtime deploys, or need to survive one server failing, which is usually when an app first goes to production with real users.

Next topicAPI Gateway

One front door for routing, authentication, throttling, aggregation and BFFs across your microservices.

Go deeperLearn complete system design, not isolated definitions

Go from requirements to APIs, services, databases, caching, load balancing, queues, concurrency and failures in complete interview-style systems.

  • Load balancing
  • Caching
  • Databases
  • Queues
  • BookMyShow
  • Uber
Explore the book

Last reviewed 18 November 2026