Part 5 of the eight-part How Backend Systems Scale series. Keep the separate powers-of-ten estimation reference nearby for the calculations.
We add a second photo API server. It runs the same code as the first, connects to the same database, and has room to handle requests.
The mobile app still calls one address. Until something sends work to the new server, that spare capacity sits unused.
Routing is the missing piece. Following it will also expose a few failures that extra application instances don’t solve by themselves.
On this page
- Route traffic to application capacity
- Who balances the load balancer?
- Deliver reusable content close to readers
- Why popular content benefits from edge caches
Route traffic to application capacity
Put one address in front of the pool
A load balancer provides an entry point and chooses a backend for incoming work:
An instance is one running copy of the application. A balancer often acts as a reverse proxy. Some balance transport connections; others understand HTTP and can use hostnames or paths.
We still need a selection rule:
| Policy | How it chooses | Useful consideration |
|---|---|---|
| Round robin | Take turns across instances | Simple when instances and work are similar |
| Least connections | Prefer fewer active connections | Connection count does not always equal actual work |
| Weighted routing | Send more traffic to stronger instances | Weights need updating when capacity changes |
Round robin works well enough for some similar instances and requests. It won’t distribute expensive image processing perfectly just by alternating destinations. Nor can any selection rule repair a database bottleneck shared by every instance.
Healthy enough to receive work
Now stop instance A. If the balancer keeps choosing it, customers still see failures while B has capacity available.
A health check gives the balancer evidence about where it should send traffic:
- Readiness asks whether an instance can accept useful work now.
- Liveness asks whether the process is functioning enough to keep running.
- A process can be alive while its request path is broken.
- Periodic checks have a detection delay; requests can fail in the gap.
Be careful with shared dependencies. An optional service failure shouldn’t necessarily remove every application instance. Restarting all instances during a database outage can also make recovery harder.
During a deployment, stop assigning new work to an old instance and let existing requests finish within a deadline. That is connection draining. The same request doesn’t automatically restart elsewhere just because another instance exists.
The hidden problem: state on one server
Suppose a customer logs in through A. We store the session in A’s memory. The next request reaches B, which has no record of it, and the customer appears logged out.
The replicas of our application code don’t contain the same temporary state. We need a deliberate state design:
| Approach | Benefit | Cost |
|---|---|---|
| Sticky routing to the same instance | Can preserve local session access | Instance failure still loses local state |
| Shared session storage | Any instance can find the session | Adds a dependency and network access |
| Validated signed tokens | Can avoid a session lookup for some designs | Expiration, revocation, and key management need care |
The same issue applies to uploaded files. Durable images belong in accessible object storage rather than an arbitrary API instance’s local disk.
Allow for a failed instance
Assume peak demand is 3 × 10^3 requests per second and a measured useful capacity of 10^3 per instance:
- Three instances only match the peak while all three work.
- Losing one leaves
2 × 10^3capacity. - Four provide enough aggregate capacity after one loss under these simplified assumptions.
- Uneven routing, bursts, and slower dependencies can require more margin.
Redundancy and spare capacity are related. A replacement destination is only useful if it can accept the work it inherits.
Who balances the load balancer?
Our diagram still has a single box at the entrance. If that box disappears, ten healthy application servers may become unreachable.
We need to consider the entry point’s failure model too:
| Layout | How it helps | What to check |
|---|---|---|
| Active/passive | A standby can take over | Failure detection and how traffic reaches the standby |
| Active/active | Multiple balancers serve traffic | Shared configuration and routing to healthy balancers |
| Managed distributed service | Provider operates the balancing fleet | Documented failure scope and remaining dependencies |
An active/passive layout needs a takeover mechanism. An active/active layout needs consistent configuration and routing to healthy balancers. A managed service still has documented failure boundaries and dependencies to understand.
Health checks and redundancy reduce disruption. They don’t guarantee that every in-flight request completes during a transition.
Local versus global routing
Within a region, the balancer chooses an application instance. Across regions, another mechanism first chooses an entry point.
Two common approaches operate at different layers:
- DNS-based routing returns addresses according to policy and health.
- Anycast lets several locations advertise the same IP address; network routing selects a reachable destination according to topology and policy.
Anycast can bring traffic into a global service near the caller in network terms. It doesn’t guarantee the closest geographic location or inspect each application’s CPU use. A selected location can still need its own local balancing.
Four related delivery terms distinguish the destination patterns:
| Term | Destination pattern | Example meaning |
|---|---|---|
| Unicast | One addressed destination | A request to one server address |
| Anycast | One of several locations advertising an address | Routing selects one reachable location |
| Multicast | Members of a selected group | Deliver to receivers subscribed to that group |
| Broadcast | All receivers in a local broadcast domain | Local network discovery; not a way to send to the entire Internet |
Why DNS failover is not immediate
Changing an authoritative DNS answer doesn’t change every client at once. Resolvers and clients cache answers, and existing connections can remain open.
- TTL influences how long an answer may be cached.
- Some requests may continue toward an old address while cached answers expire.
- Open connections have their own lifetimes.
- Clients still need sensible timeouts and retry behavior.
Route 53’s routing policies give concrete examples of DNS-level choices. Cloudflare’s anycast explanation describes the network-level approach.
Match the balancing algorithm to the workload
Beyond round robin, least connections, and weights, implementations may offer:
- Random selection, sometimes combined with a comparison between candidates.
- Least response time based on recent measurements.
- Hash-based selection using a request property to maintain affinity.
Affinity can improve reuse of local data, but a popular key can also concentrate load. Adding or removing backends changes assignments unless the placement mechanism limits movement.
Avoid memorizing a universal proxy requests-per-second capacity. TLS, payload size, connection reuse, hardware, and configuration all affect the result.
Deliver reusable content close to readers
The API can now route requests to several healthy instances. A customer on another continent still waits for every image to arrive from the original region.
A content delivery network can reuse appropriate responses closer to viewers. This is another application of proxies and caches, with a geographic delivery goal.
Follow a cache miss and a hit
The origin is the source server or storage endpoint. A CDN edge serves viewers. Its cache key identifies which response can be reused.
On a miss, the edge fetches from the origin. A later request can use that response while it remains reusable. Not every object is present at every edge, so origin behavior still matters.
A versioned URL makes freshness easier
If someone changes an avatar, the edge may still have its old bytes. The URL design affects how we handle that:
| Approach | When an image changes | Consequence |
|---|---|---|
Reuse /avatar.jpg | Replace bytes at the same URL | Existing caches may continue serving the old version |
Publish /avatar-v2.jpg | Give the new bytes a new URL | New references request a different cache entry |
A public versioned image might return:
Cache-Control: public, max-age=86400
The header permits caching and sets a one-day freshness lifetime. Choose a long lifetime only when the update and removal rules support it.
Cache-Control: no-store addresses responses that shouldn’t be stored. no-cache generally permits storage but requires validation before reuse. Their difference is specified in HTTP caching rules.
Private content needs a different design
A publicly reusable photo and a personalized account response don’t have the same permission rules. A login cookie alone is not a universal safeguard against CDN sharing under every configuration.
- Make cacheability explicit.
- Separate public assets from personalized responses.
- Include every relevant response variation in the cache key.
- Define how private downloads are authorized.
- Treat signed download URLs as credentials while valid.
A shared cache that returns the wrong person’s response has made the system faster at exposing data. Correct reuse comes before maximizing hits.
Estimate bytes before choosing capacity
Assume a photo receives 10^6 views per day and each delivered image is 2 × 10^6 bytes:
transfer/day = 10^6 × 2 × 10^6
= 2 × 10^12 bytes
≈ 2 TB/day
Using about 10^5 seconds per day:
average bytes/second ≈ 2 × 10^12 / 10^5
= 2 × 10^7 bytes/second
average bits/second ≈ 2 × 10^7 × 8
= 1.6 × 10^8 bits/second
≈ 160 Mbps
Rounding 86,400 upward slightly underestimates the true average. Peak demand and protocol overhead need separate allowances.
At 90% cache hits, with equally sized images, origin delivery falls to roughly 0.2 TB per day. Viewers still receive the full 2 TB from the delivery network. The cache changed where bytes came from; it didn’t remove delivery to viewers.
What happens when you delete a photo?
Removal has several steps:
- Remove or deny access at the origin.
- Invalidate CDN entries where supported.
- Stop listing the photo in feeds.
- Account for browser copies and files already downloaded.
A purge cannot recall bytes someone has saved.
Why popular content benefits from edge caches
A few photos may attract many views while a long tail receives very few. That uneven popularity can make caching effective, but it needs measurement rather than a universal percentage assumption.
- Frequently reused public content is a good candidate.
- Rarely requested objects may continue to miss the cache.
- Private or rapidly changing content needs appropriate reuse rules.
- Caching image bytes doesn’t automatically reduce the database work of assembling a personalized feed.
The CDN reference architecture shows a concrete delivery path.
We began by giving a new server work. Following the entry point uncovered health, state, and failover. Following the response toward a distant viewer uncovered reuse and freshness. Each component addresses a particular part of that journey.
Previous: Storage from First Principles: Logs, Indexes, and Transactions. Next: Caching from First Principles: Policies, LRU, and Cache Tiers.