How to Fix HTTP 504 Gateway Timeout Error
In this tutorial, you'll learn about How to Fix HTTP 504 Gateway Timeout Error. We cover key concepts, practical examples, and best practices to help you understand and apply this topic effectively.
The Problem
Your API client receives:
HTTP/1.1 504 Gateway Timeout
The server acting as a gateway or proxy did not receive a timely response from the upstream server.
Quick Fix
1. Increase the proxy timeout
Nginx, Apache, and other proxies have a default timeout of 60 seconds:
# Nginx — increase timeout for slow endpoints
location /api/ {
proxy_pass http://backend:3000;
proxy_connect_timeout 30s;
proxy_read_timeout 120s;
proxy_send_timeout 120s;
}
Restart Nginx:
sudo nginx -s reload
2. Optimize the slow endpoint
The upstream server may be too slow. Log and profile the slow endpoint:
// Express.js — log slow requests
app.use((req, res, next) => {
const start = Date.now()
res.on('finish', () => {
const duration = Date.now() - start
if (duration > 5000) {
console.warn(`Slow request: ${req.method} ${req.url} - ${duration}ms`)
}
})
next()
})
3. Check the upstream server health
# Test the upstream directly
curl -v http://localhost:3000/health
# Check if it responds within a reasonable time
curl -w "Total time: %{time_total}s\n" -o /dev/null -s http://localhost:3000/health
4. Check the load balancer timeout
Cloud load balancers have their own timeout settings:
- AWS ALB: defaults to 60 seconds idle timeout
- GCP HTTP LB: defaults to 30 seconds
- Cloudflare: 100 seconds for free, up to 9000 seconds for enterprise
Increase these in the cloud provider console.
5. Use async processing
For long-running operations, return immediately and Process asynchronously:
// Wrong — waits for the long operation to complete
app.post('/api/reports/generate', async (req, res) => {
const report = await generateLargeReport()
res.json(report)
})
// Right — return a job ID immediately
app.post('/api/reports/generate', async (req, res) => {
const jobId = await queueReportGeneration()
res.status(202).json({ jobId, status: 'processing' })
})
6. Check for database query slowness
A slow database query may cause the proxy to timeout:
-- PostgreSQL — find slow queries
SELECT query, calls, mean_time
FROM pg_stat_statements
ORDER BY mean_time DESC
LIMIT 10;
Prevention
- Set proxy timeouts to at least 120 seconds for production.
- Monitor API response times and set alerts for slow endpoints.
- Use async processing with job queues for long-running tasks.
- Profile and optimize database queries regularly.
- Test with realistic data sizes during development.
Common Mistakes with 504 gateway timeout
- Using
returnto exit a function early instead of wrapping a pure value in the monad - Mixing let bindings with <- bindings in do notation, producing type errors
- Overlapping type class instances that cause GHC to reject the program with ambiguous dispatch errors
These mistakes appear frequently in real-world API code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro