Cloudflare AWS ALB timeouts performance

Cloudflare Error 524 (A timeout occurred) on an AWS origin: why requests pass 125 seconds and how to fix it

Fixing Cloudflare error 524 when the origin is an AWS ALB or EC2 instance: find the slow endpoint in ALB logs, align Cloudflare, ALB and application timeouts, move long jobs to a queue, and alarm on response time, with Terraform.

Jerzy Kopaczewski ·
Your site returns Cloudflare error 524 on one page or API call, while the rest of the site works. Cloudflare reached your AWS origin and the origin accepted the request, but sent no HTTP response within 125 seconds. The cause sits in the origin: a request that does too much work, a database query that hangs, or a worker pool that has run out of capacity. On AWS there is one more cause that traps teams. An Application Load Balancer closes idle connections after 60 seconds by default, so a slow request ends in an ALB 504 long before Cloudflare gives up. Someone raises the ALB timeout to cure the 504, and the same request now fails with a 524. This runbook finds the slow request, aligns the timeouts and ends with the fix that holds: moving long work out of the request.

If Cloudflare never connects to the origin, you want error 522. If the connection is refused, see error 521.

Symptoms

Visitors see the Cloudflare page titled Error 524: A timeout occurred. It appears after a long wait of about two minutes, and only on the slow endpoint. Time the request to confirm the length of the wait:

curl -s -o /dev/null -w "%{http_code} %{time_total}s\n" --max-time 200 \
  https://app.example.com/reports/export
# 524 125.4s

A wait of about 125 seconds with a 524 at the end is the signature. The status code and the wait tell you which layer gave up:

Response Wait before it appears Who produced it
524 about 125 s Cloudflare: origin accepted the request, sent no response
504 the ALB idle timeout (60 s by default) The ALB: target did not respond in time
522 19 s to connect, or 90 s without acknowledgement Cloudflare: origin network unreachable or silent

A 504 from the ALB is a plain “504 Gateway Time-out” page. A 524 carries the Cloudflare layout and the text “A timeout occurred”.

Cause

Cloudflare’s Proxy Read Timeout is 125 seconds by default. It applies to the time between Cloudflare finishing the request and receiving a response from your origin. On AWS these are the usual culprits:

  • A synchronous request that does too much work. Report exports, bulk imports, PDF generation, large search queries and calls to a slow LLM or third-party API all run for as long as the work takes. When the work passes 125 seconds, Cloudflare closes the request.
  • An ALB idle timeout raised above 125 seconds. With the default 60 seconds, the ALB answers with a 504 first. A team that raises the timeout to 300 seconds moves the failure from the ALB to Cloudflare, and the visitor now sees a 524.
  • No ALB in front. An EC2 instance or Network Load Balancer behind Cloudflare has no 60-second ceiling, so slow requests run until Cloudflare stops them.
  • A database query or lock that hangs. The request waits on a long-running query, a lock held by a migration job or a connection pool with no free connections.
  • A saturated worker pool. All Gunicorn, PHP-FPM or Node workers are busy with slow requests, and new requests queue until the 125 seconds run out.
  • A slow upload. Cloudflare’s Proxy Write Timeout is 30 seconds and cannot be changed. A large upload over a slow client connection can also end in a 524.

Fix

Step 1: Find the slow endpoint in the ALB access logs

When Cloudflare gives up at 125 seconds and closes the connection, the ALB records the request with status 460 (the client closed the connection before the idle timeout). Requests that the ALB itself cut off show up as 504. With access logging on and the standard Athena table from the AWS documentation:

SELECT request_url,
       elb_status_code,
       count(*) AS requests,
       round(avg(target_processing_time), 1) AS avg_target_s,
       max(target_processing_time) AS max_target_s
FROM alb_logs
WHERE time > to_iso8601(current_timestamp - interval '1' day)
  AND (elb_status_code IN ('460', '504') OR target_processing_time > 60)
GROUP BY request_url, elb_status_code
ORDER BY requests DESC
LIMIT 20;

Without access logs, the CloudWatch metrics show whether response times approach the limit at all:

