Cloudflare Load Balancing
Cloud-based global load balancer. Integrates intelligent routing, health checks, and DDoS protection. Edge network across 290 cities worldwide.
Server
Cloudflare Load Balancing
Overview
Cloudflare Load Balancing is a cloud-based load balancing service that leverages Cloudflare's global network spanning 330+ cities worldwide. Through DNS-level high-speed traffic control, it reduces endpoint strain and improves latency. With geographic distribution, weighted load balancing, and real-time health check capabilities, it provides optimal performance for global users. As a SaaS solution, it enables easy configuration and management through the Cloudflare dashboard and built-in DDoS protection API without requiring additional hardware or software.
Details
Cloudflare Load Balancing operates on infrastructure with the world's fastest authoritative DNS servers and DDoS resilience, supporting L4-L7 protocols (HTTP/HTTPS, TCP, UDP). It consists of endpoint pools (endpoint groups by function, geographic area, or region), health monitors (service type, path, port configurations), and traffic control algorithms. Advanced traffic control features including geographic routing, latency-based routing, and GPS-based routing enable automatic guidance to optimal endpoints for users. It provides real-time analytics, comprehensive health monitoring, and automatic failover capabilities.
Key Features
- Global Network: Traffic distribution and DDoS protection across 330+ cities
- Intelligent Routing: Optimal routing based on geography, latency, and GPS
- Real-time Health Checks: Continuous endpoint monitoring across multiple data centers
- Multi-protocol Support: Load balancing for HTTP/HTTPS, TCP, and UDP
- API-first Approach: Developer-friendly REST API and dashboard
- Integrated Security: Unified DDoS protection, WAF, and SSL/TLS encryption
Pros and Cons
Pros
- Low latency and high availability through global distributed network
- Scalable SaaS solution without additional hardware requirements
- Integrated security features including DDoS protection, WAF, and CDN
- Operational efficiency through intuitive dashboard and comprehensive API functionality
- Detailed monitoring and insights through real-time analytics and alerting
- Reduced operational overhead through automatic failover and self-healing capabilities
Cons
- Increased latency between cloud-based load balancer and endpoints
- Vendor lock-in risks due to Cloudflare network dependency
- Increased learning and management costs with complex configurations
- Real-time constraints due to DNS-based routing
- Rising costs with traffic increases due to usage-based pricing
- Integration constraints with on-premises environments
Reference Pages
- Cloudflare Load Balancing Official Website
- Cloudflare Load Balancing Documentation
- Cloudflare API Documentation
- Cloudflare Dashboard
Code Examples
Basic Configuration and Pool Creation
# Cloudflare API key configuration
export CF_API_TOKEN="your_cloudflare_api_token"
export CF_ZONE_ID="your_zone_id"
# Create load balancer pool
curl -X POST "https://api.cloudflare.com/client/v4/user/load_balancers/pools" \
-H "Authorization: Bearer $CF_API_TOKEN" \
-H "Content-Type: application/json" \
--data '{
"name": "web-servers-pool",
"description": "Primary web servers pool",
"enabled": true,
"minimum_origins": 1,
"monitor": "health_check_monitor",
"origins": [
{
"name": "web-server-1",
"address": "203.0.113.10",
"enabled": true,
"weight": 1,
"header": {
"Host": ["example.com"]
}
},
{
"name": "web-server-2",
"address": "203.0.113.11",
"enabled": true,
"weight": 1,
"header": {
"Host": ["example.com"]
}
}
],
"notification_email": "[email protected]"
}'
# Create geographic backup pool
curl -X POST "https://api.cloudflare.com/client/v4/user/load_balancers/pools" \
-H "Authorization: Bearer $CF_API_TOKEN" \
-H "Content-Type: application/json" \
--data '{
"name": "backup-pool-eu",
"description": "European backup servers",
"enabled": true,
"minimum_origins": 1,
"origins": [
{
"name": "backup-eu-1",
"address": "198.51.100.10",
"enabled": true,
"weight": 1
},
{
"name": "backup-eu-2",
"address": "198.51.100.11",
"enabled": true,
"weight": 1
}
]
}'
Health Check Monitor Configuration
# Create HTTP health check monitor
curl -X POST "https://api.cloudflare.com/client/v4/user/load_balancers/monitors" \
-H "Authorization: Bearer $CF_API_TOKEN" \
-H "Content-Type: application/json" \
--data '{
"type": "http",
"description": "Web server health check",
"method": "GET",
"path": "/health",
"port": 80,
"interval": 60,
"retries": 2,
"timeout": 5,
"expected_codes": "200",
"expected_body": "healthy",
"follow_redirects": true,
"allow_insecure": false,
"header": {
"Host": ["example.com"],
"User-Agent": ["Cloudflare-Health-Check"]
}
}'
# HTTPS health check
curl -X POST "https://api.cloudflare.com/client/v4/user/load_balancers/monitors" \
-H "Authorization: Bearer $CF_API_TOKEN" \
-H "Content-Type: application/json" \
--data '{
"type": "https",
"description": "HTTPS health check",
"method": "GET",
"path": "/api/health",
"port": 443,
"interval": 30,
"retries": 3,
"timeout": 10,
"expected_codes": "200-299",
"expected_body": "\"status\":\"ok\"",
"header": {
"Authorization": ["Bearer health_check_token"]
}
}'
# TCP health check
curl -X POST "https://api.cloudflare.com/client/v4/user/load_balancers/monitors" \
-H "Authorization: Bearer $CF_API_TOKEN" \
-H "Content-Type: application/json" \
--data '{
"type": "tcp",
"description": "Database TCP health check",
"port": 3306,
"interval": 60,
"retries": 2,
"timeout": 5
}'
Load Balancer Creation and Geographic Routing
# Create basic load balancer
curl -X POST "https://api.cloudflare.com/client/v4/zones/$CF_ZONE_ID/load_balancers" \
-H "Authorization: Bearer $CF_API_TOKEN" \
-H "Content-Type: application/json" \
--data '{
"name": "api.example.com",
"description": "API load balancer with geographic routing",
"ttl": 30,
"fallback_pool": "backup-pool-global",
"default_pools": ["web-servers-pool"],
"region_pools": {
"WNAM": ["web-servers-pool-us"],
"ENAM": ["web-servers-pool-us"],
"WEU": ["web-servers-pool-eu"],
"EEU": ["web-servers-pool-eu"],
"APAC": ["web-servers-pool-asia"]
},
"country_pools": {
"JP": ["web-servers-pool-japan"],
"CN": ["web-servers-pool-china"],
"AU": ["web-servers-pool-australia"]
},
"pop_pools": {
"LAX": ["web-servers-pool-california"],
"ORD": ["web-servers-pool-chicago"]
},
"steering_policy": "geo",
"session_affinity": "cookie",
"session_affinity_ttl": 1800,
"session_affinity_attributes": {
"samesite": "Auto",
"secure": "Auto",
"drain_duration": 100
}
}'
# Random steering configuration
curl -X PUT "https://api.cloudflare.com/client/v4/zones/$CF_ZONE_ID/load_balancers/{load_balancer_id}" \
-H "Authorization: Bearer $CF_API_TOKEN" \
-H "Content-Type: application/json" \
--data '{
"steering_policy": "random",
"random_steering": {
"pool_weights": {
"pool_id_1": 0.7,
"pool_id_2": 0.2,
"pool_id_3": 0.1
},
"default_weight": 1
}
}'
Advanced Traffic Control Configuration
// JavaScript API client usage example
const cloudflare = require('cloudflare');
const cf = cloudflare({
token: 'your_cloudflare_api_token'
});
// Dynamic weight adjustment
async function updatePoolWeights(poolId, origins) {
try {
const response = await cf.userLoadBalancerPools.edit(poolId, {
origins: origins.map(origin => ({
name: origin.name,
address: origin.address,
weight: origin.weight,
enabled: origin.enabled
}))
});
console.log('Pool weights updated:', response.result);
} catch (error) {
console.error('Error updating pool weights:', error);
}
}
// Canary deployment configuration
async function setupCanaryDeployment(lbId, productionPool, canaryPool, canaryWeight = 0.1) {
const config = {
steering_policy: 'random',
random_steering: {
pool_weights: {}
},
default_pools: [productionPool, canaryPool]
};
config.random_steering.pool_weights[productionPool] = 1 - canaryWeight;
config.random_steering.pool_weights[canaryPool] = canaryWeight;
try {
const response = await cf.dnsRecords.edit(zoneId, lbId, config);
console.log('Canary deployment configured:', response.result);
} catch (error) {
console.error('Error setting up canary deployment:', error);
}
}
// Latency-based routing
const latencyBasedConfig = {
steering_policy: 'proximity',
proximity_steering: {
policy: "least_outstanding_requests"
}
};
Terraform Configuration Example
# terraform/cloudflare_lb.tf
terraform {
required_providers {
cloudflare = {
source = "cloudflare/cloudflare"
version = "~> 4.0"
}
}
}
provider "cloudflare" {
api_token = var.cloudflare_api_token
}
# Health check monitor
resource "cloudflare_load_balancer_monitor" "http_monitor" {
type = "http"
expected_codes = "200"
method = "GET"
timeout = 7
path = "/health"
interval = 60
retries = 2
description = "HTTP health check"
header {
Host = ["example.com"]
}
}
# Primary pool
resource "cloudflare_load_balancer_pool" "primary_pool" {
name = "primary-web-pool"
monitor = cloudflare_load_balancer_monitor.http_monitor.id
origins {
name = "web-1"
address = "203.0.113.10"
enabled = true
weight = 1
}
origins {
name = "web-2"
address = "203.0.113.11"
enabled = true
weight = 1
}
origins {
name = "web-3"
address = "203.0.113.12"
enabled = true
weight = 2
}
description = "Primary web servers"
enabled = true
minimum_origins = 2
notification_email = "[email protected]"
notification_filter {
pool {
disable = false
healthy = false
}
origin {
disable = false
healthy = false
}
}
}
# Backup pool
resource "cloudflare_load_balancer_pool" "backup_pool" {
name = "backup-web-pool"
monitor = cloudflare_load_balancer_monitor.http_monitor.id
origins {
name = "backup-1"
address = "198.51.100.10"
enabled = true
}
description = "Backup web servers"
enabled = true
minimum_origins = 1
}
# Load balancer
resource "cloudflare_load_balancer" "main_lb" {
zone_id = var.cloudflare_zone_id
name = "api.example.com"
fallback_pool = cloudflare_load_balancer_pool.backup_pool.id
default_pools = [cloudflare_load_balancer_pool.primary_pool.id]
description = "Main application load balancer"
ttl = 30
steering_policy = "geo"
# Geographic routing
region_pools = {
"WNAM" = [cloudflare_load_balancer_pool.primary_pool.id]
"ENAM" = [cloudflare_load_balancer_pool.primary_pool.id]
"WEU" = [cloudflare_load_balancer_pool.backup_pool.id]
"EEU" = [cloudflare_load_balancer_pool.backup_pool.id]
}
# Session affinity
session_affinity = "cookie"
session_affinity_ttl = 1800
# Adaptive routing
adaptive_routing {
failover_across_pools = true
}
# Random steering
random_steering {
pool_weights = {
(cloudflare_load_balancer_pool.primary_pool.id) = 0.9
(cloudflare_load_balancer_pool.backup_pool.id) = 0.1
}
default_weight = 1
}
}
# DNS record
resource "cloudflare_record" "lb_record" {
zone_id = var.cloudflare_zone_id
name = "api"
value = cloudflare_load_balancer.main_lb.id
type = "CNAME"
proxied = true
}
Monitoring and Alert Configuration
# Check pool status
curl -X GET "https://api.cloudflare.com/client/v4/user/load_balancers/pools/{pool_id}/health" \
-H "Authorization: Bearer $CF_API_TOKEN" \
-H "Content-Type: application/json"
# Get load balancer statistics
curl -X GET "https://api.cloudflare.com/client/v4/zones/$CF_ZONE_ID/load_balancers/{lb_id}/events" \
-H "Authorization: Bearer $CF_API_TOKEN" \
-H "Content-Type: application/json"
# Notification configuration
curl -X POST "https://api.cloudflare.com/client/v4/accounts/{account_id}/alerting/v3/policies" \
-H "Authorization: Bearer $CF_API_TOKEN" \
-H "Content-Type: application/json" \
--data '{
"name": "Load Balancer Pool Health Alert",
"description": "Alert when pool becomes unhealthy",
"enabled": true,
"alert_type": "load_balancing_pool_enablement_alert",
"mechanisms": {
"email": [
{
"id": "[email protected]"
}
],
"webhooks": [
{
"id": "webhook_id_here"
}
]
},
"conditions": {
"load_balancing_pool_enablement_alert": {
"pool": "pool_id_here",
"enabled": false
}
}
}'
Performance Optimization Configuration
# Origin optimization configuration
curl -X PATCH "https://api.cloudflare.com/client/v4/user/load_balancers/pools/{pool_id}" \
-H "Authorization: Bearer $CF_API_TOKEN" \
-H "Content-Type: application/json" \
--data '{
"load_shedding": {
"default_percent": 0,
"default_policy": "random",
"session_percent": 0,
"session_policy": "hash"
},
"origin_steering": {
"policy": "least_outstanding_requests"
}
}'
# Enable adaptive routing
curl -X PATCH "https://api.cloudflare.com/client/v4/zones/$CF_ZONE_ID/load_balancers/{lb_id}" \
-H "Authorization: Bearer $CF_API_TOKEN" \
-H "Content-Type: application/json" \
--data '{
"adaptive_routing": {
"failover_across_pools": true
},
"location_strategy": {
"prefer_ecs": "proximity",
"mode": "resolver_ip"
}
}'
# Performance settings in proxy mode
curl -X PATCH "https://api.cloudflare.com/client/v4/zones/$CF_ZONE_ID/settings/always_online" \
-H "Authorization: Bearer $CF_API_TOKEN" \
-H "Content-Type: application/json" \
--data '{"value": "on"}'
curl -X PATCH "https://api.cloudflare.com/client/v4/zones/$CF_ZONE_ID/settings/rocket_loader" \
-H "Authorization: Bearer $CF_API_TOKEN" \
-H "Content-Type: application/json" \
--data '{"value": "on"}'
Troubleshooting
# Check load balancer status
curl -X GET "https://api.cloudflare.com/client/v4/zones/$CF_ZONE_ID/load_balancers" \
-H "Authorization: Bearer $CF_API_TOKEN"
# Check pool health details
curl -X GET "https://api.cloudflare.com/client/v4/user/load_balancers/pools/{pool_id}/preview" \
-H "Authorization: Bearer $CF_API_TOKEN"
# DNS lookup test
dig @1.1.1.1 api.example.com
nslookup api.example.com 1.1.1.1
# Traceroute check
traceroute api.example.com
mtr api.example.com
# Get Cloudflare analytics data
curl -X GET "https://api.cloudflare.com/client/v4/zones/$CF_ZONE_ID/analytics/dashboard" \
-H "Authorization: Bearer $CF_API_TOKEN" \
-G -d 'since=-1440' -d 'until=0' -d 'continuous=true'
# Log streaming (Enterprise)
curl -X GET "https://api.cloudflare.com/client/v4/zones/$CF_ZONE_ID/logpush/jobs" \
-H "Authorization: Bearer $CF_API_TOKEN"
# Performance test
curl -w "@curl-format.txt" -o /dev/null -s "https://api.example.com/"
# curl-format.txt content:
# time_namelookup: %{time_namelookup}\n
# time_connect: %{time_connect}\n
# time_appconnect: %{time_appconnect}\n
# time_pretransfer: %{time_pretransfer}\n
# time_redirect: %{time_redirect}\n
# time_starttransfer: %{time_starttransfer}\n
# ----------\n
# time_total: %{time_total}\n