What's Actually Happening

Cloudflare returns 504 Gateway Timeout when origin server takes too long to respond. The request exceeds Cloudflare's timeout limit.

The Error You'll See

bash
Error 504 Ray ID: xxx-xxx-xxx
Gateway Timeout
The web server reported a gateway time-out error.

Why This Happens

  1. 1.Origin server slow
  2. 2.Long-running request
  3. 3.Server overload
  4. 4.Network latency
  5. 5.Application processing time

Step 1: Check Origin Server

bash
curl -I https://origin-server.com/path
time curl https://origin-server.com/path

Step 2: Check Server Resources

bash
top -bn1 | head -20
free -m
df -h

Step 3: Optimize Application

```bash # Check application logs tail -f /var/log/app/error.log

# Identify slow queries # Add caching # Use async processing ```

Step 4: Adjust Cloudflare Settings

bash
# In Cloudflare dashboard:
# Rules > Page Rules
# Cache Level: Cache Everything
# Edge Cache TTL: 1 hour

Step 5: Enable Cloudflare Caching

nginx
# Origin server headers:
Cache-Control: public, max-age=3600

Step 6: Use Workers for Long Requests

javascript
// Cloudflare Worker
export default {
  async fetch(request) {
    const response = await fetch(request);
    return response;
  }
}

Step 7: Check Firewall Rules

bash
# Ensure Cloudflare IPs are allowed
iptables -I INPUT -s 173.245.48.0/20 -j ACCEPT

Step 8: Monitor Response Time

bash
curl -w "Time: %{time_total}s\n" https://example.com/path

Step 9: Implement Background Processing

```python # Use async tasks for long operations from celery import Celery app = Celery('tasks', broker='redis://localhost')

@app.task def long_running_task(): # Process in background pass ```

Step 10: Contact Support

bash
# If issue persists:
# Cloudflare Support
# Provide Ray ID from error
  • [Fix Cloudflare 521 Web Server Down](/articles/fix-cloudflare-521-web-server-down)
  • [Fix Cloudflare 522 Connection Timed Out](/articles/fix-cloudflare-522-connection-timed-out)