aws cloudwatch get-metric-statistics \
  --namespace AWS/ApplicationELB --metric-name TargetResponseTime \
  --dimensions Name=LoadBalancer,Value=app/my-alb/0123456789abcdef \
  --start-time $(date -u -d '24 hours ago' +%Y-%m-%dT%H:%M:%S) \
  --end-time $(date -u +%Y-%m-%dT%H:%M:%S) \
  --period 300 --extended-statistics p99

A p99 close to 100 seconds or more confirms the slow-request pattern. The result of this step is a short list of URLs. Everything below applies to those URLs.

Step 2: Find out why the request is slow

Open the application log or trace for one of the URLs from Step 1 and look at where the time goes. For a PostgreSQL database behind the app, list the queries that run longest right now:

SELECT pid, now() - query_start AS runtime, state, wait_event_type, left(query, 80) AS query
FROM pg_stat_activity
WHERE state <> 'idle'
ORDER BY runtime DESC
LIMIT 10;

RDS Performance Insights gives the same picture over time, split by wait event. If the slow part is a call to another service, add a timeout of your own to that call. A call without a timeout turns one slow dependency into a 125-second wait.

Step 3: Align the timeouts across the layers

Each layer needs a timeout that expires before the layer outside it. Otherwise the outermost layer, Cloudflare, ends the request and the inner layers keep working for a client that is gone.

Layer Default Where to change it
Cloudflare Proxy Read Timeout 125 s Enterprise zones only, up to 6,000 s
ALB idle timeout 60 s (range 1 to 4000) Load balancer attribute
Reverse proxy (nginx) proxy_read_timeout 60 s nginx config
Application server Gunicorn timeout 30 s Server config

For endpoints that must stay synchronous and finish in under two minutes, set the ALB idle timeout below Cloudflare’s 125 seconds and above the real runtime. In Terraform:

resource "aws_lb" "app" {
  name               = "app"
  load_balancer_type = "application"
  subnets            = var.public_subnet_ids
  security_groups    = [aws_security_group.alb.id]

  # Below Cloudflare's 125 s Proxy Read Timeout, above the slowest legitimate request
  idle_timeout = 110
}

Keep the application server’s idle keep-alive longer than the ALB idle timeout, as AWS recommends, so the ALB does not reuse a connection the target has already closed (that case produces 502 errors). For a long request that sends data in chunks, the ALB idle timer resets on every byte, which AWS recommends for lengthy operations such as uploads.

Step 4: Move long work out of the request

Any endpoint that needs more than a minute or two belongs on a queue. Cloudflare’s own guidance for large HTTP processes is status polling. The flow has three parts:

# 1. The request starts the job and returns at once
curl -s -X POST https://app.example.com/reports/export -d '{"month":"2026-11"}'
# {"job_id":"7c1d...","status":"queued","status_url":"/reports/export/7c1d..."}   (HTTP 202)

# 2. A worker takes the job from a queue (SQS here) and runs for as long as it needs
# 3. The client polls the status URL, or receives a webhook, until the file is ready
curl -s https://app.example.com/reports/export/7c1d...
# {"status":"done","download_url":"https://app-exports.s3.eu-west-1.amazonaws.com/..."}

The enqueue side of the request handler stays short:

import json, uuid, boto3

sqs = boto3.client("sqs")

def start_export(month: str) -> dict:
    job_id = str(uuid.uuid4())
    sqs.send_message(
        QueueUrl=EXPORT_QUEUE_URL,
        MessageBody=json.dumps({"job_id": job_id, "month": month}),
    )
    return {"job_id": job_id, "status": "queued", "status_url": f"/reports/export/{job_id}"}

A worker on ECS or a Lambda function reads the queue, writes the result to S3 and records the status. The request that used to take 200 seconds now takes a few milliseconds.

Step 5: Take uploads off the proxy path

Cloudflare’s 30-second Proxy Write Timeout cannot be changed. Large files go straight to S3 with a presigned URL, so the upload never crosses the origin:

url = boto3.client("s3").generate_presigned_url(
    "put_object",
    Params={"Bucket": "app-uploads", "Key": f"incoming/{upload_id}"},
    ExpiresIn=900,
)

