Skip to content

Part 1 · Blueprint 03

Load Balancing & API Gateways

15 min reading · Sources · Editorial review pending

Balancing counts cannot fix an unhealthy or overloaded destination.

More
20px
Reading list
Page details

Published date · Last edited:

Draft edition. Editorial review and supplementary reading recommendations are still being completed.

Format: Architecture walkthrough. Prerequisites: the beginner bootcamp. Chapter prerequisites: Back-of-Envelope Capacity Estimation, Latency Numbers & Networking Foundations.

Sixty-second mental model

Problem: Balancing counts cannot fix an unhealthy or overloaded destination.

Use: Choose an observable routing unit and drain connections deliberately.

Design boundary: Route requests among eligible application instances. Health, available capacity and connection lifetime are different signals. A load balancer cannot move an already established WebSocket without a reconnect protocol.

Layer 1 · Intuition

Hypothetical scenario: Northwind is designing load balancing. Maya represents product requirements, Dev implementation and Priya reliability. The team must agree what one request means and which component owns the eligible backend set.

Think of a receptionist assigning customers to desks. Separate the requester from eligible backend set, then identify the retained evidence needed after failure.

Authority
The entitled state owner.
Invariant
A rule preserved across concurrency and failures.
API gateway
An entry point applying routing and shared API policies. Analogy: A service entrance checking credentials and directing requests.
GraphQL
A query language and execution model for requesting structured fields from a typed API. Analogy: A form where the customer selects the fields to return.
Health check
A probe used to assess whether a target can serve a defined function. Analogy: A readiness question asked before sending customers to a desk.
Horizontal scaling
Adding instances to distribute work or data. Analogy: Opening another kitchen to handle more orders.
JSON
A text format for structured values including objects, arrays, strings and numbers. Analogy: A standardized labeled packing list.

Architecture and worked reasoning

Design boundary: Route requests among eligible application instances. Health, available capacity and connection lifetime are different signals. A load balancer cannot move an already established WebSocket without a reconnect protocol.

Responsibilities on the request path

Load balancing: responsibilities and request directionRoute requests among eligible application instances. Health, available capacity and connection lifetime are different signals. A load balancer cannot move an already established WebSocket without a reconnect protocol.ClientsLoad balancerAPI instancesShared state
Route requests among eligible application instances. Health, available capacity and connection lifetime are different signals. A load balancer cannot move an already established WebSocket without a reconnect protocol.

Workload and limiting resource

Hypothetical peak is 900 requests/s. Each warmed instance has a selected 250 requests/s budget. Five instances leave four after a failure: 4 × 250 = 1,000 requests/s. Four instances leave only 750 requests/s and need rejection or reduced work. These are exercise budgets, not product benchmarks.

Keep the units attached to each intermediate result. The assumptions above describe a hypothetical exercise, not observed vendor capacity. A real capacity decision also needs a measured service curve, skew, recovery traffic and an explicit admission policy for overload.

Mutation or publication path

Load balancing: mutation boundaryReadiness admits a new instance only after dependencies and warm-up are ready. Then: Select a backend using the chosen request or connection policy. Then: Drain old connections before terminating a backend.Step 1
Readiness admits a new instance only after dependencies and warm-up are ready.
Step 2
Select a backend using the chosen request or connection policy.
Step 3
Drain old connections before terminating a backend.
Readiness admits a new instance only after dependencies and warm-up are ready. Then: Select a backend using the chosen request or connection policy. Then: Drain old connections before terminating a backend.
  1. Readiness admits a new instance only after dependencies and warm-up are ready.
  2. Select a backend using the chosen request or connection policy.
  3. Drain old connections before terminating a backend.

Observation and recovery path

Load balancing: observation boundaryFollow a request from listener to selected target. Then: Record queue time and backend response separately. Then: Retry only when the operation semantics permit another attempt.Step 1
Follow a request from listener to selected target.
Step 2
Record queue time and backend response separately.
Step 3
Retry only when the operation semantics permit another attempt.
Follow a request from listener to selected target. Then: Record queue time and backend response separately. Then: Retry only when the operation semantics permit another attempt.
  1. Follow a request from listener to selected target.
  2. Record queue time and backend response separately.
  3. Retry only when the operation semantics permit another attempt.

Failure that changes the decision

Hypothetical scenario: A shallow health probe succeeds while the database dependency is saturated. Every instance remains eligible and the balancer spreads failure. Add dependency-aware admission and bounded queues without creating a synchronized health-check cascade.

Attempt this decision before reading the explanation

Would round-robin balance long-lived connections with very unequal message rates?

