ArchitectMind
  1. Home
  2. Java Ecosystem
  3. Book 10 · Security, System Design & Solution Architecture
  4. Volume III
  5. Traffic Distribution
Book 10 · Volume III — Large-Scale & Distributed System Design · Topic 1.1

Traffic Distribution

Getting each user to the nearest healthy place that can serve them

22 min readStage 4 · Production & architecture10 interview questions
Chapter
Chapter 1 — High-Traffic Systems
Prerequisites
Volume II; Book 9 Volume VII
You will be able to
Design global and regional traffic distribution, choose routing policies, size TTLs and health checks for fast failover, use anycast where it helps, shift traffic safely for migrations and canaries, and monitor distribution quality
Covers
Traffic distribution
On this page
  1. 1. Concept / Definition
  2. 2. Why It Exists
  3. 3. Core Concepts — Routing Policies
  4. 4. How It Works Internally — DNS-Based Distribution
  5. 4A. Deep Dive — Anycast and Global Accelerator
  6. 4B. Deep Dive — Traffic Shifting for Change
  7. 4C. Deep Dive — Capacity-Aware Distribution
  8. 4D. Deep Dive — Residency-Aware Distribution
  9. 4E. Deep Dive — Failure Modes
  10. 5. APIs / Features / Syntax
  11. 6. Practical Examples
  12. 7. Common Problems & Mistakes
  13. 8. Performance & Production Considerations
  14. 9. Architecture & Design Considerations
  15. 10. Interview Questions & Answers

1Concept / Definition

Traffic distribution is the set of mechanisms that decide where each incoming request is served — which region, which edge location, which availability zone and ultimately which server. It spans from coarse, slow-changing global decisions (DNS routing to a region) down to fine, per-request decisions (a load balancer choosing a pod). Good distribution minimises latency, spreads load within capacity, avoids unhealthy locations and respects regulatory boundaries.

Layers of traffic distribution
Figure 1 — Layers of traffic distribution
Global traffic distribution — ShopNow
Figure 2 — Global traffic distribution — ShopNow
VocabularyMeaning
GSLBGlobal server load balancing — choosing a region/site
AnycastSame IP announced from many locations; BGP picks nearest
TTLHow long resolvers cache a DNS answer
Spill-overSending excess load to another region when one is full
Table 1 — Terms

2Why It Exists

Without deliberate distributionConsequence
All users hit MumbaiDubai users see +180 ms, Singapore +110 ms
No health-aware DNSRegional outage = global outage
Big-bang migrationsAll traffic moves at once; rollback impossible
No regional capacity awarenessOne region saturates while another idles
Table 2 — Why
ShopNow Global driverTarget
Latency for Gulf and SE Asia usersp95 page API < 150 ms
Regional failureService continues from other regions within 2 min
ResidencyIndian payment data stays in India
Table 3 — Drivers

3Core Concepts — Routing Policies

Routing policies
Figure 3 — Routing policies
PolicyShopNow use
Latency-basedshopnow.com → nearest of Mumbai, Hyderabad, Singapore
GeolocationPayments API for Indian cards → India regions only
WeightedMigrating catalog to a new cluster: 5% → 25% → 100%
FailoverNovaBank internet banking: Mumbai primary, Hyderabad secondary
MultivalueInternal service discovery for small fleets
Table 4 — Policy per endpoint

4How It Works Internally — DNS-Based Distribution

StepDetail
1. Client asks resolverISP or public resolver (8.8.8.8, 1.1.1.1)
2. Resolver asks authoritative (Route 53)With EDNS client subnet when supported
3. Route 53 evaluates policy + healthLatency tables per AWS region, health check status
4. Answer with TTLe.g. 60 s
5. Resolver and OS cache answerMany clients ignore short TTLs → slower failover
6. Client connects to region endpointRegional LB/edge
Table 5 — DNS routing flow
Timing factorTypical valueEffect on failover
Health check interval × threshold10 s × 3~30 s to detect
DNS TTL60 sUp to 60 s more for well-behaved resolvers
Stubborn cachesMinutesLong tail of traffic to failed region
Table 6 — Why DNS failover is minutes, not seconds