Step 6: Use the Cloudflare options when the request cannot change

  • A separate DNS-only hostname (grey cloud) for the long endpoint, for example exports.example.com. Cloudflare then no longer sits in the path, so the 125-second limit disappears. The hostname also loses Cloudflare’s WAF, DDoS protection and caching, and its origin must accept public traffic, which undoes the allowlist from the 522 runbook. Use it for authenticated, rate-limited endpoints only.
  • Enterprise zones can raise the Proxy Read Timeout to as much as 6,000 seconds with the proxy_read_timeout zone setting or a Cache Rule. Add one second to the value you want: Cloudflare documents a one-second difference between the setting and the moment the 524 appears.
  • Cloudflare Tunnel adds a second timeout layer between cloudflared and the origin. When both layers apply to a request, the shorter timeout decides.

Validation

Confirm that the slow endpoint now answers quickly or completes within the new limit, and that the next regression raises an alert before visitors see it:

# 1. The endpoint answers (202 for the async pattern, 200 for a fixed synchronous one)
curl -s -o /dev/null -w "%{http_code} %{time_total}s\n" -X POST \
  https://app.example.com/reports/export -d '{"month":"2026-11"}'
# Expected: 202 and well under a second

# 2. The ALB idle timeout is the value you set
aws elbv2 describe-load-balancer-attributes --load-balancer-arn $ALB_ARN \
  --query 'Attributes[?Key==`idle_timeout.timeout_seconds`].Value' --output text

# 3. Rerun the Athena query from Step 1 for the last hour:
#    no new 460 or 504 rows for the endpoint

Alert on response time, so the next slow request shows up as a rising p99 and not as a visitor complaint:

resource "aws_cloudwatch_metric_alarm" "alb_slow_targets" {
  alarm_name          = "alb-target-response-time-p99"
  namespace           = "AWS/ApplicationELB"
  metric_name         = "TargetResponseTime"
  dimensions          = { LoadBalancer = aws_lb.app.arn_suffix }
  extended_statistic  = "p99"
  period              = 300
  evaluation_periods  = 3
  threshold           = 60
  comparison_operator = "GreaterThanThreshold"
  alarm_actions       = [aws_sns_topic.ops.arn]
}

Cloudflare’s Origin Analytics shows origin response times per endpoint. When the P95 of an endpoint approaches 125 seconds, that endpoint is next in line for a 524.

Frequently asked questions about Cloudflare error 524

What does Cloudflare error 524 mean?

Error 524 (A timeout occurred) means Cloudflare connected to your origin and the origin accepted the request, but sent no HTTP response within the Proxy Read Timeout, which is 125 seconds by default. The connection itself works. The origin takes too long to answer, so the fix lives in the application, the database or the timeout settings of the layers in front of it.

How long is the Cloudflare timeout, and can I change it?

The Proxy Read Timeout is 125 seconds. Enterprise zones can raise it up to 6,000 seconds with the proxy_read_timeout zone setting or a Cache Rule. Free, Pro and Business zones cannot change it. They move the long endpoint to a DNS-only hostname, or turn the request into a background job that the client polls.

Why do I get a 504 from my AWS load balancer and not a 524?

An Application Load Balancer closes a connection after 60 seconds without data by default. A request that needs 90 seconds ends in an ALB 504 before Cloudflare's 125 seconds are up. If you raise the ALB idle timeout above 125 seconds, the same request fails with a Cloudflare 524 instead.

How do I find which request causes the 524 on AWS?

Turn on ALB access logs and query them for status 460 (the client closed the connection first, which is what Cloudflare does at 125 seconds) and for 504, grouped by request URL, with the target processing time. The CloudWatch metric TargetResponseTime at p99 shows the same pattern without log queries.

 

Jerzy Kopaczewski

Slow requests timing out behind Cloudflare on AWS?

Book a free 30-minute call. We trace slow endpoints from the ALB logs to the query, align timeouts across Cloudflare, ALB and the application, and move long jobs onto queues.

Book a call