Playground: the load balancerPlayground: load balancer
Send traffic and watch each algorithm pick a server. Kill a server and watch health checks kick it out of rotation.Traffic bhejo aur dekho har algorithm kaunsa server chunta hai. Server ko crash karo aur dekho health checks use rotation se nikaal dete hain.
Balancer
Why the load balancer exists
Horizontal scaling means many app servers. Someone must decide which server takes each request: that is the load balancer. It does three jobs at once: distribute (spread load evenly), protect (stop sending traffic to dying servers), and hide (clients see one address, servers can be added/removed behind it).
L4 vs L7, with the real difference
- L4 (transport): sees only IP + port, forwards TCP/UDP streams without parsing them. Extremely fast (millions of connections per box), but blind: cannot route /api vs /images differently. Examples: AWS NLB, classic hardware LB.
- L7 (application): terminates the connection and reads HTTP: path, headers, cookies, method. Enables path routing (/api -> API pool, /static -> CDN origin), header-based routing (mobile app versions), cookie stickiness, and request-level retries. Examples: NGINX, HAProxy, AWS ALB, Envoy, Cloudflare.
The tradeoff: L7 costs CPU (TLS termination + parsing) but buys routing intelligence. Modern systems default to L7; L4 sits in front when raw connection throughput is the bottleneck.
Distribution algorithms and when each wins
- Round robin: next server in line. Fine when requests cost about the same and servers are identical.
- Least connections: send to the server with fewest active requests. Wins when request durations vary wildly (some 10 ms, some 10 s): long requests do not pile up on one unlucky server.
- Consistent/IP hash: same client always hits the same server. Good for local caching, but creates hot spots and complicates rebalancing.
- Weighted: server with 2x capacity gets 2x traffic. Also the canary-deploy tool: route 5% to the new version, watch errors, ramp to 100%.
Health checks: the part that keeps users happy
The LB pings each server (TCP connect or HTTP /health) every few seconds. Two failures in a row: server leaves the rotation, traffic silently flows to the rest. Recovering server passes checks again: it rejoins. Tuning matters: too sensitive and flapping servers bounce in and out; too slow and users hit dead servers for seconds. Typical: 2-5s interval, 2-3 failure threshold, and a /health endpoint that actually checks dependencies (DB reachable, disk not full) rather than always returning 200.
The LB's own availability
"What if the LB dies?" is a mandatory follow-up. Answers: active-passive LB pairs with virtual-IP failover, DNS-level balancing across LB instances, Anycast (many LBs worldwide share one IP, BGP routes to the nearest), or a managed cloud LB that handles this internally. Never draw one LB box without its failover story.
Worked example
API at 20k RPS, request cost 5-500 ms (mixed). Choice: L7 ALB/NGINX, least-connections (because durations vary), HTTP health checks at 3s interval with 2-failure threshold, /health verifying DB connectivity, 2 LB instances via the cloud's multi-AZ setup. Sessions in Redis so any app server can take any request.
Common interview traps
- One LB box with no failover answer.
- Sticky sessions as the session strategy instead of a shared session store.
- Round robin for a workload with wildly uneven request costs.
- Health checks that return 200 even when the server cannot reach the DB.
Interview Q&A
Q: How do you deploy a new app version with zero downtime?
A: Rolling/blue-green behind the LB: spin up new-version servers, add them to the pool once healthy, drain old servers (stop new connections, finish in-flight ones), remove. Weighted routing turns this into a canary: 5% traffic first, watch error rates, then ramp.
Q: All servers are "healthy" but users see timeouts. What is wrong?
A: Classic cases: the LB's connection pool to backends is exhausted, health checks pass but the app is slow (check latency, not just liveness), or keep-alive settings make the LB hold stale connections to recently restarted servers.
Load balancer exist kyun karta hai
Horizontal scaling ka matlab: kayi app servers. Kisiko decide karna hai ki har request kaunsa server lega: yehi load balancer hai. Wo teen kaam ek saath karta hai: distribute (load barabar baanto), protect (marte servers ko traffic dena band karo), aur hide (clients ko ek address dikhe, servers peeche add/remove hote rahen).
L4 vs L7, asli farak ke saath
- L4 (transport): sirf IP + port dekhta hai, TCP/UDP streams ko bina parse kiye forward karta hai. Bahut fast (ek box par millions connections), par andha hai: /api aur /images ko alag route nahi kar sakta. Examples: AWS NLB, classic hardware LB.
- L7 (application): connection terminate karke HTTP padhta hai: path, headers, cookies, method. Path routing (/api -> API pool), header-based routing (mobile app versions), cookie stickiness, request-level retries sab possible. Examples: NGINX, HAProxy, AWS ALB, Envoy, Cloudflare.
Tradeoff: L7 ko CPU chahiye (TLS termination + parsing) par routing intelligence milti hai. Aaj kal default L7 hai; jab raw connection throughput bottleneck ho tab L4 aage baithta hai.
Distribution algorithms, aur kaun kab jeet-ta hai
- Round robin: line se agla server. Tab theek jab requests ki cost barabar ho aur servers same hon.
- Least connections: jis server par sabse kam active requests, wahan bhejo. Tab jeet-ta hai jab request durations bahut vary karein (koi 10 ms, koi 10 s): lambe requests ek server par jama nahi hote.
- Consistent/IP hash: same client hamesha same server par. Local caching ke liye accha, par hot spots aur rebalancing issues.
- Weighted: 2x capacity wale ko 2x traffic. Canary deploy ka bhi tool: naye version ko 5% traffic, errors dekho, phir 100%.
Health checks: wo hissa jo users ko khush rakhta hai
LB har server ko ping karta hai (TCP connect ya HTTP /health) har kuch second. Lagatar 2 failures: server rotation se bahar, traffic chupchaap baakiyon par. Server recover hua aur checks pass: wapas andar. Tuning matter karti hai: zyada sensitive to flapping servers andar-bahar bounce karenge; zyada slow to users seconds tak mare server par jaayenge. Typical: 2-5s interval, 2-3 failure threshold, aur /health endpoint jo sach mein dependencies check kare (DB reachable, disk full nahi), har baar 200 dene wala nahi.
LB ki apni availability
"LB mar gaya to?" ek mandatory follow-up hai. Jawab: active-passive LB pairs virtual-IP failover ke saath, DNS-level balancing multiple LBs par, Anycast (duniya bhar ke LBs ek IP share karte hain, BGP nearest par route karta hai), ya managed cloud LB jo ye internally handle karta hai. Ek LB box bina failover story ke kabhi mat banao.
Worked example
20k RPS ka API, request cost 5-500 ms (mixed). Choice: L7 ALB/NGINX, least-connections (durations vary karti hain isliye), 3s interval par HTTP health checks, 2-failure threshold, /health DB connectivity verify kare, cloud ke multi-AZ setup se 2 LB instances. Sessions Redis mein taaki koi bhi app server koi bhi request le sake.
Common interview traps
- Ek LB box, failover ka jawab nahi.
- Session strategy ke liye sticky sessions, shared session store ki jagah.
- Wildly uneven request costs wale workload par round robin.
- Health checks jo DB tak pahunch nahi paa raha tab bhi 200 dein.
Interview Q&A
Q: Naya app version zero downtime ke saath kaise deploy karoge?
A: LB ke peeche rolling/blue-green: new-version servers banao, healthy hote hi pool mein daalo, purane servers drain karo (naye connections band, in-flight finish), hatao. Weighted routing isse canary banata hai: pehle 5% traffic, error rates dekho, phir ramp.
Q: Saare servers "healthy" hain par users ko timeouts aa rahe hain. Kya galat hai?
A: Classic cases: LB ka backends ka connection pool exhaust ho gaya, health checks pass ho rahe hain par app slow hai (liveness nahi, latency dekho), ya keep-alive settings ki wajah se LB recently restarted servers ke stale connections pakde hue hai.