HLDSystem DesignDetailed Guide

Load Balancing in System Design

Learn load balancing from first principles: why it is needed, every major type of load balancer, L4 vs L7, routing algorithms, health checks, sticky sessions, reverse proxies, TLS, high availability, multi-region traffic, WebSockets, failure handling and a complete BookMyShow-style booking case study.

Fundamentals

What Is a Load Balancer?

A load balancer is a traffic-distribution layer placed between clients and a pool of backend servers. Its job is to decide which healthy backend should receive each new request or connection.

Clients

Web, mobile, API consumers

Incoming traffic

Load Balancer

Health check + routing decision

Select healthy backend

App Server A

Healthy

App Server B

Healthy

App Server C

Healthy

Why one server is not enough

A single application server has finite CPU, memory, network bandwidth and connection capacity. Even if vertical scaling gives it more resources, it still remains one failure domain.

Horizontal scaling solves this by running multiple application instances. The load balancer makes horizontal scaling useful by spreading traffic across those instances.

What the load balancer actually knows

Depending on the type, it may know backend health, connection count, response latency, request host/path, cookies, headers, server weights and other routing signals.

It should not send new traffic to a server that has been marked unhealthy, and it should support draining when a server is being removed or deployed.

Core interview idea

Load balancing is not only about performance. It also improves availability, enables horizontal scaling, supports rolling deployments, isolates failures and creates a stable frontend while backend instances are added or removed.

Request Lifecycle

1

Client sends request

The user calls a stable domain or IP.

2

Frontend receives it

DNS/CDN/WAF may sit before the load balancer.

3

LB checks routing state

Only eligible healthy targets are considered.

4

Algorithm selects target

For example Round Robin or Least Connections.

5

Backend responds

Response returns through the proxy or directly depending on architecture.

Classification

Types of Load Balancers

The phrase 'type of load balancer' can mean different things. In interviews, classify them by network layer, deployment model, traffic scope and who owns the routing decision.

How to answer this in an interview

First say that L4 vs L7 is a protocol-layer classification. Then mention deployment types such as hardware, software and managed cloud; traffic scope such as external and internal; and routing ownership such as client-side and server-side. This avoids mixing completely different categories.
Network / Transport

Layer 4 Load Balancer

Routes traffic mainly using IP addresses, TCP/UDP ports and connection information without needing to understand HTTP business semantics.

How it works

The balancer accepts a network connection and forwards packets or connections to one of the healthy backends. Because it does not need to inspect application-level fields such as URL paths, routing can be fast and protocol-agnostic.

Common use

TCP services, UDP services, databases, game servers, high-throughput network traffic and situations where application-aware routing is unnecessary.

Trade-off

It cannot normally make rich decisions such as /payments → payment-service or route by HTTP header, cookie or user plan.

Application

Layer 7 Load Balancer

Understands application protocols such as HTTP/HTTPS and can route using host, URL path, headers, cookies, methods or other request attributes.

How it works

The balancer typically terminates the client HTTP/TLS connection, reads the request and applies application-aware routing rules before opening or reusing a connection to the selected backend.

Common use

Microservices, REST APIs, web applications, path-based routing, canary releases, authentication-aware gateways and TLS termination.

Trade-off

More processing and more configuration than simple transport-level routing. It also becomes part of the application request path, so capacity and failure handling matter.

Deployment

Hardware Load Balancer

A dedicated physical appliance designed to distribute traffic using specialized hardware and vendor software.

How it works

Traffic is sent through a dedicated appliance installed in a data center. The device may provide L4/L7 balancing, TLS offload, health checks, security controls and advanced traffic policies.

Common use

Traditional enterprise data centers, regulated environments and organizations already invested in dedicated networking appliances.

Trade-off

Higher cost, procurement time, hardware capacity limits and operational overhead compared with software or managed cloud solutions.

Deployment

Software Load Balancer

Load-balancing software runs on normal virtual machines, containers or bare-metal servers.

How it works

Software such as NGINX, HAProxy or Envoy receives traffic and forwards it to configured or dynamically discovered upstream services.

Common use

Self-managed infrastructure, Kubernetes ingress, service proxies, private clouds and environments requiring fine-grained control.

Trade-off

Your team owns deployment, upgrades, scaling, security, observability and high availability unless another platform manages these concerns.

Deployment

Managed Cloud Load Balancer

