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.
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
The client calls a stable name
For example api.example.com. It never knows how many servers sit behind it.
The edge receives it
DNS, a CDN or a WAF may sit before the load balancer.
The balancer filters the pool
Only healthy, ready, non-draining targets are eligible.
The algorithm picks one
Round robin, least connections, a hash, and so on.
The backend responds
Back through the proxy, or straight to the client in some L4 setups.
Types of load balancers
“Type” can mean four different things. Interviewers notice when you separate them instead of listing everything in one breath.
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.
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.
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.
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.
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.
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.
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.
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.
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 4 | Layer 7 | |
|---|---|---|
| Sees | IP, port, TCP/UDP connection | Host, path, headers, cookies, method |
| HTTP-aware | No | Yes |
| Path routing | No | Yes |
| TLS termination | Usually passes TLS through | Commonly terminates it |
| Protocols | Any TCP/UDP | HTTP/1.1, HTTP/2, gRPC, WebSocket |
| Cost per request | Lower | Higher (parses every request) |
| Typical product | Network load balancer | Application load balancer, ingress |
L4: a connection-level decision
L7: path-based routing
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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
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)
GET /health/ready
HTTP/1.1 200 OK
Content-Type: application/json
{ "status": "UP", "ready": true, "db": "ok", "cache": "ok" }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.
Sticky sessions
Sticky sessions send a user's repeated requests to the same server. Useful sometimes, but they tie users to individual machines.
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
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
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.
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.
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.
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
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.
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.
Global load balancing
First a global layer picks a region, then that region's balancer picks a server.
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.
Load balancing WebSockets
A WebSocket stays open for minutes or hours, so balancing is about connections, not individual requests.
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.
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
Seat booking, step by step
User opens a show
The L7 balancer routes to any healthy Show service; show metadata comes from cache.
Seat map loads
Seats are available, locked or sold, read from cache with the database behind it.
User picks seat A10
The request can reach any Booking instance, so the lock can't live in one server's memory.
Acquire an atomic, expiring lock
AVAILABLE → LOCKED for this booking, with a short TTL. Only one competing request wins.
Create a PENDING booking
Persist the booking and the locked seats, with an idempotency key so retries don't duplicate it.
Start payment
The seat stays locked for the booking window only, never forever.
Payment succeeds → confirm
Seats become BOOKED and the booking CONFIRMED, guarded by a conditional update or unique constraint.
Failure or timeout → release
The seat returns to AVAILABLE. Late callbacks are reconciled: confirm if still free, otherwise refund.
Publish events
Emails, SMS, invoices and analytics run from a queue, off the booking path.
Two users, one 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.
Lock expires or payment fails: LOCKED → AVAILABLE.
Failure handling
A load-balancing design isn't complete until you explain what happens when things go wrong.
| Failure | What should happen |
|---|---|
| A backend crashes | Health 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 alive | A shallow /health still returns 200. Use passive signals (latency, timeouts, queue depth) to drain it or send it less traffic. |
| A load balancer instance fails | Others across zones keep serving, behind a stable VIP, anycast or DNS entry point. |
| A sudden traffic spike | CDN and caches absorb reads; autoscale stateless services; rate-limit and queue the rest. |
| A retry storm | Bounded retries, exponential backoff with jitter, deadlines and retry budgets. Never blindly retry non-idempotent writes. |
| A deploy drops connections | Drain first: no new requests, let in-flight work finish, terminate after a deadline. |
Timeouts and safe retries
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
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.
1What 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.
2What 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).
3What 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.
4When 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.
5Round 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.
6What 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.
7What 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.
8IP 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.
9What 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.
10Liveness 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.
11What 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.
12What 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.
13Load 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.
14What 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).
15How 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.
16Active-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.
17How 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.
18How 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.
19How 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.
20How 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.
21Why 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.
22What 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.
Quick quiz
6 questions. Pick an answer to see why it's right or wrong.
You need to route /payments and /orders on the same domain to different services. Which balancer do you need?
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.
Key takeaways
- A load balancer turns many servers into one stable endpoint. It enables horizontal scaling, failover and zero-downtime deploys.
- L4 routes connections by IP and port; L7 reads HTTP and routes by host, path, header or cookie.
- Pick the algorithm from the workload: round robin for uniform requests, least connections for uneven ones, consistent hashing when routing must stay stable.
- Route on readiness, combine active and passive health checks, and drain connections before removing a server.
- Keep servers stateless; put session state in Redis or a token instead of relying on sticky sessions.
- The balancer must not be a single point of failure: run it across zones, and use global load balancing across regions.
- Load balancing spreads load; it doesn't create capacity or correctness. Caches, queues, rate limits and database design do the rest.
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.
One front door for routing, authentication, throttling, aggregation and BFFs across your microservices.
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
Last reviewed 18 November 2026