Back to Terraform

Load Balancers, Health Monitors and AWS Origin Failover

November 6, 2026 Wasil Zafar 23 min read

Coordinate Cloudflare routing with independently managed origins and verify health-based traffic decisions

Table of Contents

  1. Separate DNS Routing, Proxying and Origin Balancing
  2. Create Monitor and Pool Contracts Before the Balancer
  3. Align Health Checks with TLS and Application Readiness
  4. Budget for Availability Features and Shared Account Resources
  5. Measure Failover and Recover the Original Route

Separate DNS Routing, Proxying and Origin Balancing

A request to app.example.com passes through two different balancers, and only one of them should choose the region. Think of a parcel network: Cloudflare is the national hub that decides which regional depot receives the parcel, and the AWS load balancer is the depot dispatcher that decides which van leaves. The hub cannot see the vans, and the depot cannot see the national network. When both try to choose a depot, parcels bounce.

Three decisions need three owners. Cloudflare DNS decides which address the client receives, the proxy decides whether requests traverse Cloudflare at all, Cloudflare Load Balancing chooses a pool, and the AWS ALB chooses a target inside that pool. The phrase "load balancer" hides four different jobs, which is why the same diagram can look correct and still have two controllers fighting.

DecisionOwnerInputEvidenceWrong owner looks like
Which edge and client TLSCloudflare zoneproxied record, edge certificatecf-ray, edge certificateorigin address exposed, no WAF or cache
Which region or poolCloudflare Load Balancingpool order plus monitor healthpool health, balancer analyticsfailover never fires, fallback serves
Which target and zoneAWS ALBtarget health plus listener ruletarget health, access logsCloudflare marks the ALB unhealthy
Which address for an origin nameCloudflare DNS, grey cloudCNAME to the ALBdig origin-a.example.comorange cloud yields DNS Internal
Which record answers the clientCloudflare Load Balancingbalancer hostnamedig app.example.coma second record keeps reappearing

A proxied balancer and a DNS-only balancer fail differently. Proxied traffic terminates at the edge, so the pool decision happens per request and a newly unhealthy origin stops receiving new requests within the monitor's detection window. DNS-only traffic returns origin addresses, so recovery is bounded by the record's TTL and by resolvers and clients that ignore it; the origin addresses are also visible.

The load balancer hostname owns its DNS record. When app.example.com is a balancer hostname, Cloudflare's load balancer record takes precedence over an A or CNAME with the same name, and that record is managed through the balancer rather than through a separate DNS resource. Declaring both in Terraform creates two owners for one name: the balancer wins at the API while the DNS resource keeps proposing an answer that is never used.

The AWS ALB owns target selection, not region selection. An ALB spreads requests across healthy targets in its target group, normally across Availability Zones, and its own health check decides membership. A Cloudflare pool should contain the ALB endpoint, not the individual targets behind it. If two Cloudflare pools point at two targets of the same ALB, Cloudflare is guessing at a decision the ALB already makes, and the ALB's TLS listener and host rules are bypassed.

Figure 1 separates the control planes: Cloudflare picks a pool and therefore a region, while the ALB picks a target and therefore a zone.