A cloud provider operates the load-balancing control plane and much of the data-plane lifecycle for you.

How it works

You configure listeners, target pools, routing rules, certificates and health checks while the provider handles infrastructure provisioning and scaling within product limits.

Common use

Cloud-native applications that need simpler operations, integrated autoscaling, TLS certificates, logging and regional or global routing.

Trade-off

Provider-specific behavior, quotas, pricing and reduced low-level control. Architecture still needs multi-zone design and healthy backends.

Traffic Scope

External / Public Load Balancer

Receives traffic from the public internet and routes it to application entry points.

How it works

A public IP or globally advertised endpoint accepts requests, applies security and routing policies, then forwards traffic to private application instances.

Common use

Public websites, mobile APIs, SaaS applications and public REST/GraphQL APIs.

Trade-off

Must be protected with TLS, DDoS controls, WAF/rate limiting where appropriate and strict backend network rules.

Traffic Scope

Internal / Private Load Balancer

Balances traffic only inside a private network, VPC or internal service environment.

How it works

Internal clients resolve or connect to a private endpoint that distributes requests across private backend instances.

Common use

Service-to-service traffic, internal admin systems, private APIs, database proxies and multi-tier architectures.

Trade-off

It is not directly reachable from the public internet, but internal authentication, authorization and network segmentation are still required.

Routing Ownership

Client-Side Load Balancing

The client or client library chooses a backend instance instead of sending every request through a central proxy.

How it works

The client receives a list of healthy service instances from service discovery and selects one using an algorithm such as round robin or random.

Common use

Some service-mesh and RPC architectures where clients can safely perform service discovery and routing.

Trade-off

Every client needs routing logic, discovery integration, retries and health awareness. Versioning that logic across many clients can be difficult.

Routing Ownership

Server-Side / Proxy Load Balancing

Clients send requests to a load-balancing proxy, and the proxy selects the backend.

How it works

The client knows only the stable load-balancer endpoint. The balancer maintains or discovers the backend pool and performs routing centrally.

Common use

Most public web applications, APIs, ingress layers and architectures where clients should not know backend topology.

Trade-off

The proxy layer must be highly available and sufficiently provisioned because it sits directly in the request path.

Global Routing

DNS / Global Load Balancing

Distributes users across regions or endpoints using DNS responses, Anycast, global proxies or traffic-management policies.

How it works

A global routing layer considers region health, geography, latency, policy or capacity and directs the user toward an appropriate regional entry point.

Common use

Multi-region applications, disaster recovery, latency reduction and global active-active deployments.

Trade-off

DNS caching and TTL can delay failover. Global traffic policy must also consider data locality, session state and database consistency.

Type Classification Diagram

Load Balancer

Classify it using multiple independent dimensions

Protocol Layer

L4 / L7

Deployment

Hardware / Software / Managed

Traffic Scope

External / Internal / Global

Routing Ownership

Client-side / Server-side

Core Interview Topic

Layer 4 vs Layer 7 Load Balancing

L4 and L7 solve the same high-level problem—selecting a backend—but they operate with different information and therefore support different routing capabilities.

Transport Layer

Layer 4 Load Balancer

L4 routing works primarily with connection metadata such as source/destination IP, TCP/UDP port and protocol. It does not need to understand the meaning of an HTTP URL.

It is useful when the service is not HTTP, when very high transport throughput is required, or when application-aware routing is unnecessary.

Example: traffic arriving on TCP port 5432 can be distributed to a pool of PostgreSQL proxies without parsing HTTP because there is no HTTP request to parse.

Application Layer

Layer 7 Load Balancer

L7 understands application protocols such as HTTP. It can read hostnames, paths, methods, headers and cookies and then route requests based on application meaning.

It is commonly used in microservice architectures because a single domain can route /users, /orders and /payments to different backend pools.

L7 can also perform TLS termination, redirects, header manipulation, authentication integration, canary routing and other application-layer features.

AreaLayer 4Layer 7
Primary informationIP, port, TCP/UDP connectionHost, path, header, cookie, HTTP method
HTTP awarenessNoYes
Path routingNoYes
TLS terminationNot an application-level featureCommonly supported
Protocol flexibilityExcellent for raw TCP/UDPBest when application protocol is understood
ProcessingLess application parsingMore request inspection
Typical exampleTCP service or network load balancerWeb/API ingress or application load balancer

L4 Routing Diagram

Client

TCP connection

L4 Load Balancer

