ayushsalampuriya.xyz Revise

System Design · Core

Load Balancing

Spread traffic across healthy backends: L4 vs L7, algorithms, health checks, sticky sessions, and where TLS terminates.

1. What a load balancer does

A load balancer (LB) is a reverse proxy that accepts client connections and forwards them to a pool of backend instances. Goals: even utilization, hide node failures, and (at L7) route by path, host, or header.

BenefitWhy it matters
Horizontal scaleAdd/remove app instances without client changes
High availabilitySkip unhealthy nodes; survive single-instance failure
SSL offloadTerminate TLS once; simplify cert rotation
Smart routingL7 path/host rules, canaries, blue-green
ProtectionCentral place for rate limits, WAF, connection limits
Client --TLS--> LB --> healthy App instances \--> drain / remove unhealthy

2. Layer 4 vs Layer 7

L4 (transport)L7 (application)
SeesIP + port (TCP/UDP)HTTP method, path, headers, cookies
SpeedVery fast, cheapMore CPU; can inspect/transform
RoutingSame pool for all bytes/api → service A, /media → other pool
ExamplesNLB, IPVS, LVSNGINX, Envoy, ALB, HAProxy HTTP mode

Interview default: L7 at the edge for HTTP APIs; L4 when you need raw TCP (databases, some streaming, gaming sockets).

3. Algorithms

Round robin (RR)

Send request N to backend N % pool_size. Fair when backends are equal and requests cost similar CPU.

Weighted round robin

Larger machines get higher weight. Useful during canaries (send 5% to the new build).

Least connections

Prefer the backend with fewest open connections. Better for long-lived or uneven work (uploads, WebSockets, slow APIs).

IP hash / consistent hash

Hash client IP (or a key) onto a backend. Improves cache locality and can approximate stickiness without cookies. Prefer consistent hashing when the pool membership changes often.

Least response time

Prefer the backend with the lowest recent latency (sometimes combined with fewest connections). Good when backends are heterogeneous or some are temporarily slow. Needs the LB to track response-time samples; can oscillate if metrics are noisy — use a short moving average.

Random

Pick a backend uniformly at random (or weighted random). Extremely simple, no shared counter state, and statistically fair at high QPS. Worse than least-conn for long-lived uneven work; fine for short, similar-cost HTTP requests.

RR: A B C A B C A B C ... Least-conn: prefer backend with min(active_conns) Least-RT: prefer backend with min(recent_latency) IP hash: backend = pool[hash(client_ip) % N] Random: backend = pool[rand() % N] Weighted: A,A,A,B,B,C (weights 3,2,1)
AlgorithmBest whenWatch out
Round robinEqual backends, similar request costSlow node still gets equal share
Weighted RRMixed instance sizes / canariesWeights need ops discipline
Least connectionsLong-lived or uneven workNeeds accurate conn tracking
Least response timeHeterogeneous or temporarily slow nodesMetric noise / oscillation
IP / consistent hashCache locality, soft stickinessUneven clients → hot backends
RandomSimple short HTTP at high QPSIgnores load and latency

4. Health checks

TypeWhat it checksTypical use
TCPAccept connection on portFast liveness; no app semantics
HTTPGET /healthz returns 2xxApp process ready to serve
Custom / scriptApp-defined (gRPC health, deep deps)Readiness with care — avoid shared-dep flaps
KnobMeaningInterview ballpark
IntervalHow often to probe5–30s
TimeoutMax wait for a probe response2–5s
Unhealthy thresholdFails before remove from pool2–3 consecutive fails
Healthy thresholdPasses before re-add2–5 consecutive passes

Prefer shallow liveness plus a separate readiness signal. On deploy, mark the instance not-ready, drain connections, then stop.

healthy if: TCP accept OK AND /healthz returns 200 within timeout unhealthy: fail M of N probes → remove from pool recover: pass K probes → add back (slow start optional)

5. Sticky sessions (session affinity)

Route the same client to the same backend. Use only when you must (legacy in-memory sessions, pinning a WebSocket to a node). Prefer externalizing state so any node works. Stickiness hurts failover and creates hot nodes when one user is heavy.

MethodHowTrade-off
CookieLB sets cookie naming the backendWorks through NAT; cookie must be trusted/signed
IP hashHash client IP → backendBreaks behind shared NAT / mobile carrier IPs
URL paramSession id in query/path hashedLeaks in logs/referrers; awkward for APIs

6. SSL / TLS termination

Internet --HTTPS--> LB (terminate TLS, certs live here) | HTTP or mTLS inside VPC --> Apps

Offload CPU-heavy crypto to the LB fleet; rotate certs with ACME or a cloud certificate manager.

7. Placement patterns

  1. Edge LB / API gateway: public entry, auth, rate limit, routing.
  2. Internal LB: service-to-service inside the VPC.
  3. DNS LB: multiple A records; coarse, client-cached, no instant health.
  4. Global LB / anycast: steer users to the nearest region.

8. HA for load balancers

Active-PassiveActive-Active
HowPrimary serves; standby takes VIP on failMultiple LBs share traffic (ECMP / anycast / DNS)
CapacityStandby mostly idleAll nodes useful under load
FailoverSeconds; VIP/ARP moveOften smoother; need shared state care
Use whenSimple on-prem pairsCloud managed LBs, high QPS edges

Managed cloud LBs are usually active-active behind the scenes. If you run your own (HAProxy/NGINX), plan VIP failover (Keepalived/VRRP) or put them behind a cloud NLB.

9. LB technologies (interview map)

TechLayerNotes
NGINXL7 (also L4 stream)Reverse proxy, TLS, path routing; very common
HAProxyL4/L7High performance; rich health/stick tables
AWS ALBL7HTTP/HTTPS, path/host rules, target groups
AWS NLBL4Ultra-low latency TCP/UDP; static IPs
CloudflareEdge L7 + DNSGlobal anycast, WAF, CDN combo

10. Global load balancing (GSLB)

GSLB steers users to a region or PoP before the regional LB picks an instance. Mechanisms: geo-DNS, latency-based DNS, anycast IP, or a global HTTP front door.

User (IN) → geo/latency DNS → Region APAC LB → local apps User (US) → geo/latency DNS → Region US LB → local apps Failover: health of region VIP → remove from DNS / anycast withdraw Trade-off: DNS TTLs delay failover; anycast is faster but harder to operate

11. Failure modes to mention

12. Interview talking points

Draw the LB in front of a pool, name L4 vs L7, pick an algorithm for the workload (least-conn for WebSockets), describe health + drain, and say where TLS ends. If asked about multi-region, add DNS or global LB on top.

Quick revision

  • L4 = TCP/UDP; L7 = HTTP-aware routing and headers.
  • Algorithms: RR, weighted, least-conn, least-RT, IP hash, random.
  • Health: TCP/HTTP/custom; set interval, timeout, healthy/unhealthy thresholds.
  • Sticky via cookie / IP / URL param — last resort; externalize state.
  • LB HA: active-passive VIP vs active-active; managed LBs preferred.
  • GSLB/geo routing for multi-region entry; then regional LB.
  • TLS often terminates at LB; drain on deploy; slow-start recoveries.