4ADeep Dive — Anycast and Global Accelerator

AspectDNS routingAnycast (Global Accelerator)
Decision pointResolver/DNSBGP at network edge
Failover speedTTL-bound (minutes)Seconds (health-based endpoint weights)
Client IPsChange per regionTwo static anycast IPs
PathPublic internet to regionEnters AWS backbone at nearest edge
UseWeb, most APIsPayment APIs, gaming, allow-listed IPs
Table 7 — Faster, steadier distribution

4BDeep Dive — Traffic Shifting for Change

TechniqueMechanism
Weighted DNSShift % of new resolutions between endpoints
Global Accelerator traffic dialsPer-region percentage (0–100%)
ALB weighted target groupsBlue/green within a region
Header/cookie routingInternal testers to new stack
RollbackSet weight back to 0 — seconds (GA), TTL-bound (DNS)
Table 8 — Canaries and migrations

4CDeep Dive — Capacity-Aware Distribution

SituationResponse
Region approaching capacityReduce its traffic dial; spill to neighbour
Region lostRemaining regions must absorb — N+1 regional capacity
Pre-planned peak (sale)Pre-scale all regions; pin users to home region
Cost optimisationWeight toward cheaper region when latency budget allows
Table 9 — Distribution follows capacity

4DDeep Dive — Residency-Aware Distribution

Data classRouting constraint
Indian payment data (RBI)Only India regions — geolocation + account home region
EU PayGrid merchantsEU data plane only
Public catalogAny region
User profileHome region; reads via replicas
Table 10 — Distribution must respect law

4EDeep Dive — Failure Modes

FailureMitigation
Health checks too sensitive (flapping)Multiple checkers, thresholds, evaluate deep health carefully
Health checks too shallowCheck a synthetic transaction, not just /ping
Thundering herd on failoverPre-scaled standby, gradual dials, client jitter
Stale DNS cachesShort TTL + anycast for critical APIs
Correlated dependency failureHealth checks include critical dependencies (with care)
Table 11 — Distribution under stress

5APIs / Features / Syntax

HCL
# Route 53 latency-based records with health checks (Terraform)
resource "aws_route53_health_check" "mumbai" {
  fqdn              = "api-aps1.shopnow.com"
  type              = "HTTPS"
  resource_path     = "/health/deep"
  request_interval  = 10
  failure_threshold = 3
  regions           = ["ap-south-1", "ap-southeast-1", "eu-west-1"]
}
resource "aws_route53_record" "api_mumbai" {
  zone_id         = var.zone_id
  name            = "api.shopnow.com"
  type            = "A"
  set_identifier  = "mumbai"
  health_check_id = aws_route53_health_check.mumbai.id
  latency_routing_policy { region = "ap-south-1" }
  alias {
    name                   = aws_lb.aps1.dns_name
    zone_id                = aws_lb.aps1.zone_id
    evaluate_target_health = true
  }
}
JAVA
// Deep health endpoint: healthy only if this region can actually serve checkout
@RestController
class DeepHealth {
    @GetMapping("/health/deep")
    ResponseEntity<Map<String, String>> deep() {
        var checks = Map.of(
            "db", probe(() -> jdbc.sql("SELECT 1").query(Integer.class).single()),
            "cache", probe(() -> redis.opsForValue().get("health")),
            "capacity", admission.acceptingTraffic() ? "ok" : "draining");
        boolean ok = checks.values().stream().allMatch("ok"::equals);
        return ResponseEntity.status(ok ? 200 : 503).body(checks);
    }
}
BASH
# Global Accelerator traffic dial: drain Singapore to 0% during an incident
aws globalaccelerator update-endpoint-group \
  --endpoint-group-arn "$SINGAPORE_ENDPOINT_GROUP_ARN" \
  --traffic-dial-percentage 0

6Practical Examples

6.1 ShopNow Global launch

Gulf users were served from Mumbai with p95 of 310 ms. Adding Singapore and Hyderabad with latency-based routing cut Gulf p95 to 140 ms (Mumbai stays nearest for Gulf, but Hyderabad absorbs Indian traffic, freeing capacity) and SE Asia p95 to 90 ms.

