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
Error 504 Ray ID: xxx-xxx-xxx
Gateway Timeout
The web server reported a gateway time-out error.Why This Happens
- 1.Origin server slow
- 2.Long-running request
- 3.Server overload
- 4.Network latency
- 5.Application processing time
Step 1: Check Origin Server
curl -I https://origin-server.com/path
time curl https://origin-server.com/pathStep 2: Check Server Resources
top -bn1 | head -20
free -m
df -hStep 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
# In Cloudflare dashboard:
# Rules > Page Rules
# Cache Level: Cache Everything
# Edge Cache TTL: 1 hourStep 5: Enable Cloudflare Caching
# Origin server headers:
Cache-Control: public, max-age=3600Step 6: Use Workers for Long Requests
// Cloudflare Worker
export default {
async fetch(request) {
const response = await fetch(request);
return response;
}
}Step 7: Check Firewall Rules
# Ensure Cloudflare IPs are allowed
iptables -I INPUT -s 173.245.48.0/20 -j ACCEPTStep 8: Monitor Response Time
curl -w "Time: %{time_total}s\n" https://example.com/pathStep 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
# If issue persists:
# Cloudflare Support
# Provide Ray ID from errorRelated Issues
- [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)