Cloudflare AWS ALB networking security-groups

Cloudflare Error 522 (Connection timed out) on an AWS origin: what to check and how to fix it

Fixing Cloudflare error 522 when the origin is an AWS ALB or EC2 instance: security group and NACL rules for Cloudflare IP ranges, stale DNS records, conntrack exhaustion and burnt CPU credits, with Terraform.

Jerzy Kopaczewski ·
Your site returns Cloudflare error 522, and it works again the moment you switch the DNS record to DNS only (grey cloud). Cloudflare is reaching for your AWS origin and getting silence: the SYN never gets answered, or the request is never acknowledged. On AWS the cause is almost always a security group or NACL that does not admit Cloudflare's IP ranges, a DNS record pointing at an address you no longer own, or an origin too starved to answer. This runbook works from the most common cause to the rarest and ends with Terraform that keeps the allowlist current without manual upkeep.

If the origin actively refuses the connection instead of going quiet, you want error 521. If the connection works but the response is empty or malformed, see error 520.

Symptoms

Visitors get the Cloudflare page titled Error 522: Connection timed out. It appears after a wait of several seconds, not instantly, and the response carries a cf-ray ID:

curl -sI https://app.example.com/ | head -5
# HTTP/2 522
# server: cloudflare
# cf-ray: 8a1b2c3d4e5f6a7b-LHR

# The same host straight to the origin (ALB or EC2), bypassing Cloudflare
curl -sI --connect-timeout 10 \
  --resolve app.example.com:443:$(dig +short my-alb-123456.eu-west-1.elb.amazonaws.com | head -1) \
  https://app.example.com/

The status code tells you what kind of failure Cloudflare saw. A 522 means nothing came back. A refused connection is a 521, and an empty or invalid reply is a 520.

Code What Cloudflare saw Where to look
522 Silence: no SYN+ACK, or no acknowledgement of the request Firewalls, security groups, NACLs, DNS, overload
521 Connection refused (RST) Nothing listening, wrong port or SSL mode
520 Connected, but the reply was empty or malformed Application crash, headers, HTTP/2

Cause

Cloudflare’s documentation describes two timeouts behind a 522. Before the TCP connection exists, no SYN+ACK arrives within 19 seconds of the SYN. After it exists, no acknowledgement of the request arrives within 90 seconds. On AWS these are the usual culprits:

  • Security group or NACL missing Cloudflare’s ranges. The most common cause by a distance. Inbound rules were written for office IPs or a previous setup, and once the domain is proxied the traffic comes from Cloudflare’s edge, not from users. A custom NACL adds its own trap: it is stateless, so a missing outbound rule for ephemeral ports drops the replies.
  • A DNS record pointing at a stale address. An EC2 instance without an Elastic IP gets a new public address after every stop and start, while the A record keeps the old one. ALB addresses change even more often, so an A record holding a resolved ALB IP is a design mistake.
  • An ALB with the internal scheme, or one in a subnet with no route to an internet gateway.
  • A host firewall (iptables, ufw, fail2ban, CSF) that bans a Cloudflare range after a burst of bad requests. Your whole audience arrives from a small set of Cloudflare ranges, so one ban cuts off everyone behind it.
  • An overloaded host. A full conntrack table silently drops new connections, and exhausted CPU credits on a burstable instance slow the app past the 90-second limit.

Fix

Step 1: Establish whether Cloudflare’s traffic reaches the origin at all

This decides whether you are hunting a network problem or an application one. If the origin is an ALB with access logging on, there should be no requests from Cloudflare addresses during the errors. If you have VPC Flow Logs in CloudWatch Logs, look for rejected packets:

# CloudWatch Logs Insights on the VPC Flow Logs log group
fields @timestamp, srcAddr, dstAddr, dstPort, action
| filter dstPort = 443 and action = "REJECT"
| stats count(*) as rejected by srcAddr
| sort rejected desc
| limit 20

If the top sources fall inside Cloudflare’s ranges (172.64.0.0/13, 104.16.0.0/13 and the rest), a security group or NACL is dropping them and Steps 3 and 4 are your fix. No rejections but still no traffic? Go to Step 2.

The current ranges come from https://api.cloudflare.com/client/v4/ips. As of November 2026 that is 15 IPv4 and 7 IPv6 ranges.

Step 2: Confirm the DNS record points at a live origin

# Compare the record in the Cloudflare DNS panel with reality

