MoonitorMoonitor
All posts

502, 503 and 504 Errors: What They Mean and How to Monitor Them

Learn what 502, 503 and 504 errors mean, their common causes and how monitoring can pinpoint failures, catch intermittent 5xx errors and alert early.

17 min read
502, 503 and 504 Errors: What They Mean and How to Monitor Them

For 502 503 504 errors, each code tells you something different about a failed request. A 502 Bad Gateway means a gateway or proxy got an invalid response from the server behind it. In practice, proxies also return 502 when they can't connect to that server at all. A 503 Service Unavailable means the service can't take requests right now, because of overload, maintenance or running out of capacity. A 504 Gateway Timeout means the gateway waited too long for an answer and gave up. You can catch all three early by combining HTTP/S monitoring, response-time tracking and multi-region checks, then tuning your alert rules to match how your service is used.

That's the short version. The rest of this guide goes deeper: what each code means in practice, what usually causes it, and which monitor type is likely to warn you first. Grab a cuppa and let's work through it together. ☕

502 vs 503 vs 504 errors in plain terms 🧭

Picture this. It's 2am, your phone buzzes, and the site you shipped yesterday is showing a plain white page that says 'Bad Gateway'. Where do you look first? Your app? The database? The load balancer? Panic makes every layer look equally guilty.

The status code is your first clue, because it tells you what the gateway experienced when it tried to talk to whatever sits behind it.

Code Who is complaining What it usually signals Typical first check
502 Bad Gateway Proxy or load balancer Upstream sent an invalid response. Many proxies also use 502 when the upstream connection fails outright, such as a crashed app or a wrong port or socket Is the app process running, and does the proxy point at the right upstream?
503 Service Unavailable The server or an intermediary Reachable, but can't take the request right now (overload, maintenance mode, exhausted workers, rate limiting, no healthy targets) Capacity, worker and connection pool usage, maintenance flags
504 Gateway Timeout Proxy or load balancer Upstream didn't answer in time (slow queries, hung processes, network trouble) Slow queries, dependency latency, timeout settings at each layer

Comparison: Comparison table graphic with three columns for 502 Bad Gateway, 503 Service Unavailable and 504 Gateway Timeout, rows for what it means, who is complaining, common cause and first thing to check, clean flat design with colour-coded headers for 502, 503 and 504 Errors: What They Mean and How to Monitor

What is the difference between a 502 and a 504 error?

Here's the line I like to remember: a 502 is a bad answer, and a 504 is no answer in time. With a 502, the proxy dealt with the upstream and the result wasn't usable. With a 504, the proxy sat there waiting until the clock ran out.

There's a wrinkle, though. The HTTP standard (RFC 9110) defines 502 as the gateway receiving an invalid response from an inbound server, 503 as a temporary inability to handle the request, and 504 as no timely response from upstream. A refused connection isn't an HTTP response at all, but proxies such as Nginx commonly report it as a 502 anyway. So when you see a 502, read it as 'the proxy couldn't get a usable answer from upstream'. Don't assume the upstream actually replied with something malformed. Exact behaviour varies by proxy and cloud provider.

Typical causes behind 502 503 504 errors

Once you know which code you're looking at, the list of suspects gets much shorter. These are the culprits I see most often.

Common causes of 502 Bad Gateway errors

  • An app process that crashed or is mid-restart
  • A wrong upstream port or socket in your Nginx or HAProxy config
  • PHP-FPM or Gunicorn workers dying under memory pressure
  • A failed deploy that left nothing healthy listening
  • Container health check mismatches, where the orchestrator thinks a container is ready before the app is
  • A CDN that can't reach your origin because of a connection, DNS or TLS problem

Common causes of 503 Service Unavailable errors

  • Traffic spikes that outpace capacity
  • Connection pool or worker exhaustion
  • Planned maintenance pages (these are meant to return 503)
  • Autoscaling lag, where new capacity arrives a few minutes too late
  • A dependency outage that makes your app refuse work
  • Rate limiters or WAF rules rejecting legitimate traffic

Common causes of 504 Gateway Timeout errors

  • Slow database queries
  • Third-party API calls that hang
  • Mismatched timeouts, such as a proxy giving up at 30 seconds while the app is happy to work for 60
  • An overloaded upstream
  • Network or DNS problems between layers

A familiar deploy story