Connection-level decision

Backend

Selected healthy target

L7 Path-Based Routing Diagram

api.example.com

HTTPS requests

Inspect HTTP request

L7 Load Balancer

Host / path / header rules

/users

User Service

/orders

Order Service

/payments

Payment Service

Routing Strategy

Load Balancing Algorithms

After deciding which backends are healthy and eligible, the load balancer still needs an algorithm to choose the next target. Static algorithms use little live state; dynamic algorithms react to runtime load.

1

Round Robin

Static

S1 → S2 → S3 → S1 → ...

Requests are assigned to healthy servers sequentially. Each server gets a turn, making the algorithm simple and predictable.

Best for

Backends with roughly equal capacity and requests with similar processing cost.

Trade-off

It does not know whether one server is already busy, slow or handling expensive requests.

2

Weighted Round Robin

Static / Weighted

S1 weight 5, S2 weight 3, S3 weight 2

Each backend receives traffic in proportion to a configured weight. A stronger machine can receive more requests than a smaller machine.

Best for

Mixed-capacity servers or gradual traffic shifting between old and new deployments.

Trade-off

Static weights may not reflect real-time CPU, memory, latency or queue depth.

3

Least Connections

Dynamic

Choose backend with minimum active connections

The next request goes to the healthy server currently handling the fewest active connections.

Best for

Long-lived or uneven requests where active connection count is a useful approximation of load.

Trade-off

One connection can be much more expensive than another, so connection count is not a perfect measure of actual resource usage.

4

Weighted Least Connections

Dynamic / Weighted

Connections are normalized by server capacity

Combines live connection counts with backend capacity. A powerful server is allowed to hold more concurrent connections.

Best for

Heterogeneous fleets where request duration varies and server capacity is not equal.

Trade-off

Requires reasonable capacity weights and accurate connection accounting.

5

Least Response Time

Dynamic

Prefer low latency + low active load

The balancer uses observed response time, often together with connection count, to prefer backends that are responding quickly.

Best for

Systems where backend latency varies meaningfully during runtime.

Trade-off

Needs continuous measurements. Poor sampling or temporary latency spikes can cause traffic oscillation.

6

Random

Static / Probabilistic

Pick one random healthy backend

A healthy backend is selected randomly. Across a large number of requests and sufficiently uniform servers, traffic tends to spread out.

Best for

Simple large pools where a small amount of short-term imbalance is acceptable.

Trade-off

Individual decisions do not consider live server load.

7

Power of Two Choices

Dynamic / Probabilistic

Pick 2 random servers → choose the less loaded

The balancer samples two healthy backends and selects the less loaded one. This offers much better balance than pure random while avoiding a full scan of every backend.

Best for

Large backend pools where checking every server on every request would be expensive.

Trade-off

Needs a meaningful load metric and is more complex than basic random routing.

8

IP Hash

Hash Based

hash(clientIP) % N

A hash of the client IP determines the backend. The same IP tends to map to the same server while the backend set remains stable.

Best for

Simple client affinity where approximate stickiness is enough.

Trade-off

Many users can share one NAT IP, client IPs can change, and adding/removing servers can remap many clients.

9

URL / Key Hash

Hash Based

hash(path or resourceKey) → backend

Routing uses a stable request attribute such as URL, tenant ID, user ID or resource key rather than only the client address.

Best for

Cache locality, tenant affinity or workloads where related requests should reach the same shard or worker.

Trade-off

Bad key distribution can create hot spots and the routing key must be available before backend selection.

10

Consistent Hashing

Hash Based

hash(key) → position on hash ring

Both servers and routing keys are mapped to a logical hash ring. When a server is added or removed, only a portion of keys are remapped instead of nearly every key.

Best for

Distributed caches, partition-aware routing and systems where routing stability matters as the backend pool changes.

Trade-off

More complex than modulo hashing and usually needs virtual nodes or good weighting for balanced distribution.

11

Resource / Adaptive Routing

Dynamic

CPU + memory + queue + latency + errors

Routing decisions use one or more runtime signals such as CPU, memory, queue depth, outstanding requests, error rate or custom load scores.

Best for

Specialized workloads where simple connection count is a poor proxy for backend capacity.

Trade-off

Telemetry is delayed and noisy. A badly designed feedback loop can cause traffic to bounce between servers.

Round Robin Example

Request 1

Request 2

Request 3

Round Robin

