Load balancing and stateless services
How does load balancing work, and why should services be stateless to scale horizontally?
TL;DR
A load balancer spreads incoming requests across several instances of a service, removes unhealthy ones using health checks, and gives clients a single endpoint. Horizontal scaling (adding instances) only works if any instance can handle any request, which means the service must be stateless: no sessions, uploads or caches that only live in one instance's memory or disk. Move that state to shared stores (Redis, the database, object storage) and you can add, remove or replace instances freely.
Key points
- L4 load balancers route by IP and port (TCP/UDP): fast, protocol-agnostic. L7 load balancers understand HTTP: route by path or header, terminate TLS, retry, and rate-limit.
- Algorithms: round robin, least connections (good for uneven request durations), weighted (different instance sizes), and consistent hashing (cache affinity).
- Health checks: an active probe of
/healthz; take an instance out after N failures. - Sticky sessions pin a user to one instance. They're a workaround for stateful apps, but they cause uneven load and lose sessions when an instance dies.
- Connection draining lets in-flight requests finish during deploys.
- Load balancers exist at many layers: DNS and global (GeoDNS, anycast), cloud LBs (ALB, NLB), reverse proxies (NGINX, Envoy), and client-side (in a service mesh).
Example
┌──► api-1 ─┐
client ─► LB ─► api-2 ─┼──► PostgreSQL
└──► api-3 ─┘ Redis (sessions, cache)Any API instance can serve any request because sessions live in Redis, not in instance memory.
Common follow-ups
- Isn't the load balancer a single point of failure? Managed cloud LBs are redundant across zones; self-hosted pairs use failover (keepalived with a floating IP).
- Vertical vs horizontal scaling? Vertical means a bigger machine: simple, but limited and a single failure point. Horizontal means more machines: needs statelessness, but scales further and survives failures.
What interviewers look for
Tip
Connect statelessness to horizontal scaling, compare L4 and L7, and mention health checks and draining.
- Red flag: relying on sticky sessions as the scaling strategy.