Most of us have lived through this one. You roll out a new version, the old containers shut down, and the new ones take twenty seconds to warm up. For those twenty seconds, the load balancer sends requests to something that isn't listening yet. The result is a short, sharp burst of 502s, and then everything looks fine. Nobody notices unless something happens to be watching at that moment. That's exactly why it's worth fixing with proper health checks and graceful shutdowns instead of shrugging it off.

One problem, different 5xx error codes

The same underlying issue can surface as different codes depending on timing and configuration. A deploy that leaves a load balancer with no healthy targets might produce 503s. If the targets stay reachable but the app or a dependency becomes slow, those same requests might exceed the proxy timeout and turn into 504s instead. The code tells you what the layer reporting the error saw, not necessarily what broke.

That also means the same code can come from your app, a reverse proxy, a load balancer or a CDN. An edge-generated 504, for example, often means the origin was too slow, not that the edge itself failed. For exact definitions, keep RFC 9110 (sections 15.6.3 to 15.6.5), the Nginx docs and your cloud provider's troubleshooting pages bookmarked.

Which monitor catches each 502, 503 or 504 error first?

This is the part I find most useful day to day. Knowing the cause is nice, but knowing which monitor is likely to speak up first is what shortens your next incident.

One caveat before the table. 'First' depends on your check interval, where your probes run, your alert thresholds and which layer is affected. A monitor checking every minute will usually beat one checking every ten, whatever the type. Treat the table as a sensible starting point, not a guarantee. It also helps to separate monitors that spot the symptom (an HTTP check failing) from those that hint at the cause (a DNS change, an expiring certificate, a missed heartbeat).

Error Likely culprit Early signal to look for Useful monitor (symptom or cause)
502 Crashed app or dead workers Non-2xx status, then missed background jobs HTTP/S monitoring with status code checks (symptom), plus heartbeat monitoring for workers that die alongside the app (cause)
502 / 503 Failed config change or error page served oddly Page loads but content is wrong or missing Keyword monitoring to confirm expected content actually renders (symptom)
503 Resource exhaustion Response times climbing before collapse, where the resource is the bottleneck Response-time analytics on key endpoints (symptom), plus port checks to confirm the service is listening
504 Slow dependency A specific endpoint slowing down API monitoring on the endpoint that calls the dependency, with response-time thresholds (symptom)
502 / 504 DNS or certificate problems at the edge Resolution changes, handshake failures, approaching expiry DNS monitoring and SSL certificate monitoring (cause)
504 (sometimes later) Silently stalled scheduled task A missed check-in, possibly hours earlier Cron job monitoring and heartbeat checks (cause)

Infographic: Matrix infographic mapping error codes (502, 503, 504) to likely culprits and the monitor type that would catch each first (HTTP/S, keyword, port, ping, heartbeat, DNS, SSL, response-time), using icons and connecting lines for 502, 503 and 504 Errors: What They Mean and How to Monitor

A few notes on why these pairings work:

  • Keyword monitoring earns its keep when a misconfigured proxy or cache serves an error page with a misleading 200. A plain status check says everything is fine, while a keyword check notices that your product name has vanished from the page.
  • Heartbeat monitoring catches the quiet stuff. A queue worker or nightly job that stalls rarely returns an error to anyone. It just stops checking in, and a while later your upstream may start timing out.
  • DNS and SSL checks rule out the boring causes. It's a bit embarrassing to spend an hour debugging a proxy when a certificate expired or a DNS record changed, so I like having those covered.

And to be honest with you, monitoring points you to the layer. Your logs and traces confirm the root cause. Think of monitors as the smoke alarm and logs as the fire investigation.

Why do intermittent 5xx errors come and go?

'Why do 503 errors come and go?' is one of the questions I hear most. The answer is that 503s are usually tied to capacity or state, and both change minute by minute. Load spikes, one unhealthy node behind a load balancer (so every third request fails), autoscaling lag, rate limiting kicking in and out, and short deploy windows can all do it.

This is where check frequency matters. If your monitor runs every 10 minutes and you have a 90-second burst of errors, there's a good chance it slips straight between two checks and you never hear about it. For critical endpoints, shorter intervals genuinely change what you can see.

Location matters too. A CDN edge or routing problem might only affect users in one region. A single monitoring location can miss that completely, or report a local blip as a total outage. Checking from several regions helps you tell a problem with one probe or network route from a broader outage, and Moonitor supports multi-region verification for exactly this reason.

There's a trade-off, though. If you only alert when several regions agree, a real incident confined to one region can be delayed or never alert at all. If most of your users are in the UK and your monitoring only confirms failures when a probe elsewhere also sees them, you could miss the very outage your customers are living through. Choose your confirmation rules based on where your users are and how much delay you can tolerate.