Cycle through healthy servers

Server A

Request 1

Server B

Request 2

Server C

Request 3

Algorithm choice does not replace capacity planning

A perfect routing algorithm cannot save a system whose total backend capacity is smaller than incoming demand. Load balancing, autoscaling, caching, queueing, rate limiting and database scaling solve different parts of the overall capacity problem.

Reliability

Health Checks and Backend Eligibility

The balancer must know which targets can safely receive traffic. Health checking is therefore part of routing correctness, not only monitoring.

Active Health Checks

The balancer periodically probes a backend endpoint or opens a connection. After a configured number of failed checks, the backend is removed from rotation.

A recovery threshold is normally used before returning the instance to service so one intermittent success does not cause flapping.

Example health endpoint
GET /health/ready

200 OK
{
  "status": "UP",
  "ready": true
}

Passive Health Signals

The balancer can observe real production traffic: timeouts, connection resets, excessive 5xx responses or unusually high latency.

Passive checks are valuable because a process can answer a synthetic health endpoint while real user requests are failing.

Health State Diagram

Load Balancer

Maintains healthy target pool

Health probes

Server A

Healthy ✓ receives traffic

Server B

Unhealthy ✕ removed

Server C

Healthy ✓ receives traffic

Liveness is not the same as readiness

A process may be alive but not ready to serve traffic. During startup it may still be loading configuration or warming caches. During failure it may be unable to reach critical dependencies. Use readiness semantics to decide whether new traffic should be routed to the instance.

Connection Draining

During a deployment or scale-down, immediately killing an instance can terminate user requests. Instead, mark the target as draining: stop new routing, keep existing requests or connections for a configured grace period, then remove the server after in-flight work completes or a deadline is reached.

Session Affinity

Sticky Sessions

Sticky sessions route repeated requests from the same user or session to the same backend. They can be useful, but they also couple users to individual instances.

User A

Session cookie or affinity key

Affinity key

Load Balancer

Maps User A → Server 2

Server 1

Server 2

User A keeps returning here

Server 3

Why teams use it

It can preserve in-memory session state, improve cache locality or support a legacy service that was not designed to be fully stateless.

Why it can hurt scaling

Traffic can become uneven, a failed server can lose local session state, and deployments become harder because users are coupled to specific instances.

Preferred scalable design

Keep application instances stateless where practical. Store shared session state in an appropriate distributed store such as Redis or use signed/token-based session mechanisms when the security model allows it. Then any healthy backend can serve the next request.

Related Concept

Load Balancer vs Reverse Proxy

A reverse proxy represents one or more backend servers to clients. Load balancing is one capability a reverse proxy can provide, but reverse proxies can do much more.

Load Balancer

The primary concern is distributing traffic across multiple eligible backend instances while considering health and a routing algorithm.

The same product may also perform TLS termination, routing and observability, but traffic distribution is the defining role.

Reverse Proxy

A reverse proxy terminates the client-facing connection and forwards requests to backend services. It hides backend topology and can centralize cross-cutting behavior.

Common features include TLS, compression, caching, redirects, authentication integration, request/response header changes and load balancing.

Client

Knows only public endpoint

Reverse Proxy / L7 Load Balancer

TLS + routing + balancing + policy

Service A

Service B

Service C

Examples

Products such as NGINX, HAProxy and Envoy can perform reverse-proxy and load-balancing responsibilities. Cloud application load balancers and ingress controllers also combine several of these concepts.

Security

TLS Termination and Re-encryption

An application-aware load balancer can terminate HTTPS, inspect the HTTP request and optionally create a new encrypted connection to the backend.

Client

HTTPS

Encrypted connection

L7 Load Balancer

Certificate + TLS termination

HTTP or new HTTPS connection

Backend Service

Private application network

Why terminate TLS at the balancer?

It centralizes certificate management and allows the L7 proxy to inspect HTTP routing information. It can also reduce repeated certificate configuration across every backend.

Why re-encrypt to the backend?

Some security and compliance models require encryption even inside the private network. In that case the load balancer creates another TLS connection to the selected backend.

Avoid Single Point of Failure

High Availability of the Load-Balancing Layer

If every request depends on one load-balancer process, that process becomes a new single point of failure. The load-balancing tier itself must therefore be redundant.

Stable Frontend

DNS / Anycast / VIP / managed global entry

Load Balancer A

Zone A

Load Balancer B

Zone B