6.2 NovaBank failover

Internet banking uses failover routing with deep health checks; a drill showed 95% of traffic moved to Hyderabad in 2 min 10 s, with a tail from resolvers ignoring TTL — so the mobile app additionally carries both regional endpoints and switches on repeated failures.

6.3 PayGrid static IPs

Merchants allow-list IPs, so PayGrid uses Global Accelerator: two static anycast IPs, per-region endpoint groups, and 20-second failover.

6.4 Worked example — failover time

Scenario. ShopNow's leadership asked how long customers would be affected if the Mumbai region failed and DNS had to move traffic to Hyderabad.

ComponentSeconds
Detect (10 s × 3)30
DNS TTL60
Total (well-behaved)~90
Table 12 — Budget

What it shows. The failover time budget adds up each stage. Route 53 health checks run every 10 seconds and need three consecutive failures, so detection takes about 30 seconds. The record's TTL is 60 seconds, so well-behaved resolvers pick up the new answer within another minute. The total for well-behaved clients is about 90 seconds. Some resolvers and clients cache longer than the TTL, so a small share of users may take several minutes. Writing the budget down gave leadership a realistic number and showed which levers, such as a shorter TTL or Global Accelerator, could reduce it.

Common mistake. Quoting the TTL alone as the failover time, ignoring detection time and resolvers that cache longer than the TTL.

Takeaway. Calculate failover time end to end, from detection through caching, and use it to choose the right routing tool.

6.5 Worked example — weighted migration

Scenario. ShopNow was moving its API from an old EKS cluster to a new one and could not risk a big-bang switch.

DayNew cluster weight
15%
325%
7100%
Table 13 — Gradual shift

What it shows. Weighted routing shifts traffic gradually. On day one, the new cluster receives 5% of requests, enough to reveal problems while limiting impact. After error rates and latency stay healthy, the weight increases to 25% on day three and reaches 100% on day seven. At each step, the team compares metrics between clusters. If anything goes wrong, setting the weight back to zero returns all traffic to the old cluster within the TTL. The migration completed with no customer-visible incident, and the old cluster was kept as a fallback for one more week.

Common mistake. Moving all traffic at once, so any problem affects every user immediately.

Takeaway. Migrate traffic in small, measured steps with a quick rollback path.

6.6 Worked example — spill-over

Scenario. During a festival sale, the Mumbai region approached its capacity limit while Hyderabad still had room.

Region loadAction
Mumbai 90% capacityDial Mumbai 80%, Hyderabad absorbs
Table 14 — Capacity-aware

What it shows. Capacity-aware spill-over moves excess load before it causes failures. When Mumbai reached 90% of capacity, operators reduced its traffic dial to 80%, and Hyderabad absorbed the remaining share. Users in Mumbai's area saw a few extra milliseconds of latency instead of errors or throttling. After the peak, the dial returned to normal. The team later automated the dial based on regional utilisation, so spill-over now happens within a minute without manual action.

Common mistake. Waiting for a region to fail under load before moving traffic.

Takeaway. Use traffic dials to spill excess load to other regions before capacity runs out.

6.7 Worked example — interview whiteboard

Scenario. In interviews, ShopNow asks: "How do you route global users to your service?"

PromptAnswer outline
"How do you route global users to your service?""Layered: DNS/GSLB (Route 53 latency or geo, with deep health checks and 60 s TTL) or anycast (Global Accelerator) for fast failover/static IPs; CDN edge for cacheable content; regional LBs across AZs; ingress/mesh inside. Policies per endpoint: latency for general, geo for residency, weighted for migrations, failover for active-passive. Size for N+1 regions; pre-scale for peaks; drain with traffic dials. Watch DNS cache tails, flapping, thundering herds. Monitor traffic and latency by user geography."
Table 15 — Structured answer

