Distance is delay. No amount of code makes light travel faster through fiber, so a request from London to a server in Virginia always pays tens of milliseconds each way. To be fast globally you move servers and data closer to users. A global system also has many moving parts, so this note covers the patterns for when calls between them fail, too.
Data locality#
Performance is best when the user, the compute and the data are physically close to each other.
- Regional deployment: keep web servers and their database in the same region (for example
us-east). If servers are in New York and the database is in Los Angeles, every query pays a cross-country round trip of roughly 60 ms. - Availability zones (AZs): separate data centers in the same metro area, linked by fast private fiber (around a millisecond apart). Spreading across AZs means one building losing power doesn't take you down, without a noticeable latency cost.
- Multi-region: run copies of your stack in several regions (say London, Tokyo and New York) and send each user to the nearest one. Replicate data into those regions so a London user isn't waiting on a database in New York to load their profile.
Content delivery networks (CDNs)#
Running your full stack in many regions is expensive. For content that many users share, a CDN gets it close to them for you. A CDN is a global network of edge servers in hundreds of cities. Instead of every user connecting to your origin (your own servers), they connect to a nearby edge location.
- First request: the edge doesn't have the file, so it fetches it from the origin and caches a copy.
- Next requests: later users in that city get the file straight from the edge, in a few milliseconds instead of a long trip to the origin.
- Dynamic content: for requests that can't be cached, edges keep warm, pre-established connections to the origin and route over optimized paths. CDN vendors often call this dynamic site acceleration.
- Origin shield: an extra caching tier between edges and origin, so a cache miss in many cities at once becomes a single request to your origin rather than a stampede (a flood of identical requests hitting it at the same moment).
What to put on a CDN:
- Static assets: images, CSS, JavaScript, video. Video platforms rely heavily on CDNs.
- Slow-changing data: product catalogs, public profiles, popular search results.
- Anything for a global audience far from your main data center.
Benefits: lower round-trip time, far less load on your origin (it no longer serves the same logo millions of times), and some resilience, because edges can keep serving cached content during a brief origin outage.
Stale content: if you update a file but the CDN still has the old copy, users see old content. Fix it with versioned file names (style.v2.css, image_v2.png) so a new version is a new URL, or by purging the cache.
In short, the origin and the edge do different jobs:
| Origin server | CDN edge | |
|---|---|---|
| Where | One or a few data centers | Hundreds of cities |
| Serves | Dynamic data, the source of truth | Static and cacheable content |
| Speed for distant users | Slow | Consistently fast |
How users reach the nearest edge#
All of this depends on users landing on an edge near them. A CDN has two jobs before it serves a byte: steer each user to a good edge, and keep connections cheap.
- Anycast via BGP: every edge location announces the same IP address to the internet with BGP, the protocol routers use to exchange routes. Each router picks the best path it knows, so a user's packets reach a nearby edge. "Nearby" means the best network path (fewest hops or best policy), not always the shortest physical distance. If one location goes offline, it stops announcing the address and traffic flows to the next best one.
- DNS-based steering: some CDNs instead return a different edge IP depending on where the DNS query comes from. This works well when the user's resolver is near the user. See DNS.
- Placement at IXPs: CDNs put servers at internet exchange points, the buildings where many ISPs connect and swap traffic. From there, an edge is one short hop from many ISPs' users, and the CDN avoids paying for long transit routes.
- TLS connection reuse: a TLS handshake costs extra round trips. The user's handshake ends at the nearby edge, so those round trips are short. The edge then keeps a pool of open, already-encrypted connections to the origin and reuses them for many users' requests.
Caching dynamic and personalized pages#
Getting users to an edge is half the work. The other half is deciding what the edge may cache. Static files are easy, but pages that mix shared and per-user content need more care, or one user's data can leak to another.
- Cache key: the CDN stores each response under a key, usually the host and path, and optionally the query string. Two requests with the same key get the same cached response. Add a header or cookie to the key only when the response varies by it. Every extra part of the key splits the cache into more copies and lowers the hit ratio.
- Bypass on headers and cookies: configure the CDN to skip the cache when a request carries a session cookie or an
Authorizationheader. Those requests go to the origin, so a personalized dashboard is never served to the wrong user. - Short TTLs for semi-dynamic data: headlines, scores and search results can be cached for a few seconds. Even a short TTL absorbs most of the load in a traffic spike.
- Edge-Side Includes (ESI): a markup language that splits a page into fragments. The edge caches the shared layout and navigation, and fetches only the personal fragments (for example, "Hello, Sam" and the cart count) from the origin. Not every CDN supports ESI.
- Never cache real-time data: a stock ticker or a chat stream must come from the origin on every request.
The most damaging CDN bug is caching a personalized response under a shared key. The next user sees someone else's account page. Mark per-user responses Cache-Control: private or no-store, and bypass the cache when a session cookie is present.
Browser cache and CDN cache#
The CDN isn't the only cache in the path. A request can be answered by two caches before it reaches your origin, and they form layers.
- Browser cache: if the browser holds a fresh copy (by
Cache-Control: max-ageorExpires), it uses that copy. No request leaves the device. - CDN edge cache: on a browser miss, the request goes to the edge. A hit is served from the edge.
- Origin: on an edge miss, the edge fetches from the origin (or the origin shield) and caches the result.
The browser copy wins while it is fresh. So purging the CDN does not update browsers that already hold a fresh copy. They keep the old file until their own max-age ends. This is another reason to use versioned file names for assets.
You can set different lifetimes for the two layers. max-age applies to every cache. s-maxage applies only to shared caches such as CDNs, and overrides max-age there:
Cache-Control: public, max-age=60, s-maxage=86400
Here browsers keep the file for 60 seconds and the CDN keeps it for a day. You can purge the CDN when the file changes, and browsers pick up the change within a minute.
Regional partitioning#
Multi-region copies the same data everywhere. When data only matters locally, you can go further and split the whole system into independent geographic "islands", sometimes called cells.
- The idea: a rider in Miami never needs to see drivers in Seattle. The data has natural geographic boundaries.
- Each region gets its own stack: load balancers, app servers and databases, all in a data center near its users.
- Good fits: ride-sharing (trips are local to a city), food delivery (restaurants within a few miles), local marketplaces.
Benefits:
- Speed: both user-to-server and server-to-database trips are short.
- Fault isolation: if one region's data center fails, other regions are untouched.
- Scalability: ten moderate databases are easier to run than one enormous global one.
Cells do raise one awkward case. The traveler problem: a Miami user flies to London. A global entry point, such as geo-aware DNS, routes them to the London cell, and you decide how their home-region data (profile, payment methods) follows them.
Here's how cells compare with keeping one global database:
| One global database | Regional partitioning | |
|---|---|---|
| User latency | High for users far away | Low everywhere |
| Complexity | Low | Higher: you must route users to the right region |
| Blast radius | One failure affects everyone | Contained to one region |
| Consistency | Easy | Hard for users or data that cross regions |
When things fail#
Regions, CDNs and cells all add network calls between parts of your system, and in a distributed system the network is unreliable. Calls will fail, hang or return errors, and your design must expect it.
1. Retries with exponential backoff and jitter#
For transient failures (a brief network blip, a momentary overload), retry.
- Exponential backoff: wait longer after each failure (1 s, 2 s, 4 s, 8 s…) instead of hammering a struggling server every second.
- Jitter: add randomness to each wait. Without it, thousands of clients that failed at the same moment retry at the same moment too, a thundering herd that acts like a self-inflicted denial-of-service attack.
- Cap the number of attempts and the maximum delay.
Here's all three in a small Python helper:
import random
import time
def call_with_retries(fn, max_attempts=5, base=0.5, cap=8.0):
for attempt in range(max_attempts):
try:
return fn()
except ConnectionError:
if attempt == max_attempts - 1:
raise
# "Full jitter": sleep a random time up to the
# exponential bound, so clients that failed
# together don't retry together.
bound = min(cap, base * 2 ** attempt)
time.sleep(random.uniform(0, bound))
2. Idempotency keys#
Retrying is dangerous when the call has side effects. Retry a payment and you might charge the customer twice. The fix is to make the operation idempotent: doing it twice has the same effect as doing it once.
- The client generates a unique idempotency key (a UUID) for the operation and sends it with every attempt.
- The server checks a fast store (often Redis or a database table) for that key.
- Not seen: process the request, then store the key with the result.
- Seen and finished: return the stored result without processing again.
- Seen but still in progress: reject or wait, so two attempts don't run at the same time.
This makes writes as safe to retry as reads.
3. Circuit breakers#
A cascading failure happens when one slow service makes its callers wait, their threads fill up, and they become slow too, until the whole system is stuck. A circuit breaker stops calling a service that is clearly failing. It moves between three states:
- Closed (normal): requests flow. The breaker counts errors.
- Open (tripped): once errors pass a threshold (say 50% over a window), every call fails fast without touching the struggling service, giving it time to recover.
- Half-open (testing): after a timeout (say 30 s), a few trial requests are allowed. If they succeed, the breaker closes. If they fail, it opens again.
What you do while the circuit is open depends on the operation:
| Scenario | Action when open | User experience |
|---|---|---|
| Reading a feed | Fallback: serve cached or slightly old data | Smooth; content is a little stale |
| Making a payment | Fail fast: "Try again in a minute" | Safe; no double charges or long hangs |
| Uploading data | Queue it for background processing | Delayed but accepted |
Summary#
Here are the three patterns side by side.
| Pattern | Problem it solves | How |
|---|---|---|
| Retries + backoff + jitter | Transient blips | Try again, waiting longer and randomly |
| Idempotency keys | Double processing on retry | One key, one result |
| Circuit breaker | Cascading failure from a dead or overloaded dependency | Stop calling it for a while; use a fallback |
Used together: retry transient errors with backoff and jitter, protect side effects with idempotency keys, and wrap each dependency in a circuit breaker with a sensible fallback.
Key takeaways#
- Latency is bounded by physical distance, so keep users, servers and data close together.
- Use multiple AZs for resilience within a region and multiple regions for global users.
- CDNs cache static and slow-changing content near users. Use versioned URLs to avoid stale files.
- CDNs reach users through anycast or DNS steering and edges at IXPs. Cache keys, cookie bypass and ESI keep personalized pages safe.
- A fresh browser copy wins over the CDN, so a CDN purge does not reach browsers until their
max-ageends. - Regional partitioning (cells) gives low latency and fault isolation when data is naturally local.
- Retries need exponential backoff with jitter, and side-effecting calls need idempotency keys.
- Circuit breakers stop one failing dependency from taking down everything that calls it.