Build a Traffic Distributor for L4 and L7 Backend Pools
System DesignModel answerLast updated
Design a software traffic distributor that spreads L4 and L7 requests across a backend pool, with health monitoring, sticky sessions, failover, and its own horizontal scaling.
Task
You are asked to design a software traffic distributor that sits in front of a fleet of application servers. It accepts client connections and forwards them to healthy backends. It must work for both L4 (raw TCP) and L7 (HTTP/HTTPS) traffic.
Functional requirements
- Distribute traffic by a configurable policy: round robin, least connections, or weighted distribution.
- Probe backends periodically and take unhealthy ones out of rotation, then bring them back when they recover.
- Support session affinity ("sticky sessions") for L7 traffic, so a returning user tends to reach the same backend.
Non-functional requirements
- High availability: the distributor must tolerate failures of its own nodes without dropping the service.
- Scalability: it must hold thousands of concurrent connections, and scale out as load grows.
- Latency: it should add minimal overhead on the request path.
Scale assumptions
- Peak load of 100,000 requests per second.
- A pool of 50 backend servers.
What to deliver
- A high-level architecture, described in text (components and how they connect).
- How state is managed: connection tracking, backend health, configuration, and session affinity.
- The request flow for L4 traffic and for L7 traffic.
- A strategy for scaling and protecting the distributor itself.
State your assumptions, size the system with rough numbers, and call out the trade-offs you are making.
Hints
Hint 1
Start with numbers: 100K RPS over 50 backends is about 2K RPS each. Estimate concurrent connections and egress bandwidth, and ask whether TLS terminates at the distributor.
Hint 2
Separate the control plane (config, health, membership) from the data plane (packet and request forwarding). The data plane should keep serving if the control plane is unreachable.
Hint 3
Ask which state truly needs to be shared. Connection tables can be rebuilt from a deterministic hash, load counts can stay local (try sampling two backends), and stickiness can live in a signed cookie.
Hint 4
For failover, think about how a front tier spreads flows across distributor nodes (ECMP/BGP with a stable VIP) and how a node dying avoids breaking existing connections.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
1. Clarify and size
Assumptions I would state up front:
- 100K RPS peak across 50 backends means about 2K RPS per backend.
- With roughly 20 KB responses, egress is about 2 GB/s (~16 Gbps). That is large enough that the L4 tier should not sit on the return path (see Direct Server Return below).
- Many clients use keep-alive, HTTP/2 or WebSockets, so plan for 200K-500K concurrent connections.
- TLS terminates at the L7 tier. Full handshakes are CPU-expensive, so session resumption and keep-alive matter.
- Latency budget: microseconds at L4, under about 1 ms added at p99 at L7.
- Capacity: a tuned Envoy or Nginx node handles roughly 30-50K TLS RPS, so 6 L7 nodes across 2 availability zones gives N+2 headroom. L4 nodes (XDP/IPVS style) forward millions of packets per second, so 3-4 nodes are for redundancy, not throughput.
2. Architecture
Clients -> DNS -> VIP (anycast)
|
Edge routers -- BGP/ECMP --> L4 tier x4 (consistent hash on 5-tuple, encapsulate)
|
L7 tier x6 (TLS termination, routing, stickiness, retries)
|
Backend pool (50 servers)
Control plane: etcd (3-5 nodes) + config API + health-check service
Data-plane nodes watch etcd and hot-apply config
Two planes:
- Data plane (L4 and L7 nodes): stateless or soft-state, horizontally scalable, and it fails static (keeps serving the last known config) if the control plane is down.
- Control plane: the source of truth for pools, weights, policies and health. Writes are tiny (50 backends, changes every few seconds), so a consistent store like etcd is plenty. Never store per-request or per-connection state there.
3. State management
| State | Location | Reason |
|---|---|---|
| Pool config, weights, policy | etcd, cached in memory per node | Low churn, needs consistency |
| Backend health | Local probes plus aggregated view in etcd | Fast local reaction, global agreement |
| L4 flow table | Local per-node map with LRU | Hot path, must be local |
| Active connection counts | Local per L7 node | Exact global counts are not needed |
| Sticky mapping | Signed cookie on the client | Stateless, survives node loss |
Key ideas:
- Reconstructible connection tracking. L4 nodes choose an L7 node with Maglev or consistent hashing over the healthy L7 set. If an L4 node dies, ECMP moves its flows to another L4 node, which computes the same hash and picks the same L7 node. No conntrack replication is needed.
- Least connections without global state. Each L7 node counts only its own connections and uses power-of-two-choices: sample two backends, pick the less loaded. This avoids the herding that "pick the global minimum" causes with stale data.
- Hybrid health checking.
- Active:
GET /healthzevery ~2 s with jitter; mark down after 3 consecutive failures, up after 2 successes (hysteresis prevents flapping). - Passive: eject a backend after about 5 consecutive 5xx responses or timeouts.
- Nodes react locally at once and publish to etcd so everyone converges. To avoid 6x50 probe traffic, a small checker quorum can probe and write results centrally.
- Active:
4. Request flow
L4 (TCP)
- SYN reaches the edge router, which ECMP-hashes to an L4 node.
- On a flow-table miss, the node hashes the 5-tuple over healthy L7 nodes and records the choice.
- It encapsulates (IP-in-IP/GUE) and forwards. No TCP termination here.
- Later packets hit the table in O(1).
- With Direct Server Return, the L7 node answers the client directly using the VIP as source, keeping the L4 tier off the heavy return path.
L7 (HTTP/HTTPS)
- Terminate TCP and TLS (session tickets for resumption) and parse the request.
- Match host/path/header rules to select a pool.
- Stickiness: if a valid affinity cookie exists (HMAC-signed so it cannot be forged) and the backend is healthy, use it; otherwise re-pick and reset the cookie. Fallback is a source-IP hash, with the caveat that users behind NAT collapse onto one backend.
- Otherwise apply the policy: smooth weighted round robin, or least connections via P2C.
- Forward over a pooled keep-alive upstream connection, adding
X-Forwarded-Forand a request ID. - Enforce timeouts; retry only idempotent requests, capped by a retry budget (~10% of traffic) to avoid retry storms.
- Stream the response back.
5. Scaling and availability of the distributor itself
- L4 tier: every node announces the VIP via BGP; BFD withdraws a dead node's route in under a second. To scale, add a node and announce.
- L7 tier: L4 nodes health-check L7 nodes. Adding a node means registering it; with Maglev only about 1/N of flows move.
- Control plane: etcd across 3 or 5 nodes in multiple zones; the data plane fails static if it is unreachable.
- Multi-region: GeoDNS or anycast, with a full stack per region.
- Deploys: drain connections and roll one node at a time.
- Protection: per-client rate limits, connection limits and SYN-flood defenses at the L4 tier.
6. Trade-offs
- Two tiers vs. one: two tiers add a hop but separate packet-rate scaling from protocol work and give a stable VIP while L7 nodes churn.
- Cookie vs. IP-hash stickiness: cookies are precise and stateless but L7-only; IP hash works at L4 but skews under NAT and remaps when the pool changes.
- Local vs. global load info: approximate local counts cost a little balance quality but buy lower latency and resilience.
- Aggressive vs. conservative health thresholds: fast ejection reduces errors but risks flapping and cascading overload.
7. Common mistakes
- Replicating connection tables between nodes instead of using deterministic hashing.
- Making the LB a single point of failure (one active/passive pair with no plan for scale).
- Putting per-request state in a strongly consistent store.
- Ignoring the return path bandwidth at L4.
- Retrying non-idempotent requests or retrying without a budget.
- Marking backends up or down on a single probe result.
- Forgetting connection draining when removing a backend or deploying.