Python services in production · Scenario
502 and 504 errors from Nginx
Practise this out loud
Say your answer out loud to an AI interviewer that follows up, and get a score for it.
Practise by voiceThe interviewer asks
Users see random '502 Bad Gateway' errors from our Nginx, and the finance team gets '504 Gateway Timeout' on the monthly report page. The app is Django on Gunicorn in Kubernetes, behind Nginx. How do you work through this?
Then
Follow-ups the interviewer asks next
- What does a 502 from Nginx mean, and what does a 504 mean?
- Where do you look first for each?
- The 502s line up with deploys and scale-downs. Explain the chain of events.
- Someone sets every timeout to 600 seconds. What happens?
- How should timeouts be ordered from the load balancer down to the database?
- What's the proper fix for the report?
The answer
What a strong answer covers
- 502: Nginx got no valid response from the upstream: connection refused (nothing listening), reset, or closed early (a worker killed mid-request by Gunicorn's timeout, the OOM killer or a shutdown).
- 504: the upstream didn't answer within Nginx's
proxy_read_timeout(60 s by default). - Look at the exact Nginx error-log message, Gunicorn's log (
WORKER TIMEOUT,was sent SIGKILL! Perhaps out of memory?), traces of the slow endpoint, and the database's slow queries. - The 502 chain: on a rollout or scale-down the pod gets SIGTERM and Gunicorn stops accepting, but Nginx still sends new requests to that pod for a few seconds (refused), and requests longer than the graceful timeout are cut off. Fix: a readiness probe, a
preStopsleep of 10 to 15 seconds so the pod leaves the endpoints first, andterminationGracePeriodSecondslonger than the sleep plus Gunicorn'sgraceful_timeout. - The 504: the report takes about 75 s, past Nginx's 60 s, while Gunicorn (timeout 90) keeps a sync worker busy for nothing. Each click takes a worker out of service.
- 600 seconds everywhere: slow requests hold workers for 10 minutes, the queue grows, and a few clicks take the site down.
- Ordering: each inner layer gives up a little before the outer one (database
statement_timeout< app and HTTP-client timeouts < Gunicorntimeout< Nginxproxy_read_timeout< load balancer idle timeout), so the app fails first with a clear error. For keep-alive, the upstream's idle timeout must be longer than the proxy's in front of it. - Report: an index on
(account_id, posted_on), then a background job (Celery) that writes the file to S3 and sends a link, or monthly aggregates computed in advance.
The red pen
Common traps
Avoid:raising every timeout; treating 502 and 504 as the same thing; "add workers" without finding the slow query.
Practise this out loud
Say your answer out loud to an AI interviewer that follows up, and get a score for it.
Practise by voicePractise questions like this out loud
Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.