# EC2: current public address and state
aws ec2 describe-instances \
  --instance-ids i-0123456789abcdef0 \
  --query 'Reservations[].Instances[].[PublicIpAddress,State.Name]' --output text

# ALB: the scheme must be internet-facing
aws elbv2 describe-load-balancers \
  --query 'LoadBalancers[].[LoadBalancerName,Scheme,DNSName]' --output table

Two rules remove this whole class of failure. Give instances an Elastic IP. Point ALBs with a CNAME to the load balancer’s DNS name, which Cloudflare also supports at the zone apex through CNAME flattening. Never copy an address from dig into an A record for an ALB.

Step 3: Admit Cloudflare’s ranges in the security group

Adding 22 rules by hand is tedious and goes stale. Use customer-managed prefix lists and one rule per list. A prefix list holds a single address family, so you need two, and each one counts against the rule quota at its maximum size (here 20 and 10 of the default 60):

data "http" "cloudflare_ips" {
  url = "https://api.cloudflare.com/client/v4/ips"
}

locals {
  cloudflare = jsondecode(data.http.cloudflare_ips.response_body).result
}

resource "aws_ec2_managed_prefix_list" "cloudflare_v4" {
  name           = "cloudflare-ipv4"
  address_family = "IPv4"
  max_entries    = 20

  dynamic "entry" {
    for_each = toset(local.cloudflare.ipv4_cidrs)
    content {
      cidr        = entry.value
      description = "Cloudflare"
    }
  }
}

resource "aws_ec2_managed_prefix_list" "cloudflare_v6" {
  name           = "cloudflare-ipv6"
  address_family = "IPv6"
  max_entries    = 10

  dynamic "entry" {
    for_each = toset(local.cloudflare.ipv6_cidrs)
    content {
      cidr        = entry.value
      description = "Cloudflare"
    }
  }
}

resource "aws_vpc_security_group_ingress_rule" "alb_https_cloudflare_v4" {
  security_group_id = aws_security_group.alb.id
  prefix_list_id    = aws_ec2_managed_prefix_list.cloudflare_v4.id
  ip_protocol       = "tcp"
  from_port         = 443
  to_port           = 443
}

resource "aws_vpc_security_group_ingress_rule" "alb_https_cloudflare_v6" {
  security_group_id = aws_security_group.alb.id
  prefix_list_id    = aws_ec2_managed_prefix_list.cloudflare_v6.id
  ip_protocol       = "tcp"
  from_port         = 443
  to_port           = 443
}

The rules belong on the ALB’s security group, because the ALB, not the instance behind it, receives Cloudflare’s traffic. The instance’s own security group should admit only the ALB’s group. With a single EC2 origin and no ALB, the same rule goes on the instance. Cloudflare’s ranges change rarely but they do change, so run terraform plan on a schedule (weekly in CI is enough) and catch drift before a customer does.

Step 4: Check the network ACLs

Security groups are stateful, NACLs are not. If the subnet has a custom NACL it needs an inbound rule for port 443 from Cloudflare’s ranges and an outbound rule for ephemeral ports (1024-65535) back to them. Without the second rule the SYN arrives and the reply never leaves, which looks exactly like this error.

SUBNET=subnet-0123456789abcdef0
aws ec2 describe-network-acls \
  --filters Name=association.subnet-id,Values=$SUBNET \
  --query 'NetworkAcls[].Entries[].[RuleNumber,Egress,Protocol,RuleAction,CidrBlock,PortRange]' \
  --output table

The default quota is 20 rules per NACL, so 15 IPv4 ranges plus the return rules is a tight fit. For subnets that host an ALB, the simplest fix is to keep the default allow-all NACL and do the filtering in security groups, which are more precise anyway.

Step 5: Rule out the host firewall and resource starvation

If the origin is an EC2 instance, check three things on it:

# 1. Is a host firewall dropping Cloudflare ranges?
sudo iptables -L INPUT -n | grep -E "DROP|REJECT"
sudo fail2ban-client status 2>/dev/null

# 2. Is the conntrack table full (new connections silently dropped)?
sudo dmesg | grep -i "nf_conntrack: table full"
sysctl net.netfilter.nf_conntrack_count net.netfilter.nf_conntrack_max

# 3. Is something listening, and is the box coping?
sudo ss -tlnp | grep -E ':(80|443)\b'
uptime

On burstable (T-family) instances, check the CPU credit balance too. At zero the instance is throttled and can miss the 90-second acknowledgement window:

