Sub topic 13
Keeping the proxy tier available and scalable
This chapter assumes you know how a reverse proxy load balances across backends and how health checks detect failed backends. It also assumes basic familiarity with IP addresses, DNS and TCP. Earlier chapters made the backends redundant. Now the proxy tier needs the same treatment, because every request passes through it.
Why the proxy becomes the weak point
A single reverse proxy in front of ten healthy backends is still a single point of failure. If that one machine crashes, runs out of file descriptors, or needs a reboot for a kernel patch, the whole service is unreachable even though every backend is fine.
The proxy tier also limits capacity. Each proxy has a ceiling set by CPU, memory, network bandwidth and the number of concurrent connections it can hold. TLS handshakes are CPU-heavy. Cached responses use memory and disk. Long-lived connections such as WebSockets use file descriptors.
Two separate goals follow from this:
- Availability: the service keeps working when one proxy instance fails or is taken down for maintenance.
- Scalability: the tier can handle more traffic by adding instances, not by buying a bigger machine.
You usually solve both with the same design: several identical proxy instances and a way to spread clients across them.
Active-passive: one live proxy, one standby
The simplest design runs two proxies. One is active and receives traffic. The other is a standby with the same configuration. Both share a floating virtual IP address (VIP). Clients and DNS point at the VIP, never at an individual proxy.
A health protocol decides who holds the VIP. The common one on Linux is VRRP (Virtual Router Redundancy Protocol), implemented by keepalived. The active node sends periodic advertisements. If the standby stops hearing them, it claims the VIP and sends a gratuitous ARP so the local network learns the new location of the address.
A minimal keepalived configuration for the active node looks like this:
vrrp_script chk_nginx {
script "/usr/bin/pgrep nginx"
interval 2
weight -20
}
vrrp_instance VI_1 {
state MASTER
interface eth0
virtual_router_id 51
priority 110
advert_int 1
virtual_ipaddress {
10.0.0.100/24
}
track_script {
chk_nginx
}
}The standby uses state BACKUP and a lower priority, for example 100. The vrrp_script lowers the node's priority by 20 when nginx is not running, so the standby wins even if the machine itself is still up.
Active-passive is easy to reason about, but it has costs:
- The standby sits idle, so you pay for capacity you do not use.
- Failover takes a few seconds, and in-flight connections on the failed node are lost.
- The pair is limited to one machine's capacity at a time.
- VRRP needs both nodes on the same layer 2 network. Many cloud networks do not allow it, and providers offer their own mechanism instead (an elastic IP reassignment, for example).
Active-active: all proxies serve traffic
In an active-active design, every proxy instance handles traffic at the same time. If one fails, the others absorb its share. Capacity grows by adding instances. The open question is how clients get spread across them. There are three common answers.
DNS round robin
You publish several A records for one name, one per proxy. Resolvers return them in rotating order, and clients pick one.
This is cheap and needs no extra component, but it has weaknesses:
- DNS does not know a proxy is down. Clients keep receiving the dead address until you remove the record and the TTL (time to live) expires.
- Clients and resolvers cache answers, so you do not control how evenly traffic splits.
- Some clients retry the next address on connection failure, and some do not.
Short TTLs help but increase DNS query load. DNS round robin works best when combined with a health-checked DNS service that removes unhealthy records automatically.
A layer 4 load balancer in front
A layer 4 load balancer works on TCP connections and does not parse HTTP. It is fast and can carry very high connection counts. It spreads connections across the proxy instances and health-checks them. Cloud network load balancers and tools like LVS or HAProxy in TCP mode fill this role.
This produces a layered design: a thin, simple layer 4 tier distributes to a thicker layer 7 proxy tier, which does the HTTP work (routing, caching, TLS, headers) and forwards to backends. The layer 4 tier rarely changes, so it is a reasonable place to put the stable public address.
Note that if TLS is terminated at the layer 7 proxies, the layer 4 tier passes encrypted bytes through. The client's source address can then be lost unless you use the PROXY protocol, which prepends a small header carrying the original client address. Both the layer 4 balancer and the proxy must be configured to use it.
Anycast and BGP
Large operators announce the same IP address from many locations using BGP. The network routes each client to the nearest announcing site. If a site stops announcing, traffic shifts to others. This gives both scaling and geographic distribution, but it requires your own address space and routing expertise. Most teams use it through a CDN or a cloud provider instead of running it themselves.
| Approach | Failure detection | Failover speed | Complexity | Typical use |
|---|---|---|---|---|
| Active-passive with VRRP | Heartbeat | Seconds | Low | Small sites, one data center |
| DNS round robin | None by default | Minutes (TTL-bound) | Very low | Cheap spreading, paired with DNS health checks |
| Layer 4 balancer in front | Health checks | Seconds | Medium | Self-run or cloud scale-out |
| Anycast with BGP | Route withdrawal | Seconds | High | Global services, CDNs |
Keep the proxies stateless
Scaling out is easy only when any proxy instance can serve any request. Check these points:
- Configuration is identical and versioned. Deploy it from source control or a config management tool, not by hand-editing each node. A node with a stale config is a hidden failure.
- No session state lives in the proxy. If you use sticky sessions, such as
ip_hashin nginx or a cookie, they only bind a client to a backend. They do not need to be shared across proxies when each proxy computes the same hash. Cookie-based stickiness set by the proxy is the trap. A different proxy may not know the mapping unless it is encoded in the cookie value itself. - Caches are per instance. Each proxy fills its own cache, so a request that hits proxy A and then proxy B is a miss on B. Your overall hit ratio drops as you add instances. Fixes include routing by URL hash to a cache-tier proxy, or adding a shared cache layer behind the edge proxies.
- Rate limits are per instance too. A limit of 100 requests per second per client, enforced independently on four proxies, allows up to 400. Use a shared store such as Redis if you need an exact global limit, or divide the limit by the instance count if approximate is acceptable.
- TLS keys and certificates are distributed securely. All instances need the certificate, and renewals must reach all of them. Session ticket keys should be shared, or resumed sessions will fail when a client lands on a different proxy.
Draining and graceful change
Availability also covers planned changes. When you reload a proxy or remove it from rotation, you do not want to cut live requests.
nginx supports graceful reload. On nginx -s reload, it starts new worker processes with the new configuration and tells old workers to stop accepting connections and exit after finishing their current requests. Long-lived connections can keep old workers alive for a long time, so set worker_shutdown_timeout to bound the wait:
worker_shutdown_timeout 60s;To remove a whole instance, drain it first:
- Tell the load balancer in front to stop sending new connections to it.
- Wait for in-flight requests to finish, or for a set timeout.
- Stop or patch the instance.
- Return it to rotation only after its health check passes.
Rolling changes, one instance at a time, keep capacity above the minimum. Make sure the remaining instances can carry the full load while one is out. This is the N+1 rule: provision enough instances that losing one still leaves enough capacity.
Capacity and what to measure
Scale on measurements, not guesses. Useful signals for a proxy tier:
- Requests per second and active connections per instance.
- CPU usage, with attention to TLS handshake rate.
- Memory and cache disk usage.
- Open file descriptors compared with the limit (
worker_connectionsand the OSulimit). - Upstream response time and error rates (5xx, 502, 504).
- Network throughput against the interface limit.
Autoscaling on CPU or connection count works well for stateless proxies, provided new instances take traffic only after they pass health checks and warm-up is short. A cold cache on a new instance sends extra traffic to the backends, so scale up before the peak, not during it.
Failure modes to design for
- Split brain. In an active-passive pair, a network fault between the nodes can make both believe the other is dead. Both claim the VIP and the network behaves unpredictably. Use a dedicated heartbeat path, and consider adding a third observer or fencing.
- Healthy proxy, unreachable backends. Failover between proxies does not help if both reach the same broken backend pool. Check backend health from every proxy, and make sure a proxy that cannot reach any backend removes itself from rotation.
- Overload after failover. When one instance dies, its traffic moves to the rest and can push them over their limits, causing a cascade. Keep headroom, and use connection limits and timeouts to fail fast instead of queueing.
- Retry storms. If clients and the proxy both retry failed requests, a brief fault multiplies load. Retry only idempotent requests, limit attempts, and add backoff.
- Shared dependencies. Two proxies in the same rack, on the same power feed, or using the same config deployment can fail together. Spread them across failure domains such as availability zones.
Choosing a design
For a small service in one data center, an active-passive pair with a VIP is often enough. For a service that must grow, run several identical proxies behind a layer 4 balancer or a cloud load balancer, spread across availability zones, and size the tier to survive one failure. For a global audience, add DNS-based geographic routing or anycast, usually through a provider. In every case, keep proxies stateless, drain before changes, and test failover.
Exercise
Your site runs four identical nginx proxies behind a layer 4 balancer. Each proxy enforces a limit of 50 requests per second per client IP, and each keeps its own cache. A single client sends 400 requests per second spread evenly. (a) Roughly how many requests per second can that client get through, and why? (b) What happens to the cache hit ratio compared with a single proxy, and how could you reduce the effect?
Show answer
(a) Each proxy sees about 100 requests per second from the client and allows 50, so about 200 requests per second pass in total. The limit is enforced per instance, not globally. To enforce a true global limit, use a shared store such as Redis, or set the per-instance limit to the global limit divided by four if an approximate result is acceptable. (b) The hit ratio drops, because each proxy has to fill its own cache and a request that reaches a different proxy is a miss. You can reduce this by having the balancer route by a hash of the URL so the same content always reaches the same proxy, or by adding a shared cache tier behind the edge proxies.
Exercise
A two-node keepalived pair loses its heartbeat link, but both nodes can still reach clients. What can go wrong, and name two measures that reduce the risk?
Show answer
Each node thinks the other has failed and claims the virtual IP, which is called split brain. Clients may be sent to either node, and connections can break as the network's ARP tables change. Measures include sending heartbeats over more than one network path, adding a third node or external witness to decide who is active, and fencing the suspected failed node so it cannot serve traffic.