Why it works. The outline describes layers. At the top, DNS or global server load balancing such as Route 53 chooses a region using latency or geolocation policies, with deep health checks and sensible TTLs. Anycast services such as Global Accelerator or CloudFront provide fast failover and stable IPs where needed. Within a region, load balancers distribute requests across zones and instances, and the service mesh handles service-to-service traffic. The answer also covers capacity planning, residency rules and monitoring of real user latency. Interviewers hear a complete, layered design with clear trade-offs.

Common mistake. Answering only "use a load balancer", which covers one layer and ignores global routing.

Takeaway. Explain traffic distribution as layers from global DNS to local load balancing.

6.8 Worked example — residency routing

Scenario. PayGrid must keep card payment data for Indian merchants within India under RBI rules.

RequestRegion
Card payment, Indian merchantMumbai/Hyderabad only
Table 16 — Compliance

What it shows. Residency routing ensures card payment requests for Indian merchants are served only by the Mumbai and Hyderabad regions. Geolocation and merchant home-region routing send these requests to Indian endpoints, and the services there store data locally. Even if a user travels abroad, their merchant's payments stay in India. Failover is configured only between the two Indian regions, never to Singapore, so a disaster does not cause a compliance breach. Auditors can see the routing rules and failover pairs in the configuration repository.

Common mistake. Using pure latency-based routing, which could send regulated requests to a region outside the country.

Takeaway. Combine routing policies with residency rules, including during failover.

6.9 Worked example — anti-patterns

Scenario. A review of ShopNow's earlier routing setup found several weaknesses that would have hurt during an outage.

Anti-patternEffect
Shallow /ping health checksRoute to broken regions
TTL 86,400 sFailover takes a day
No spare regional capacityFailover causes second outage
Single global endpointLatency for distant users
Table 17 — Common mistakes

What it shows. The table names them. Shallow /ping health checks reported regions as healthy even when the database behind them had failed, so traffic kept going to broken regions. A TTL of 86,400 seconds meant failover could take a full day. Regions without spare capacity would collapse when they received a failed region's traffic. The fixes were deep health checks that test real dependencies, a 60-second TTL and N+1 capacity planning. A later regional drill completed failover in under two minutes.

Common mistake. Testing failover only on paper, so these weaknesses are discovered during a real incident.

Takeaway. Use deep health checks, short TTLs and spare capacity, and prove them with drills.

6.10 Worked example — EDNS client subnet

Scenario. ShopNow saw some users in Delhi being routed to Singapore even though Indian regions were closer.

Without ECSWith ECS
Routed by resolver locationRouted by user subnet
Table 18 — Accuracy

What it shows. Without EDNS Client Subnet, Route 53 sees only the location of the user's DNS resolver, which may be a public resolver far away. With ECS, supported resolvers pass part of the user's IP subnet, so routing decisions use the user's real location. After checking ECS support for the main resolvers used by their customers and reviewing latency data, ShopNow confirmed that most mis-routed users now reached the nearest region.

Common mistake. Assuming DNS routing always knows where the user is.

Takeaway. Understand how DNS sees user location, and check routing accuracy with real data.

6.11 Worked example — mobile endpoint list

Scenario. ShopNow's mobile app kept failing for some users during a DNS-based failover, because their devices cached old answers.

App configBehaviour
Primary + secondary API hostsSwitch after 3 failures
Table 19 — Client-side distribution

What it shows. Client-side distribution adds a second path. The app's configuration lists a primary and a secondary API host. If three requests to the primary fail, the app switches to the secondary and retries periodically before switching back. This recovers users within seconds instead of waiting for DNS caches to expire. The configuration is delivered remotely, so hosts can be changed without releasing a new app version.

Common mistake. Relying only on DNS for mobile clients that may cache answers for a long time.

Takeaway. Give clients a fallback endpoint so they can recover without waiting for DNS.

6.12 Worked example — health check regions

Scenario. A network problem near one health checker once caused ShopNow's healthy region to be marked as failed.

CheckersReason
3+ checker regionsAvoid false positives
Table 20 — Reliability

What it shows. Health checks run from at least three checker regions, and a region is declared unhealthy only when a majority agree. A problem near one checker no longer triggers a false failover. Route 53 supports this by letting you choose checker regions and the failure threshold. The team also alerts when checkers disagree, which often reveals a real network issue worth investigating.