aws cloudwatch get-metric-statistics \
  --namespace AWS/EC2 --metric-name CPUCreditBalance \
  --dimensions Name=InstanceId,Value=i-0123456789abcdef0 \
  --start-time $(date -u -d '3 hours ago' +%Y-%m-%dT%H:%M:%S) \
  --end-time $(date -u +%Y-%m-%dT%H:%M:%S) \
  --period 300 --statistics Minimum

Fail2ban and similar tools deserve a closer look. They see the source of every request as a Cloudflare address, so one burst of bad requests from a single visitor can ban a whole range and lock out everyone behind it. Add Cloudflare’s ranges to the ignore list (ignoreip) and base blocking on the real client address in the CF-Connecting-IP header.

Step 6: Rule out Cloudflare-side causes

  • A Worker on a custom domain that calls fetch on its own hostname gets a 522. Use a Route on a different hostname, or the global_fetch_strictly_public compatibility flag.
  • An Origin Rule that resolves to a reserved address (for example 100:: or 192.0.2.0) also ends in a 522.
  • On Cloudflare Pages, check that the CNAME points at the custom Pages domain.

If nothing here resolves it, gather what Cloudflare support will ask for: the cf-ray, the full URL, a traceroute or MTR from the origin to a Cloudflare address seen in your logs, and the relevant host logs.

Validation

Confirm traffic arrives now, and that the fix will survive the next range change:

# 1. The site answers through Cloudflare
curl -s -o /dev/null -w "%{http_code} %{time_total}s\n" https://app.example.com/
# Expected: 200 and a response time of a few seconds at most

# 2. The ALB security group carries the prefix-list rules
aws ec2 describe-security-group-rules \
  --filters Name=group-id,Values=sg-0123456789abcdef0 \
  --query 'SecurityGroupRules[?IsEgress==`false`].[PrefixListId,FromPort,ToPort]' --output table

# 3. ALB access logs now show requests from Cloudflare addresses
#    (client:port starting 104.16., 172.64. and similar)

# 4. No REJECT entries from Cloudflare ranges in VPC Flow Logs
#    (rerun the Insights query from Step 1; it should return nothing)

Alert on it too. 522s show up in the Cloudflare dashboard (Analytics, status codes) and in Logpush as EdgeResponseStatus. An alarm on rising 52x responses finds the problem before a support ticket does.

An allowlist of Cloudflare addresses keeps out traffic that did not come through Cloudflare, but not traffic from another Cloudflare customer who points their zone at your address. If the origin should serve only your domain, add Authenticated Origin Pulls (a client certificate) or a secret header checked at the ALB. The cleanest answer removes the open port altogether: Cloudflare Tunnel connects outbound to Cloudflare, so the origin needs no inbound rules and a security-group-driven 522 cannot happen.

Frequently asked questions about Cloudflare error 522

What does Cloudflare error 522 mean?

Error 522 (Connection timed out) means Cloudflare got no response from your origin server. Either no SYN+ACK came back within 19 seconds of the connection attempt, or after connecting, the request went unacknowledged for 90 seconds. Cloudflare itself is working; the problem sits between it and your origin.

Why does my AWS ALB or EC2 instance return 522 after moving behind Cloudflare?

Usually because a security group or NACL admits only specific addresses, and once the domain is proxied the traffic reaches your origin from Cloudflare's IP ranges instead of from users. Add those ranges to the ALB's security group, ideally through managed prefix lists, and check that any custom NACL has an outbound rule for ephemeral ports.

What is the difference between Cloudflare errors 522, 521 and 520?

A 522 is silence (packets lost, or the origin too slow to acknowledge), a 521 is an active refusal of the connection, and a 520 is a connection that works but returns an empty or invalid response. The code points you at the layer to check: firewalls, security groups and DNS for 522, listeners and ports for 521, the application itself for 520.

Can I use an A record with the ALB's IP address in Cloudflare?

No. Load balancer addresses change, so a fixed A record will sooner or later point at an address that no longer belongs to your ALB. Use a CNAME to the ALB's DNS name. Cloudflare supports a CNAME at the zone apex through CNAME flattening.

 

Jerzy Kopaczewski

Still seeing 52x errors with Cloudflare in front of AWS?

Book a free 30-minute call. We tidy the network around ALBs and EC2 behind Cloudflare: security groups, NACLs, DNS, Authenticated Origin Pulls, or Tunnel in place of open ports.

Book a call