App 1

App 2

App N

Active-Passive

One balancer handles traffic while another is ready to take over. Failure detection triggers failover to the standby.

It is conceptually simple but standby capacity is underused and failover time matters.

Active-Active

Multiple balancers serve traffic simultaneously. Traffic is distributed among them and the remaining instances continue if one fails.

This improves both availability and usable capacity, but shared state and configuration must be handled carefully.

Managed load balancers

Cloud-managed services hide much of this infrastructure, but the system designer still needs to think about zones, backend health, quotas, regional failure and whether global failover is required.

Scale

Handling Millions of Requests

At high scale, load balancing is only one layer. The system reduces unnecessary origin traffic before distributing the remaining requests across regions, services and backend instances.

Millions of Users

Web + mobile + API traffic

CDN / Edge Cache

Serve static and cacheable content near users

WAF / Rate Limiting

Protect origin and control abusive traffic

Global Traffic Manager

Choose healthy region

Regional LB A

Zone-aware backend pool

Regional LB B

Zone-aware backend pool

App 1

App 2

App N

CDN

Remove static and cacheable traffic before it reaches application servers.

Autoscaling

Add stateless application capacity when sustained demand grows.

Caching

Avoid repeated database and service work for popular reads.

Rate Limiting

Protect the system from abusive or accidental overload.

Queueing

Move non-immediate work out of the synchronous request path.

Database Scaling

Scale reads, partition data and protect the write path independently.

Do not say 'add a load balancer' and stop

In an HLD interview, explain where traffic is reduced, where it is distributed, how backend capacity scales, how the database is protected and what happens when one layer becomes unhealthy.

Multi-Region

Global Load Balancing

Global load balancing chooses a region or edge entry point before regional load balancing chooses an individual backend.

Global Users

India, Europe, US and other regions

Global Traffic Manager

Latency + geography + health + policy

India Region

Regional LB + app fleet

Europe Region

Regional LB + app fleet

US Region

Regional LB + app fleet

Common routing signals

Geographic proximity, measured latency, region health, regulatory requirements, capacity, cost and explicit business policy can all affect region selection.

The hard part is data

Routing users to another region is much easier than keeping data correct across regions. Replication lag, write ownership, data residency and conflict handling often dominate the multi-region design.

DNS failover is not instantaneous

Recursive resolvers and clients can cache DNS answers until TTL expiry, and some software may cache longer. DNS-based failover must therefore be designed with realistic caching behavior in mind.

Long-Lived Connections

Load Balancing WebSockets

WebSocket connections remain open for a long time, so the balancing problem is different from short independent HTTP requests.

Client

HTTP upgrade request

Upgrade: websocket

WebSocket-Aware Load Balancer

Select backend when connection opens

Long-lived connection

Realtime Server

Connection remains attached

Why connection count matters

A server with many long-lived WebSockets can remain busy even when it is receiving few new HTTP requests. Least Connections or capacity-aware routing is often more meaningful than plain Round Robin.

Broadcast and cross-server messaging

If User A is connected to Server 1 and User B to Server 4, realtime events may need a shared pub/sub or messaging layer so one application server can reach users connected elsewhere.

Deployment behavior

During deployments, connection draining is especially important because WebSockets can remain open for minutes or hours. You need a maximum connection age, graceful shutdown strategy or client reconnect behavior.

Complete HLD Example

BookMyShow-Style Booking System: Where Load Balancing Fits

A ticket-booking platform has two very different traffic patterns: extremely heavy read traffic for discovery and seat maps, and correctness-sensitive write traffic when users lock and purchase seats.

Important note

This section is an interview design model for a BookMyShow-style system. It explains how you can design the problem; it is not a claim about BookMyShow's private production architecture.

What happens during a blockbuster ticket release?

Imagine tickets for a highly anticipated movie open at 10:00 AM. Thousands or millions of users may refresh the same city, movie and showtime pages within seconds. Most of those requests are reads: movie metadata, theatre list, show timings and seat maps. A smaller percentage reaches the critical booking path, where the same seat can be requested by many users at nearly the same time.

Read Spike

Discovery endpoints receive huge fan-out. CDN, application caching and read replicas can reduce origin/database load.

Booking Contention

Multiple users can select the same seat. Correctness requires atomic locking or reservation logic with expiration.

Payment Uncertainty

Payment can succeed, fail, time out or return late. The booking workflow must be idempotent and recoverable.

High-Level Traffic Architecture

Users

Search, browse, seat map, booking

CDN / Edge

Static assets + cacheable public content

WAF + Rate Limiter

Protect high-demand endpoints

L7 Load Balancer / API Entry

Health-aware routing by path/service

Search Service

Movies + theatres

Show Service

Timings + seat map

Booking Service

Locks + reservation state

Payment Service

Payment orchestration

Cache / Redis

Hot reads + short-lived locks

Booking Database

Authoritative seat + booking state

Event / Queue Layer

Notifications + async processing

What the load balancer solves here

The load balancer spreads requests across healthy instances of Search, Show, Booking and Payment services. It allows those services to scale horizontally and survive individual server failures. It does not decide who owns a seat. Double-booking prevention belongs to the booking/inventory consistency design.

Step-by-Step Seat Booking Flow

1

User opens a show

The request reaches the L7 load balancer and is routed to a healthy Show Service instance. Frequently requested show metadata can be served from cache.

2

Seat map is loaded

The service reads current seat state from an appropriate cache/database model. Available, locked and sold seats must be distinguishable.

3

User chooses Seat A10

The booking request is routed to any healthy Booking Service instance. The application should not rely on that one server keeping the lock only in local memory.

4

Booking Service acquires an atomic temporary lock

The system attempts to transition A10 from AVAILABLE to LOCKED for this user/order, normally with a short TTL. Only one competing request should succeed.

5

Create a PENDING booking

Persist a booking/order identifier and the locked seats before redirecting the user into payment. The request should carry an idempotency key so retries do not create duplicate bookings.

6

Payment starts

The payment service creates or tracks the payment attempt. The seat remains locked only for the booking window rather than forever.

7

Payment success confirms seats

On verified success, the authoritative seat state is changed to BOOKED/SOLD and the booking becomes CONFIRMED. Database uniqueness or conditional updates provide another correctness boundary.

8

Failure or timeout releases the lock

If payment fails or the reservation TTL expires, the seat returns to AVAILABLE. Late payment callbacks need reconciliation so a user is not charged for an unavailable seat without recovery handling.

9

Async events are published

Confirmation email/SMS, analytics, invoice generation and other non-critical tasks can be processed through an event or queue layer instead of blocking the booking response.

Seat Locking Diagram

User A

Requests Seat A10

User B

Requests Seat A10 at same time

Both requests reach booking tier

Load Balancer

Requests can go to different Booking Service instances

Booking Instance 1

Handles User A

Booking Instance 2

Handles User B

Shared atomic seat state

Seat Lock / Inventory Store

A10 can be locked by only one booking

User A

Lock acquired → continue to payment

User B

Lock rejected → choose another seat

Why sticky sessions do not solve double booking

Even if every request from User A goes to the same application server, User B can be routed to another server and compete for the same seat. Correctness must live in shared, authoritative state with atomic operations, constraints or transactional logic—not in the load balancer.

What Happens During a Huge Ticket Drop?

1. Edge absorbs public content

Posters, static JavaScript, CSS and other cacheable resources should not consume booking-service capacity.

2. Read endpoints scale independently

Search/show services can run many stateless replicas behind load balancers and use cache/read replicas where appropriate.

3. Admission control protects writes

If demand exceeds safe booking capacity, rate limiting, waiting rooms or queues are safer than allowing every request to hammer the database.

4. Booking path stays correctness-first

Seat locks, idempotency and database constraints remain authoritative even when thousands of application instances are serving traffic.

5. Payment callbacks are idempotent

Duplicate callbacks or client retries should not confirm the same booking twice or charge twice.

6. Async work is separated

Email, SMS and analytics should not make the synchronous seat-confirmation transaction slower.

Simplified seat-state idea
AVAILABLE
   |
   | atomic lock(userId, bookingId, expiresAt)
   v
LOCKED
   |    |   lock expires / payment fails
   |   -----------------------------> AVAILABLE
   |
   | verified payment success
   v
BOOKED

Production Reliability

Failure Handling and Operational Concerns

A production load-balancing design is incomplete unless you explain what happens when backends become unhealthy, retries increase load, deployments drain connections or the balancing layer itself fails.

Backend crashes

Health checks should mark the instance unhealthy and remove it from new routing. Existing connections may fail and need safe retry behavior at the appropriate layer.

Backend becomes slow but stays alive