Common mistake. Using a single health checker, which turns its own problems into false failovers.

Takeaway. Use multiple independent checkers and majority decisions for health.

6.13 Worked example — geoproximity bias

Scenario. ShopNow wanted more Indian traffic to go to Hyderabad, where it had added capacity.

BiasEffect
+20 on HyderabadPull more Indian traffic there
Table 21 — Tuning

What it shows. Geoproximity routing allows a bias that expands or shrinks a region's catchment area. A bias of +20 on Hyderabad pulled more Indian traffic there without forcing all users to change regions. Latency monitoring confirmed that users moved to Hyderabad still had good response times. The bias can be adjusted gradually as capacity changes, which is safer than switching routing policy entirely.

Common mistake. Making large bias changes at once, which can suddenly overload a region.

Takeaway. Tune geoproximity bias gradually and verify with latency and capacity metrics.

6.14 Worked example — canary region

Scenario. ShopNow wanted to release a risky change to its multi-region API safely.

ReleaseRegion order
Singapore → Hyderabad → MumbaiSmallest blast radius first
Table 22 — Safe rollout

What it shows. Releases follow a canary region order: Singapore first, because it has the smallest share of traffic, then Hyderabad, then Mumbai, the largest region. After each step, the team waits and checks error rates and latency before continuing. If Singapore shows a problem, only a small group of users is affected and the release stops there. This limits the blast radius of bad changes.

Common mistake. Releasing to all regions at the same time.

Takeaway. Roll out region by region, starting with the smallest blast radius.

6.15 Worked example — internal traffic

Scenario. Inside a region, ShopNow's service-to-service traffic was crossing zones frequently, adding latency and data transfer costs.

TrafficDistribution
Service → serviceMesh, zone-aware
Table 23 — Inside region

What it shows. Internal traffic is distributed by the service mesh with zone-aware routing: calls prefer instances in the same availability zone and cross zones only when local capacity is unhealthy or overloaded. Average internal latency fell, and the monthly cross-zone data transfer bill dropped noticeably. Failover to other zones still works automatically when a zone has problems.

Common mistake. Treating internal traffic as free and ignoring zone placement.

Takeaway. Use zone-aware routing for internal traffic to reduce latency and cost while keeping resilience.

6.16 Worked example — interview follow-ups

Scenario. Interviewers at ShopNow follow up on DNS and anycast to test understanding.

Follow-upAnswer
"Why is DNS failover slow?"Detection + TTL + caches ignoring TTL
"When anycast?"Fast failover, static IPs, backbone routing
Table 24 — Common probes

Why it works. DNS failover is slow because it combines detection time, the record's TTL and resolvers or clients that cache answers longer than the TTL. Anycast announces one IP address from many locations, so network routing reaches the nearest healthy edge, and failover happens within the provider's network in seconds. Anycast suits critical APIs that need fast failover, stable IP addresses or backbone routing. Strong candidates explain both mechanisms and when each fits.

Common mistake. Claiming DNS failover is instant because the TTL is short.

Takeaway. Explain the mechanics behind each routing option and when to use them.

6.17 Worked example — checklist

Scenario. ShopNow reviews every public endpoint against a traffic distribution checklist.

Item✔
Policy per endpoint✔
Deep health checks✔
TTL sized✔
N+1 capacity✔
Traffic dials✔
Geo metrics✔
Table 25 — Distribution baseline

What it shows. The checklist confirms a routing policy per endpoint, deep health checks, a TTL sized for the failover target, N+1 regional capacity, traffic dials for manual control and geographic latency metrics. Endpoints missing an item get actions before launch. During the next regional drill, every reviewed endpoint failed over within its target. The checklist is also re-run whenever an endpoint's traffic pattern or criticality changes.

Common mistake. Applying the checklist only to the main website and forgetting APIs used by partners or mobile apps.

Takeaway. Review every public endpoint with the same traffic checklist.

6.18 Worked example — latency map

Scenario. ShopNow wanted to detect routing problems before customers complained.