It balances assignment counts, not necessarily work. Measure active connection work, use an appropriate least-load strategy where useful, and retain reconnect/catch-up semantics for failures.

Supporting mechanism analysis

Hypothetical scenario: Northwind. Maya represents product, Dev implementation and Priya reliability. The following workflow develops the underlying mechanism.

Maya: “Show which evidence changes the routing decision, and what happens before that change.”

You will turn a worker count into a distribution policy: which destination is eligible, what health evidence supports that judgment and how uneven work affects the choice. The product-record service remains a shared dependency, so removing one application worker cannot settle every failure case.

Before you continue: Two workers have equal connection counts. Must they be carrying equal request work?

A connection is not a fixed amount of application work. Its requests and durations matter. Using connection count can be reasonable, but the signal must match the workload being distributed.

This keeps the policy tied to its purpose. Compare request mix, in-flight work and waiting before deciding whether another distribution signal would be more useful.

A load balancer selects among destinations for incoming work. A transport-layer balancer can distribute connections, while an application-layer proxy can make decisions using HTTP requests. These boundaries matter: several requests can travel over one connection. Equal connection counts do not necessarily imply equal request counts or equal work.

In Northwind’s design, an HTTP reverse proxy receives catalogue reads and selects an eligible application worker. The workers do not hold essential visitor state locally, so either can serve the next anonymous read. The existing product-record service remains a downstream dependency. Routing around an application worker cannot repair a product service that every worker needs.

Keep regional destination selection separate from local worker selection. A name-resolution or global routing policy may direct a visitor toward a region. The regional proxy then selects a worker. A change in one layer need not immediately update every other layer, especially where clients reuse connections or cached name-resolution results.

Round robin rotates assignments across eligible workers. With similar workers and many similarly costly requests, it is a useful baseline. Weighted routing deliberately gives some destinations a larger share. Neither policy creates capacity; both decide how existing capacity is used.

Least-connections routing uses active connection counts as a signal of outstanding work. It can help when connection counts track occupancy, but that proxy becomes less informative when connections carry different amounts of work. Choosing an algorithm requires understanding the unit it observes and the workload it is meant to balance.

Hypothetical scenario. Choose one hundred active HTTP/2 streams carried by a single connection. An L4 balancer that assigns that connection to worker A has made one placement decision; counting connection assignments cannot establish equal request work across A and B. An L7 proxy may distribute eligible HTTP requests separately, while also terminating and managing their upstream connections.

Least-outstanding-request routing can avoid a worker with many unfinished requests, but request count is still a proxy for work. One expensive request may consume more CPU or hold more memory than several cheap ones. Keep the selected twenty-qualifying-reads-per-second worker envelope tied to the original request mix.

Separate routing configuration from serving decisions. A control-plane outage need not stop a data plane that can safely use its last valid endpoint set. An endpoint becoming unhealthy, however, requires a bounded observation and removal path. During drain, stop new assignments, track existing work and set an explicit termination bound; removing a name does not migrate a live connection.

Now preserve the separate stress case of thirty reads per second. With two workers, normal ideal share is 30 ÷ 2 = 15 per second, but one survivor must accept thirty. Demand exceeds its selected capacity by 30 − 20 = 10 per second. Perfect routing cannot remove that deficit. Three workers leave (3 − 1) × 20 = 40 reads per second after one loss, giving a fluid-model margin of 40 − 30 = 10 per second.

Those calculations assume the selected capacity remains valid under the same latency and freshness conditions. If twenty was measured without the product-service wait or with a different connection mix, it cannot be transferred uncritically. Per-worker capacity is a workload-dependent observation to establish, not a hardware label.

A passive health check learns from real request failures. An active probe sends separate checks. Either needs rules about what counts as failure, when to remove a worker and how to admit it again. A process answering a shallow probe can still fail catalogue lookups; a transient probe failure can also remove otherwise useful capacity.

Choose an illustrative two-second detection interval after a worker becomes unusable. Under ideal equal routing of fifteen requests per second, its assigned average rate is 7.5 per second. Over that interval, the fluid estimate is 7.5 × 2 = 15 affected assignments. This is not a bound on actual failures: request arrivals, in-flight work, thresholds and connection reuse can change the count.

That delay belongs in the failure model. Claiming seamless failover from a redundant worker count hides the requests sent before detection. Record what callers observe during detection, what can safely be retried and whether the survivor can absorb repeated attempts. Retry policy will receive its own treatment; redundancy alone does not define it.

Planned removal can stop new assignments while allowing suitable in-flight work to finish. That is connection or request draining, depending on the boundary. Abrupt failure offers no such cooperation. Distinguish both from deleting a destination name and assuming existing connections immediately disappear.