A shallow /health endpoint may still return 200. Track latency, timeouts, queue depth and passive error signals so a slow instance can be drained or receive less traffic.

Load balancer instance fails

Run multiple balancer instances across failure domains. Use active-active or active-passive failover and a stable frontend such as managed anycast, VIP or DNS/global routing.

Sudden traffic spike

Use CDN and caching to absorb read traffic, autoscale stateless services, enforce admission control/rate limits and queue work that does not need synchronous execution.

Retry storm

Retries multiply traffic during an outage. Use bounded retries, exponential backoff, jitter, deadlines and retry budgets; do not blindly retry non-idempotent operations.

Deployment causes connection loss

Mark an instance as draining, stop sending new requests, allow in-flight requests or long-lived connections to finish, then terminate the instance after a safe deadline.

Important Timeout and Retry Path

Client

Request with deadline

Load Balancer

Connect + request timeout

Slow Backend

May time out without crashing

Retry only when safe

Bounded Retry + Backoff + Jitter

Avoid synchronized retry storms

Be careful retrying writes

Retrying GET-like idempotent reads is usually simpler than retrying booking, payment or order-creation requests. For writes, use idempotency keys and clearly define whether a timeout means "failed" or merely "result unknown."

Metrics to Monitor

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 Preparation

Load Balancing Interview Questions

After studying this chapter, you should be able to answer these questions with theory, trade-offs and a diagram.

1

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

2

What problems are solved by horizontal scaling plus load balancing?

3

What are the different types of load balancers?

4

Hardware vs software vs managed cloud load balancer?

5

External vs internal load balancer?

6

Client-side vs server-side load balancing?

7

What is the difference between L4 and L7 load balancing?

8

When would you choose L4 over L7?

9

Round Robin vs Weighted Round Robin?

10

Round Robin vs Least Connections?

11

What is Weighted Least Connections?

12

What is Least Response Time?

13

What is Power of Two Choices?

14

IP Hash vs consistent hashing?

15

Why is consistent hashing useful when nodes change?

16

What are active and passive health checks?

17

Liveness vs readiness?

18

What is connection draining?

19

What are sticky sessions and why can they be harmful?

20

Load balancer vs reverse proxy?

21

What is TLS termination and backend re-encryption?

22

How do you prevent the load balancer from becoming an SPOF?

23

Active-active vs active-passive load balancing?

24

How would you handle millions of requests per second?

25

Where should CDN, WAF, rate limiter and load balancer sit?

26

How does global load balancing work?

27

Why can DNS TTL delay regional failover?

28

How do you load balance WebSockets?

29

How do retries create retry storms?

30

How would a load balancer fit into BookMyShow system design?

31

Why does load balancing not solve double booking?

32

How would you lock a seat while a payment is in progress?

33

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

Quick Revision

Frequently Asked Questions

Short answers for the most important load-balancing concepts.

What is a load balancer in system design?

A load balancer is an entry layer that distributes incoming traffic across multiple healthy backend instances. It improves scalability, availability and failure isolation by preventing every request from depending on one server.

What are the main types of load balancers?

Common classifications include Layer 4 and Layer 7, hardware and software, managed cloud, external and internal, client-side and server-side, plus DNS or global traffic load balancing.

What is the difference between L4 and L7 load balancing?

L4 makes routing decisions mainly from transport-level information such as IP addresses and TCP or UDP ports. L7 understands application protocols such as HTTP and can route by host, path, header, cookie or method.

Which load balancing algorithm is best?

There is no universal best algorithm. Round Robin is simple for uniform backends, Least Connections helps with uneven request duration, weighted algorithms handle different capacities, and hashing is useful when routing affinity or cache locality matters.

How does load balancing help a BookMyShow-style booking system?

Load balancing distributes browsing, show search, seat-map and booking requests across healthy service instances. It does not itself prevent double booking; seat locking, idempotency, database constraints and transactional booking logic are needed for concurrency correctness.

Can a load balancer become a single point of failure?

Yes. Production systems use multiple load-balancer instances or managed highly available load-balancing services, often across zones and sometimes across regions.

Mastering System Design — HLD

Learn complete system design, not isolated definitions.

Move from requirements to APIs, services, databases, caching, load balancing, queues, concurrency, scalability and failure handling in complete interview-style systems.

CachingLoad BalancingDatabasesQueuesRate LimitingBookMyShowUberScalability
Explore HLD Book

Continue Learning