MetricUse
RUM latency by countryDetect mis-routing
Table 26 — Observability

What it shows. Real user monitoring collects latency by country and city from actual browsers and apps. A latency map highlights places where users suddenly see higher latency, often a sign of mis-routing. When users in the Middle East started reaching Mumbai instead of the nearer edge, the map showed it within an hour, and a routing configuration error was fixed. The same data also helped choose where to add the next edge location.

Common mistake. Relying only on server-side metrics, which cannot see the user's real experience.

Takeaway. Use real user latency by geography to detect routing problems early.

6.19 Worked example — DDoS

Scenario. ShopNow's public endpoints were a target for large DDoS attacks during big sales.

LayerProtection
Anycast edges + ShieldAbsorb floods near source
Table 27 — Security

What it shows. Anycast edges with AWS Shield absorb floods close to their source. Because the same IP is announced from many edge locations, attack traffic is spread across the provider's global network rather than concentrated on one region. WAF rules at the edge filter application-layer attacks. A large attack during one sale was absorbed with no noticeable impact on customers.

Common mistake. Exposing regional load balancers directly to the internet, so attacks hit the region head-on.

Takeaway. Use anycast edges and DDoS protection to absorb attacks before they reach your regions.

6.20 Worked example — cost

Scenario. ShopNow considered putting all traffic behind Global Accelerator.

ChoiceImpact
Global Accelerator per-GB feeUse for critical APIs only
Table 28 — Economics

What it shows. The cost review showed that Global Accelerator charges a per-GB fee in addition to normal data transfer. For high-volume static content, CloudFront was cheaper and faster. For critical APIs, such as checkout, the faster failover and backbone routing justified the fee. ShopNow used Global Accelerator only for those APIs, saving money while keeping the benefit where it mattered. The decision is reviewed yearly as traffic volumes and prices change.

Common mistake. Applying a premium routing service to all traffic without checking cost.

Takeaway. Use premium routing features where their benefit justifies the cost.

6.21 Worked example — interview scenario

Scenario. In an interview, ShopNow asks: "A region fails during a sale. What happens?"

QuestionAnswer
"Region fails during sale"Health check fails → DNS/GA shift; others pre-scaled; shed low priority
Table 29 — Apply

Why it works. A strong answer walks through the sequence. Health checks fail, and DNS or Global Accelerator shifts traffic to the surviving regions. Those regions are already scaled with spare capacity, so they can absorb the load. If capacity is still tight, low-priority features, such as recommendations, are switched off to protect checkout. The candidate also mentions communication, monitoring and failing back once the region recovers.

Common mistake. Saying only "traffic moves to another region" without capacity or degradation plans.

Takeaway. Describe the full failover sequence, including capacity and graceful degradation.

6.22 Worked example — sticky region

Scenario. ShopNow's signed-in customers occasionally saw missing cart items when requests switched between regions.

UserHome region
Signed-in customerPinned for data locality (cookie + routing)
Table 30 — Consistency aid

What it shows. Sticky home regions keep a signed-in customer pinned to one region for data locality, using a cookie and routing rules. Their cart and session data live in that region, so every request finds the latest data. If the home region fails, customers move to another region, where data is replicated with a short delay. Missing cart items dropped to almost zero in normal operation.

Common mistake. Routing each request independently for users whose data lives in one region.

Takeaway. Pin users to a home region when data locality matters, with planned failover.

6.23 Worked example — maintenance

Scenario. ShopNow needed to upgrade networking in the Hyderabad region without affecting customers.

ActionTool
Drain region for upgradeDial to 0, wait for connections
Table 31 — Operations

What it shows. Draining a region is a planned operation. The traffic dial for Hyderabad is set to zero, so new requests go elsewhere. Operators wait for existing connections to finish, watching connection counts fall. Only then does the upgrade start. Afterwards, the dial is raised gradually back to normal. Customers saw no impact, and the runbook is reused for every regional maintenance.

Common mistake. Starting maintenance while traffic is still flowing to the region.

Takeaway. Drain traffic with dials and wait for connections to finish before maintenance.