A few habits help here:

  • Use incident history to spot patterns. Errors at the same time every day usually point to a cron job, a backup or a traffic peak. Note whether your logs are in UTC or UK time (GMT/BST) so the clocks line up when you compare.
  • Monitor several URLs, not just the homepage. A healthy homepage can easily hide a failing API route.
  • Check the dull endpoints too, like login, checkout and health routes.

Here's a story that sticks with me. Imagine a small team that kept writing off a handful of evening 503s as a 'random glitch'. Nobody could reproduce it. Then they looked at their incident history and saw the errors lining up almost to the minute with a nightly data export that hogged the database. The glitch wasn't random at all. It ran on a schedule, and the history was what revealed it. Once they moved the job and added a heartbeat monitor on it, the 'mystery' was gone.

How to alert on 5xx errors without false alarms

Good alerting means getting the right notifications, not more of them. Here's a setup that works well for many teams.

  1. Decide what counts as a failure, and be precise about 5xx. Many monitors treat anything outside the accepted status range as a failure. So if you tell a monitor to expect a 2xx, it will usually flag 3xx redirects and 4xx client errors too, not only 5xx. That's often right for a homepage or health endpoint, but it isn't a '5xx only' alert. To alert on 5xx only, either set the accepted status codes to everything below 500 (for example 200-499), or use a rule such as 'fail when status is 500 or above' if your tool offers one. Then handle the rest deliberately. Use a separate monitor that expects a 301 or 404 for pages you've retired or moved. A 404 on a retired page isn't the same as a 502 on your API.
  2. Use multi-region verification where it fits. Requiring a failure from more than one location removes a lot of one-off network blips. Remember the trade-off, though. If your users are mostly in one region, or a regional incident would hurt you, consider a lower confirmation threshold or an immediate alert from your most important location.
  3. Set sensible confirmation rules. For non-critical endpoints, require a couple of consecutive failures before alerting. For critical ones, such as checkout or authentication, alert immediately.
  4. Route alerts to where your team actually lives. That might be email, Slack, Discord, Telegram, or webhooks into your on-call tooling. Use different channels by severity, so a flaky staging endpoint doesn't wake someone at 3am.
  5. Publish a status page. During an incident you don't want to hand-write updates in the middle of the chaos. A branded status page that reflects your monitors lets customers see what's happening while you focus on fixing it.
  6. Plan for maintenance. Expected 503s during planned work shouldn't page anyone. Pause the relevant monitors or note the scheduled window so you avoid alert fatigue.
  7. Tie it back to a target. A 99.9% availability objective allows roughly 43.2 minutes of downtime in a 30-day month, while 99.99% allows about 4.32 minutes. Having a number in mind helps you decide which blips deserve a page and which belong in a weekly review.

A gentle reminder: a quiet pager is a good thing, not a sign that monitoring isn't working. When alerts are rare and accurate, people trust them and respond faster when one arrives. That trust is hard to win back once a noisy week has taught everyone to ignore the channel.

Using response-time trends as an early warning for 504 errors ⏱️

Here's something that changed how I think about 504s: they often don't arrive out of nowhere. Response times frequently creep upward first, as a database, queue or dependency starts to strain. By the time users see a Gateway Timeout, the warning signs have sometimes been sitting in your graphs for hours. That said, not every timeout gives notice. A hung dependency or a sudden network fault can cause 504s with no gradual climb, so treat trends as a useful clue and not a guarantee.

A healthy baseline looks fairly flat, with small wobbles around a typical value. A problem looks like a slow climb, or a growing number of spikes. Averages can hide this, because a few very slow requests get smoothed away. Where you can, look at the spikes and the slow tail, not just the mean.

Chart: Line chart showing response time creeping upward over several hours, crossing a warning threshold line at 3 seconds before hitting a 30-second gateway timeout line where 504 errors begin, annotated with 'early warning' and 'users see 504s for 502, 503 and 504 Errors: What They Mean and How to Monitor

Some practical ways to use this:

  • Set thresholds well below your proxy timeout, based on your own baseline. In the chart above, the warning line sits at 3 seconds against a 30-second timeout, but that's only an illustration. If your endpoint normally answers in 200ms, 3 seconds is already a serious slowdown. If it's a heavy report that takes 8 seconds, it would alert constantly. Start from your normal response times and what your users will tolerate, then set the threshold comfortably above the usual wobble and well short of the timeout.
  • Compare before and after deploys. A step change in response time right after a release is a very clear regression signal.
  • Bring data to capacity conversations. 'Response times have crept up over the last month as traffic grew' is a far easier argument than 'it feels slower lately'.
  • Take the data with you. Moonitor has a full API and data export, so you can pull trends into your own dashboards and post-incident reviews.