A recovered worker may have cold caches, empty connection pools or unfinished initialization. Returning its full weight immediately can make the first assignments slower than those on established workers. A gradual return may help, but its availability and precise behavior depend on the chosen proxy. Do not assume every product or edition implements the same controls.

NGINX’s HTTP load-balancing guide documents round-robin, weighted and connection-based selection, with product-specific capabilities. It is a concrete place to check the policy’s observation boundary. A diagram labeled “NGINX” is still incomplete until the chosen method, health behavior and recovery policy are stated.

Hypothetical failure scenario. Both workers pass a process-level check, but one has lost its connection to the product service. Round robin continues sending it catalogue reads. Infrastructure graphs show even distribution while visitors see intermittent failures. A check of the actual serving capability, combined with request-outcome evidence, reveals the mismatch.

Layer 3 · Internals

Trade-offs and limits

ApproachProvidesRequires
Transport-layer routingDistributes connections without parsing application requests.Cannot choose a backend using an HTTP route or user-level policy.
Application-layer routingCan use method, path and request metadata.Adds protocol handling and requires deliberate connection and retry behavior.

Recovery decision

Hypothetical scenario: A shallow health probe succeeds while the database dependency is saturated. Every instance remains eligible and the balancer spreads failure. Add dependency-aware admission and bounded queues without creating a synchronized health-check cascade.

It balances assignment counts, not necessarily work. Measure active connection work, use an appropriate least-load strategy where useful, and retain reconnect/catch-up semantics for failures.

Write your design before revealing the review

Would round-robin balance long-lived connections with very unequal message rates?

Evidence you can explain in your own design

Drafts and self-review are stored only in this browser. They are separate from reading completion.

Compare your decision

It balances assignment counts, not necessarily work. Measure active connection work, use an appropriate least-load strategy where useful, and retain reconnect/catch-up semantics for failures.

A shallow health probe succeeds while the database dependency is saturated. Every instance remains eligible and the balancer spreads failure. Add dependency-aware admission and bounded queues without creating a synchronized health-check cascade.

Check your understanding

Would round-robin balance long-lived connections with very unequal message rates?

It balances assignment counts, not necessarily work. Measure active connection work, use an appropriate least-load strategy where useful, and retain reconnect/catch-up semantics for failures.

How would you recover from this failure: A shallow health probe succeeds while the database dependency is saturated. Every instance remains eligible and the balancer spreads failure. Add dependency-aware admission and bounded queues without creating a synchronized health-check cascade.

Start with the exact boundary that failed. Readiness admits a new instance only after dependencies and warm-up are ready. Select a backend using the chosen request or connection policy. Drain old connections before terminating a backend. Then recover evidence through the observation path: Follow a request from listener to selected target. Record queue time and backend response separately. Retry only when the operation semantics permit another attempt. Preserve the distinction between a confirmed state change and an unavailable response.

Which assumption in the worked calculation would a burst or concentrated tenant invalidate first?

Hypothetical peak is 900 requests/s. Each warmed instance has a selected 250 requests/s budget. Five instances leave four after a failure: 4 × 250 = 1,000 requests/s. Four instances leave only 750 requests/s and need rejection or reduced work. These are exercise budgets, not product benchmarks. Recompute the affected resource rather than multiplying unrelated storage and network budgets by the same factor. Route requests among eligible application instances. Health, available capacity and connection lifetime are different signals. A load balancer cannot move an already established WebSocket without a reconnect protocol.

Which component in this topology could be removed from a smaller first deployment?

Clients, Load balancer, API instances, Shared state name responsibilities, not a requirement for separate processes. Co-locate responsibilities when their transaction, trust and capacity boundaries permit it. Readiness admits a new instance only after dependencies and warm-up are ready.

What evidence must a caller have before relying on the observation path?

Follow a request from listener to selected target. Record queue time and backend response separately. Retry only when the operation semantics permit another attempt. It balances assignment counts, not necessarily work. Measure active connection work, use an appropriate least-load strategy where useful, and retain reconnect/catch-up semantics for failures.

45-minute interview rubric

  1. 00–05: scope request and eligible backend set.
  2. 05–12: identify the limiting resource and derive the domain workload above, retaining units and assumptions.
  3. 12–28: draw eligible backend set, numbered writes and reads.
  4. 28–40: challenge recovery: Choose an observable routing unit and drain connections deliberately.
  5. 40–45: defend backend_id placement, observations and remaining assumptions.

Go deeper

Decision log

Choose an observable routing unit and drain connections deliberately.

Preserve request identity and eligible backend set ownership.

Revisit changed workload, observations or recovery objectives.