6.24 Worked example — flapping

Scenario. ShopNow's Singapore region kept switching between healthy and unhealthy every minute during a network problem.

SymptomFix
Region toggles every minuteRaise threshold; hysteresis
Table 32 — Stability

What it shows. Flapping happens when a region is close to the health threshold, so small changes flip its status. The fix was to raise the failure threshold and add hysteresis: a region must fail several checks to be removed and pass several checks to return. Traffic stopped bouncing, and users had a stable experience while the network issue was resolved.

Common mistake. Using very sensitive health checks without hysteresis, which causes instability.

Takeaway. Add thresholds and hysteresis so routing is stable during partial problems.

6.25 Worked example — synthetic probes

Scenario. ShopNow's internal monitoring showed everything healthy, but some customers abroad reported failures.

ProbeFrom
Checkout syntheticDubai, Singapore, Delhi
Table 33 — Outside-in view

What it shows. Synthetic probes run real checkout journeys from Dubai, Singapore and Delhi, giving an outside-in view similar to customers'. They detected that an edge configuration change had broken checkout for users in the Middle East. Internal metrics had not shown it because those requests never reached the region. The change was rolled back within minutes. Probe results also feed the status page, so customers and support teams see the same picture as engineers.

Common mistake. Testing only from inside your own network.

Takeaway. Run synthetic probes from the locations where your customers are.

6.26 Worked example — documentation

Scenario. During an incident, on-call engineers struggled to remember how each endpoint was routed.

EndpointPolicyTTL
api.shopnow.comLatency + health60 s
Table 34 — Runbook

What it shows. The runbook documents each endpoint's routing policy and TTL, for example api.shopnow.com uses latency routing with health checks and a 60-second TTL. It also lists the traffic dials, failover regions and owners. Engineers now find the information in seconds, and changes to routing are reviewed against the documentation. After each drill or incident, the runbook is reviewed and corrected where reality differed from the documentation.

Common mistake. Keeping routing knowledge only in the console or in people's memory.

Takeaway. Document routing configuration in runbooks and keep it up to date.

7Common Problems & Mistakes

MistakeFix
Shallow healthDeep checks
Long TTLs60 s or anycast
No spare capacityN+1
Big-bang cutoversWeights
Table 35 — Mistakes and fixes

8Performance & Production Considerations

ConsiderationPractice
Latency by geographyRUM
Failover drillsQuarterly
Health check tuningReview
Table 36 — Operating distribution

9Architecture & Design Considerations

GuidelineDetail
Layered, health-awareEvery tier
Policy per endpointLatency, geo, failover
Plan capacity for lossN+1 regions
Table 37 — Design guidance

10Interview Questions & Answers

Q1L1 · BasicConcept

What is traffic distribution?

Traffic distribution is the set of decisions that determine which region, edge location and server handles each request. It works in layers: DNS or global load balancing chooses a region, anycast edges and CDNs serve users close to them, regional load balancers spread requests across availability zones and instances, and service meshes route internal calls. Good traffic distribution improves latency, availability and cost, and supports failover, migrations, maintenance and data residency requirements. Each layer has its own failure modes and tuning options, so designs should state clearly how traffic is steered at every level and how it is moved when something fails.

Q2L1 · BasicConcept

Name DNS routing policies.

Route 53 offers several routing policies. Simple routing returns one answer. Weighted routing splits traffic by percentage, useful for migrations. Latency routing sends users to the region with the lowest measured latency. Geolocation routing chooses by the user's country or continent, useful for residency. Geoproximity routing chooses by distance, with an adjustable bias. Failover routing sends traffic to a standby when the primary is unhealthy. Multivalue answer routing returns several healthy addresses. Policies can be combined in a hierarchy, for example latency routing between regions with failover inside each, to meet several goals at once.

Q3L2 · IntermediateInternals

Why is DNS failover slow?

DNS failover is slow because several delays add up. Health checks need time to detect a failure, often tens of seconds. The record's TTL then determines how long resolvers keep the old answer. Some resolvers, operating systems and applications cache answers for longer than the TTL. Connections that are already open may also keep using the failed endpoint. Together, this can mean minutes rather than seconds for some users. This is why critical services combine DNS with anycast, client-side fallback or connection draining, and why failover time should be measured end to end in drills rather than assumed from the TTL.