Can monitoring tell you which layer is failing?

Short answer: it narrows things down quickly, but it won't replace logs and tracing for the final root cause. The trick is to combine monitor types, because each one tests a different layer.

Diagram: Layered architecture diagram showing DNS, CDN, load balancer or proxy, application, and database, with callouts showing which monitor type (ping, port, HTTP, keyword, heartbeat) tests each layer and the error code that typically appears when that layer fails for 502, 503 and 504 Errors: What They Mean and How to Monitor

Here's how I read the signals:

  • Ping or port monitor fails: likely a network or server-level issue, not the application.
  • Port is open but the HTTP check returns 502: the proxy is up, so the application behind it is the likely problem.
  • HTTP returns 503 with fast responses: the app is deliberately refusing traffic, whether for maintenance, rate limiting or capacity.
  • HTTP times out or returns 504 with rising response times: suspect slow dependencies or database load.
  • Failures from only some regions: look at your CDN, routing or DNS rather than your origin.
  • Heartbeat missed alongside 5xx errors: background workers or queues are probably involved.

A simple troubleshooting order for 502, 503 and 504 errors

When you're tired and the pressure is on, a fixed order stops you jumping around. Work from the outside in:

  1. DNS and SSL
  2. Network and port
  3. Proxy or load balancer
  4. Application
  5. Database and dependencies

Each step either clears a layer or points you at the culprit.

A simple monitoring setup to start with today

You don't need a grand monitoring strategy to get going. Here's a sensible first pass, focused on what to watch. The alert routing and rules above cover how to act on it.

  1. Add an HTTP/S monitor for your main site and each critical API endpoint, with the accepted status codes set as described in the alerting section.
  2. Add a keyword monitor on key pages to catch error pages served with misleading status codes.
  3. Add ping and port monitoring for your web server's reachability and listening ports. For databases, avoid exposing the port to the public internet just so a monitor can reach it. Run the check from inside your network, or use a private or agent-based approach, and keep access restricted.
  4. Add heartbeat monitors for the cron jobs and workers that keep your app healthy.
  5. Add SSL certificate and domain expiration monitoring, plus DNS record change detection, to rule out the boring causes.

Monitors are usually quick to create, so you can cover a real project in an afternoon. Moonitor offers a 7-day free trial with no credit card needed, so you can try it on live services and see whether it fits. Do check the current plan details and support options on the Moonitor site to make sure they suit your team.

FAQ about 502, 503 and 504 errors

What is the difference between a 502 and a 504 error?

A 502 means the gateway got an invalid response from the upstream server. Many proxies also return 502 when they can't connect to the upstream at all, for instance because the app has crashed. A 504 means the gateway didn't get a response before its timeout expired. In practice, 502 often points to a crashed or misconfigured app, while 504 points to something slow or hung.

Why do 503 errors come and go?

Because they are usually tied to capacity or state. Traffic spikes, exhausted workers, one unhealthy node behind a load balancer, deploys and rate limiting can all cause brief bursts of 503s that clear on their own. Frequent checks help you catch these short windows, and multi-region checks help you tell a local blip from a wider problem.

How do I alert on 5xx responses only?

Expecting a 2xx response will usually flag 3xx and 4xx responses as failures too, so it isn't a 5xx-only rule. Instead, set your HTTP/S monitor to accept every status below 500 (or use a 'fail on 500 and above' condition if available). Handle redirects and client errors with separate monitors where they matter. Then add consecutive-failure rules and, where it suits your user base, multi-region confirmation to cut down on momentary blips.

Can monitoring tell me which layer is failing?

It can point you in the right direction. Combining ping, port, HTTP, keyword and heartbeat monitors shows whether the network, proxy, application or a background job is the likely culprit. You will still want logs and traces to confirm the exact root cause.

Should I treat a 502 during a deploy differently from one at random times?

Yes. Brief 502s during a rolling restart may be expected, though they are worth fixing with health checks and graceful shutdowns. Random 502s outside deploy windows deserve more urgency, as they usually signal crashes or resource problems.

502 503 504 errors

Know before your users do.

Moonitor checks your sites, APIs and cron jobs around the clock, and verifies every failure from a second country before it ever pages you.