Separate DNS Routing, Proxying and Origin Balancing
%%{init: {'theme':'base','themeCSS':'.edgeLabel .label text, .edgeLabel text, .edgeLabel span { fill:#132440 !important; color:#132440 !important; }','themeVariables': {'primaryColor':'#16476A','primaryTextColor':'#ffffff','primaryBorderColor':'#132440','secondaryColor':'#3B9797','secondaryTextColor':'#ffffff','secondaryBorderColor':'#132440','tertiaryColor':'#c4873b','tertiaryTextColor':'#132440','tertiaryBorderColor':'#132440','lineColor':'#5a6e82','textColor':'#132440','titleColor':'#132440','mainBkg':'#16476A','nodeBorder':'#132440','clusterBkg':'#eef3f7','clusterBorder':'#132440','edgeLabelBackground':'#ffffff','actorBkg':'#16476A','actorTextColor':'#ffffff','actorBorder':'#132440','activationBkgColor':'#3B9797','activationBorderColor':'#132440','signalColor':'#5a6e82','signalTextColor':'#132440','noteBkgColor':'#c4873b','noteTextColor':'#132440','noteBorderColor':'#132440','labelBoxBkgColor':'#a8dede','labelBoxBorderColor':'#132440','labelTextColor':'#132440','loopTextColor':'#132440','altBackground':'#f8f9fa','fontFamily':'DM Sans, sans-serif'}}}%%
flowchart TD
    C["Client
app.example.com"] --> E{"Proxied?"} E -->|"yes"| P["Edge proxy
TLS · WAF · cache"] E -->|"no"| D["DNS answer
TTL-bound"] P --> L["Load balancer
chooses region"] D --> L L -->|"primary healthy"| A["Pool primary
ALB us-east-1"] L -->|"primary critical"| B["Pool secondary
ALB eu-west-1"] L -->|"all pools critical"| F["Fallback pool
health ignored"] L -->|"fallback disabled"| X1["530 / 1016
no last resort"] A --> AT["Target group
chooses AZ and target"] B --> BT["Target group
chooses AZ and target"] AT --> I1["Instance"] BT --> I2["Instance"] R["Route 53 failover
not in this path"] -.->|"do not duplicate"| L classDef primary fill:#132440,color:#ffffff,stroke:#0b172b; classDef secondary fill:#16476A,color:#ffffff,stroke:#0f314a; classDef ok fill:#3B9797,color:#ffffff,stroke:#2a6f6f; classDef danger fill:#BF092F,color:#ffffff,stroke:#7a0420; classDef warn fill:#c4873b,color:#132440,stroke:#8a5a1f; class C,L primary; class P,D,A,B secondary; class AT,BT,I1,I2 ok; class F,X1 warn; class R danger;

Duplicate ownership usually looks reasonable in a diagram. Two pools, two origins, two regions: the shape is right, but both origins are targets of one ALB, or both pools point at the same ALB name with different weights. That version doubles the blast radius instead of reducing it, because one ALB failure removes both pools. The independence test is concrete: if the two origins share an ALB, a target group or a certificate, they are not independent.

Route 53 is not a second failover layer in this design. The origin name can be a grey-clouded CNAME to the ALB, which is a static mapping, not a health policy. Adding a Route 53 failover record beneath the Cloudflare load balancer creates a second health decision with different thresholds and no shared evidence; when the two disagree, the outer layer wins and the inner one is invisible.

Figure 2 draws the same boundary as regions: the Cloudflare side owns the choice of region, and each AWS region owns the choice of target.

Who chooses the region and who chooses the target Client app.example.com Cloudflare boundary — one zone, one account Edge proxy TLS · WAF · cache Load balancer pool order · health Fallback pool health ignored AWS us-east-1 — primary ALB Target group Instance chooses Availability Zone and target ALB checks /healthz on the target ACM certificate per region AWS eu-west-1 — secondary ALB Target group Instance chooses Availability Zone and target same contract, independent failure no shared ALB or certificate Anti-pattern: two pools → two targets behind one ALB. One ALB failure removes both pools.

Create Monitor and Pool Contracts Before the Balancer

Create the monitor, then the pools, then the balancer. The dependency is also the ownership boundary: a monitor is account-scoped, a pool is account-scoped and references a monitor, and a balancer is zone-scoped and references pools. Terraform encodes that order in the graph, but the graph does not validate that the three contracts agree on host, port and path.

ResourceScopeRequired identityContract that mattersChange behavior
cloudflare_load_balancer_monitoraccountaccount_idtype, port, path, expected codes, interval, timeout, consecutive countsone edit reaches every pool that references it
cloudflare_load_balancer_poolaccountaccount_id, unique nameorigins, monitor, minimum origins, steeringorigin edits apply in place
cloudflare_load_balancerzonezone_id, hostnameordered default pools, fallback, steering, proxy statusorder changes priority immediately
cloudflare_dns_record for an originzonerecord namegrey CNAME to the ALBorange cloud breaks endpoint checks

Version 5 changed the shape of these resources, so old examples fail at plan. A monitor now requires an account identifier and uses consecutive down and up counters rather than the older failure-count names.

The pool schema changed too. A pool takes origins as a list of objects, and each origin's header is a host list rather than a pool-level map; a v4-era nested origin block is not a schema the pinned provider accepts.

Read the schema you pinned, not the example you saved. With Terraform CLI 1.17.1 and cloudflare/cloudflare 5.28.1, the provider schema command shows the selected attributes and whether an argument is computed or required. The schema is the contract for an apply; a blog post is only a hint about which contract once existed.

The monitor is a template, not a per-pool setting. Its interval, timeout, path and expected codes apply to every pool that references it. Changing one monitor therefore changes production and lab health at the same time, and the plan shows a single in-place update that says nothing about the number of pools affected.

minimum_origins is a pool threshold, not a per-origin switch. With one origin in a pool, set it to one; the pool is healthy while that origin passes and critical when it fails. With two origins, one tolerates a single loss, while two makes any single loss take the whole pool out of service. Choose the number from the failure you intend to survive, not from the number of origins you happened to create.

steering_policy = "off" means ordered failover, not "no steering". Pools are used in default_pools order, and an unhealthy pool is skipped. A latency policy would choose the closest pool per user rather than preserve an ordered active-passive preference, which is a different availability and cost decision; it also makes an active-passive rehearsal produce ambiguous evidence.

The fallback pool ignores health. It is the pool of last resort, so it receives traffic even when it is failing. Make it a static maintenance response or a third, independently managed origin, and never the primary pool under another name. If every pool is critical and the fallback is disabled, a proxied hostname returns a 530 with a 1016 origin DNS failure, not a clean 503.

Zero-downtime failover is a retry, not a health decision. Between probes, Cloudflare can retry a request that returns 521, 522, 523, 525 or 526 against another healthy origin, and adaptive_routing can extend that retry across pools. It does not replace the monitor: the retry covers a transient connection failure, while the monitor decides whether the pool stays in rotation.

Session affinity changes what "recovered" means. With no affinity, the next request after recovery can return to the primary immediately. With cookie or header affinity, an existing session stays on the secondary until its TTL or until the origin is drained; drain is available only on proxied balancers. Do not enable stickiness to compensate for a health check that is testing the wrong path.

Terraform completion is not pool health. Apply returns when the API accepts the monitor, pools and balancer, and the pool status is unknown until probes have run. The first probes may fail while a certificate propagates or a security group change settles, so a green apply followed by an unhealthy pool is an ordering problem before it is a configuration error.

Name pools by role, and write the order explicitly. A count ties identity to an index, so inserting a pool in the middle silently moves the primary. A for_each keyed by role keeps the resource address stable, but the priority still lives in an ordered list and must be reviewed as a list.

Figure 3 follows the creation order and the branches that make a technically valid plan operationally wrong.

Create Monitor and Pool Contracts Before the Balancer
%%{init: {'theme':'base','themeCSS':'.edgeLabel .label text, .edgeLabel text, .edgeLabel span { fill:#132440 !important; color:#132440 !important; }','themeVariables': {'primaryColor':'#16476A','primaryTextColor':'#ffffff','primaryBorderColor':'#132440','secondaryColor':'#3B9797','secondaryTextColor':'#ffffff','secondaryBorderColor':'#132440','tertiaryColor':'#c4873b','tertiaryTextColor':'#132440','tertiaryBorderColor':'#132440','lineColor':'#5a6e82','textColor':'#132440','titleColor':'#132440','mainBkg':'#16476A','nodeBorder':'#132440','clusterBkg':'#eef3f7','clusterBorder':'#132440','edgeLabelBackground':'#ffffff','actorBkg':'#16476A','actorTextColor':'#ffffff','actorBorder':'#132440','activationBkgColor':'#3B9797','activationBorderColor':'#132440','signalColor':'#5a6e82','signalTextColor':'#132440','noteBkgColor':'#c4873b','noteTextColor':'#132440','noteBorderColor':'#132440','labelBoxBkgColor':'#a8dede','labelBoxBorderColor':'#132440','labelTextColor':'#132440','loopTextColor':'#132440','altBackground':'#f8f9fa','fontFamily':'DM Sans, sans-serif'}}}%%
flowchart TD
    M["Monitor
account_id · https · /healthz"] --> P1["Pool primary
origin-a · host app.example.com"] M --> P2["Pool secondary
origin-b · host app.example.com"] P1 --> L["Load balancer
default_pools order"] P2 --> L L --> D["LB-managed DNS
app.example.com"] L --> F["Fallback pool
separate owner"] P1 -->|"minimum_origins not met"| X1["Pool critical
skip to next"] P2 -->|"host or TLS mismatch"| X2["Endpoint unhealthy
all pools critical"] L -.->|"fallback = primary"| X3["No last resort"] L -.->|"still referenced"| X4["Pool delete rejected"] classDef primary fill:#132440,color:#ffffff,stroke:#0b172b; classDef secondary fill:#16476A,color:#ffffff,stroke:#0f314a; classDef ok fill:#3B9797,color:#ffffff,stroke:#2a6f6f; classDef danger fill:#BF092F,color:#ffffff,stroke:#7a0420; classDef warn fill:#c4873b,color:#132440,stroke:#8a5a1f; class M,L primary; class P1,P2,D secondary; class F warn; class X1,X2,X3,X4 danger;

Align Health Checks with TLS and Application Readiness

A health check is a synthetic request with a contract. It has a protocol, port, path, expected status or body, a Host header, a TLS name, an interval, a timeout, retries, and consecutive pass and fail counts. The origin is healthy only when every part of that contract matches; a check that passes in a browser can still fail from Cloudflare's network because one of the parts is different.

TLS and HTTP carry different names, and both must be on the certificate. Cloudflare opens TLS to the endpoint and sends a Host value; the listener's certificate must cover both the endpoint name and the application host when the two differ. That is why each origin gets a name you control and a certificate that includes both that name and the application host. A certificate covering only the application host fails when the handshake name is the endpoint name, and the ALB's AWS-generated DNS name cannot be put on a public certificate at all. Turning off validation with allow_insecure hides the mismatch for the probe while the data path still enforces its own validation.

The endpoint host header wins over the monitor host header. If a pool origin sets a host, health probes to that origin use it; otherwise the monitor's header applies, and with neither the endpoint address becomes the host. That precedence is useful for per-origin virtual hosts and dangerous when only one origin has an override, because the two probes no longer test the same request.

Simulate Zone is what makes probes inherit the zone's origin settings. Without probe_zone, a monitor does not use the zone's Authenticated Origin Pulls certificate, Origin CA trust, Argo path or dedicated egress addresses; the browser path can be healthy while every probe is rejected at the origin. Set the probe zone whenever the origin authenticates Cloudflare rather than merely accepting its address range.

The origin ACL must admit Cloudflare, not your laptop. The ALB security group needs 443 from Cloudflare's published ranges, and those ranges change; a rule built from a screenshot is a future outage. Authenticated Origin Pulls is stronger because it proves the client certificate, not the source address, and it is the reason the monitor needs the probe zone. Health checks originate inside Cloudflare's network, so a rule that allows only your office address produces a timeout that looks like a dead origin.

A 200 from a static file proves liveness, not readiness. The health path should exercise the dependency that actually gates traffic, but it should not fail on a non-critical dependency, or a partial outage becomes a full one. Expected-body matching reads only the first 10 KB, and redirects should be rejected rather than followed unless the redirect is the intended steady state.

ObservationLayerLikely causeEvidence to collect
Every probe fails at onceTLS or monitorcertificate names or probe zonehandshake output, origin TLS log
Probe times out, browser worksNetwork ACLsecurity group excludes Cloudflare rangesALB access log, flow log
ALB returns 503, pool criticalTarget healthno healthy target in the grouptarget health, instance log
Users see 421, probes passSNI and Hostnames on the certificate disagreecf-ray, origin request log
Fallback serves at full trafficSteeringall default pools criticalpool health, balancer analytics
Probe volume spikesMonitor scopetoo many regions or too short an intervalrequest counts per endpoint

Two health systems can disagree, and both can be right. The ALB checks the target; Cloudflare checks the ALB. An ALB that has just lost its only target returns 503, which the Cloudflare monitor rejects on its next probe, so the disagreement is usually a timing gap rather than a contradiction. If the ALB is healthy but Cloudflare is not, the difference is in the path, the certificate, the Host header or the ACL.

Timing is a budget, not a promise. Detection is roughly the interval multiplied by consecutive_down, plus timeout and retry time; recovery is roughly the interval multiplied by consecutive_up. Probe scheduling and the number of check regions add variance, so record observed timestamps instead of quoting a vendor number as a guarantee.

Budget for Availability Features and Shared Account Resources

Availability is an add-on with a bill and a permission boundary. Load Balancing is a paid capability; its commercial dimensions are the balancer hostnames, health checking and probe volume, and they sit alongside the AWS ALB hours and capacity units, the instances, and the data transfer. Verify current pricing before the lab; the design decision is whether regional isolation is worth a second control plane, not whether the feature is free.

The API token needs three permission groups. The balancer needs Load Balancers write, monitors and pools need their own write permission, and the grey-clouded origin names need DNS write in the zone. A token with only the first two can create the balancer and then fail while creating the origin records, which is a confusing partial apply rather than a clean permission error.

Monitors and pools are account-scoped, so a zone is not an isolation boundary. A monitor edited for a lab changes every pool in the account that references it, including production. A pool that a balancer still references cannot be deleted, so cleanup can fail for a reason that has nothing to do with the lab's own state.

Use a separate account where possible, and a prefix where it is not. A lab- prefix on monitors and pools, a dedicated zone, and a description that names the owner make a shared account survivable. prevent_destroy on a shared monitor is a guard rail, but it also blocks the eventual cleanup, so apply it only to resources you intend to keep.

Figure 4 contrasts the shared-account shape with an isolated one; the difference is not cosmetic, because the shared monitor is a single edit path into two environments.

Shared monitor versus isolated account, with cost dimensions Shared account One monitor prod-web Production pool serves customers Lab pool tests failover One edit changes both pools the lab is not isolated by zone Blast radius: two environments, one monitor Separate accounts Account A — production Monitor Production pool Account B — lab Monitor Lab pool One edit, one blast radius same contract, separate credentials and state Meter LB hostnames · health checks · probe volume · ALB hours + capacity units · instances · egress

Probe traffic is a real load, not a rounding error. Each selected region sends probes from three data centers, and a pool checked from all regions sends 39 probes per endpoint per interval. A short interval multiplies that across every endpoint, and the ALB access log records each one; choose one or two regions for the lab and justify any wider setting with a recovery requirement.

The cheapest failover is the one you do not need. If a single multi-AZ ALB meets the recovery objective, Cloudflare Load Balancing adds a second control plane, a second health model and a second bill without adding a region. If the requirement is to survive a regional failure, the two-region design earns its cost; write that requirement down before the first apply.

Measure Failover and Recover the Original Route

Rehearse the decision, not the disaster. The useful test is a controlled origin failure with a known start time, not a region shutdown. You want to see the monitor cross its threshold, the balancer skip the pool, the secondary answer, and the primary take traffic back after recovery, each with a timestamp and an independent observation.

Lab

Verify origin failover

Status: design-only. No AWS or Cloudflare credential was used to produce this article, and these steps were not executed here. Versions: Terraform CLI 1.17.1, cloudflare/cloudflare 5.28.1, hashicorp/aws 6.72.0, verified 6 November 2026.

Prerequisites. Load Balancing enabled on the account and zone; a zone you can delegate; two AWS regions with a default VPC and two subnets each; an ACM certificate per region covering the origin name and the application host; an API token with the three permission groups; a budget alarm.

Minimal setup. One proxied balancer hostname reaches two grey-clouded origin names, each a CNAME to an ALB in its own region. Each ALB has an HTTPS listener, a host rule for the application host, and a target group checking the health path.

ObjectValue
Balancer hostnameapp.example.com
Primary originorigin-a.example.com to the us-east-1 ALB
Secondary originorigin-b.example.com to the eu-west-1 ALB
Health path/healthz, expected 200
Region signalX-Origin-Region response header

The application returns the region header so a request can be attributed to an origin without reading Cloudflare logs.

  1. Baseline. Resolve the balancer hostname and send 20 requests that print status, time and the region header. Record the cf-ray values. All should name the primary.
  2. Confirm health first. Both endpoints must be healthy before the test. A pool that is already critical makes the rest of the trace unreadable.
  3. Induce a health failure on the primary without changing Cloudflare. Make /healthz return 500, or block 443 from Cloudflare's ranges in the primary ALB security group. Record t0 when the change lands.
  4. Poll every 10 seconds with the same request. Record the first failed probe, the time the pool becomes critical, and the first response from the secondary. These are t1, t2 and t3.
  5. Read two independent views. Compare balancer analytics with the pool health event log. The point is to see the same transition twice, not to trust one dashboard.
  6. Recover. Restore /healthz or the security group rule. Poll until the primary answers again; record t4 and t5. Existing sessions may stay on the secondary until their TTL.
  7. Test the last resort. Disable both default pools, confirm the fallback answers, then disable the fallback and confirm the proxied error. Restore both.
  8. Close the loop. Run a plan and expect no changes, then destroy in the order balancer, pools, monitor, origin records. Audit the account for a leftover monitor, pool or ALB.

Expected observation. A clean sequence, not a fixed duration: failure, detection, pool critical, secondary traffic, recovery, primary traffic. Detection is bounded by interval times consecutive_down; recovery by interval times consecutive_up. If the sequence skips a step, suspect a cached DNS answer, a probe that never reached the origin, or a pool that was already unhealthy.

Failure checks. A TLS error on every probe points at the certificate name or the probe zone. A timeout while a browser succeeds points at the security group or the probe source ranges. A 421 points at an SNI and Host mismatch. A 503 from the ALB means no healthy target. A 530 with 1016 means the fallback is disabled while every pool is critical.

Cost dimensions. Load balancer hostnames, health checking and probe volume, two ALB hours and capacity units, two instances, and data transfer. The lab is small but not free; the add-on bills until it is removed.

Cleanup. Delete the balancer before the pools, because a pool in use cannot be deleted. Remove the origin records only after the pools no longer reference them. Check that a monitor is not shared with another zone before deleting it, and release any temporary addresses. Delete saved plans and keep state out of Git.

References (verified 6 November 2026):

  • Cloudflare Load Balancing: https://developers.cloudflare.com/load-balancing/
  • Monitors: https://developers.cloudflare.com/load-balancing/monitors/
  • Override Host headers: https://developers.cloudflare.com/load-balancing/additional-options/override-http-host-headers/
  • Endpoint and pool health: https://developers.cloudflare.com/load-balancing/understand-basics/health-details/
  • cloudflare_load_balancer: https://registry.terraform.io/providers/cloudflare/cloudflare/5.28.1/docs/resources/load_balancer
  • cloudflare_load_balancer_pool: https://registry.terraform.io/providers/cloudflare/cloudflare/5.28.1/docs/resources/load_balancer_pool
  • cloudflare_load_balancer_monitor: https://registry.terraform.io/providers/cloudflare/cloudflare/5.28.1/docs/resources/load_balancer_monitor
  • ALB target group health checks: https://docs.aws.amazon.com/elasticloadbalancing/latest/application/target-group-health-checks.html

Next in the Series

In Workers Delivery: Build Artifacts, Versions and Deployments, we'll explore Separate Worker identity, immutable application artifacts and traffic deployment decisions.