Visiting your website and see that it keeps loading? After a long wait, the annoying message appears: 502 Bad Gateway. What exactly does this mean, and what can you do to prevent this?
What causes a 502 Bad Gateway?
When your website throws a 502 error, it means that something is wrong between the server and an external connection. The most common cause is PHP processes crashing due to a stuck external connection. This is mostly annoying, but there are ways to reduce the risk of this happening again.
How does it work?
To understand the problem, it is good to understand how PHP requests are handled. With every request to your website, a PHP worker is deployed to process that request. Once it is done, the worker is released for new requests.
But imagine that your application (e.g. cURL or Guzzle) calls an external service, like a weather report. Normally this takes less than a second. But if that external service is slow or unresponsive, your application will be waiting, and the PHP worker will be busy.
If this happens repeatedly, all PHP workers can become busy, and new visitors will no longer be able to access the site, resulting in a 502 Bad Gateway.
What can you do to prevent this?
Unfortunately, there is no permanent solution to this problem. Even increasing the number of PHP workers only helps temporarily. But there are some steps you can take to reduce the chance of problems:
- Control which cURL requests your application makes and only do so when strictly necessary.
- Use APM tools such as New Relic or Datadog to quickly see which external endpoint is crashing.
- Reduce the standard cURL request timeout from 30 seconds to, for example, 5 seconds.
- Have a workaround in place that allows you to temporarily pause external connections.
By following these steps, you will reduce the chances of encountering a 502 Bad Gateway error and keep your website running smoothly.