Q4L2 · IntermediateInternals

What is anycast?

Anycast is a networking technique where the same IP address is announced from many locations. Internet routing delivers each user's packets to the nearest location, in network terms. If one location fails, routing sends traffic to the next nearest one, usually within seconds. Services such as AWS Global Accelerator and CloudFront use anycast to provide stable IP addresses, fast failover and DDoS absorption close to the source. Unlike DNS, anycast does not depend on resolver caching, so failover is faster and more predictable, although it is mainly offered by large networks and cloud providers.

Q5L3 · Senior EngineerDesign

What makes a good health check?

A good health check tests whether the region can actually serve users, not just whether a web server responds. It should exercise key dependencies, such as the database and cache, through a lightweight synthetic request. Checks should run from multiple independent locations, with thresholds that avoid false failures and hysteresis to avoid flapping. Results should be monitored and alerted on, and checks must be fast and cheap enough not to add load. Poor health checks are a common cause of outages, because they route users to broken regions.

Q6L3 · Senior EngineerScenario

How migrate traffic safely?

Use weighted routing to move a small percentage of traffic, such as 5%, to the new target, and compare error rates, latency and business metrics with the old target. Increase the weight in steps when results are healthy, pausing long enough to see problems. Keep the old target running and ready, so setting its weight back to 100% is a quick rollback. Communicate each step and keep TTLs short during the migration. Automate the steps where possible, with automatic rollback when error rates or latency exceed agreed thresholds.

Q7L4 · Technical ArchitectDesign

How handle residency in routing?

Handle residency by routing regulated requests only to compliant regions. Use geolocation routing or a home region assigned per customer or merchant, so their data is processed and stored in the right country. Configure failover only between compliant regions, never to a region outside the jurisdiction. Store routing rules as code, monitor where requests are served, and include residency checks in audits and architecture reviews. Residency requirements should be captured as explicit drivers, so routing, storage, backups and disaster recovery designs all respect them consistently rather than each team interpreting the rules differently.

Q8L4 · Technical ArchitectConcept

What is spill-over?

Spill-over is a technique for handling load near a region's capacity limit. Instead of letting the region become overloaded, some of its traffic is moved to another region with spare capacity, usually by adjusting traffic weights or dials. Users moved may see slightly higher latency, but they avoid errors. Spill-over can be manual during events or automated using utilisation metrics, and the receiving region must have enough headroom. Spill-over plans should be tested before peak events, so operators know the exact steps and their effects.

Q9L5 · Solution ArchitectEstimation

How size regions for failover?

Size regions using N+1 planning: if any one region fails, the remaining regions must be able to handle its traffic in addition to their own. For two regions, each normally runs at no more than about half of its capacity. Account for peak events, autoscaling speed, service quotas and dependencies such as databases. Test the plan with failover drills and load tests, and review it as traffic grows. Without N+1 capacity, failover simply moves an outage from one region to another, because the surviving regions collapse under the extra load.

Q10L5 · Solution ArchitectTrade-off

When use Global Accelerator?

Use AWS Global Accelerator for critical APIs that need static IP addresses, for example for partner allow-lists, very fast regional failover without waiting for DNS caches, or better performance through the AWS backbone network. It also absorbs DDoS traffic at the edge. Because it adds a per-GB charge, it is usually reserved for important, latency-sensitive traffic, while static content stays on CloudFront. For most other traffic, DNS routing with health checks is simpler and cheaper, so the choice should be made per endpoint based on failover targets, client needs and cost.

Test your knowledge on this topic →Flashcards from this topic's 10 questions, filtered by level and type.

Free question pack

Get 100 free Core Java interview questions

Subscribe for the Book 1 question pack (PDF, every answer explained) and new tutorials once a week. No spam, unsubscribe anytime. What is in the pack?

Almost done! Check your inbox and click the confirmation link. Your download link arrives as soon as you confirm.