Sub topic 13
Metrics, Logs and Troubleshooting
This chapter assumes you know what a load balancer does, the difference between Layer 4 and Layer 7 balancing, and how health checks work. It also assumes you can read an NGINX or HAProxy configuration file and use basic command-line tools. The goal is to show you what to measure, what to log, and how to work from a symptom to a cause when traffic misbehaves.
Why the load balancer is a good place to observe
Every request passes through the load balancer. That makes it a natural vantage point. It sees the client's view (how long a request took, whether it succeeded) and the backend's view (which server answered, how long it took to respond). Comparing those two views is the core of most troubleshooting.
Observability here has three sources:
- Metrics are numbers sampled over time, such as requests per second or active connections. They tell you that something changed.
- Logs are one record per request or connection. They tell you which requests were affected.
- Active probes and manual tests are requests you send yourself. They tell you why, by isolating one hop at a time.
Health checks, covered in an earlier chapter, feed all three. A backend that flips between up and down shows up as a metric, a log line, and a probe result.
Metrics worth collecting
The exact names differ between products, but the categories are consistent. A common grouping is rate, errors, and duration for traffic, plus saturation and backend state for capacity.
| Category | What to track | What it tells you |
|---|---|---|
| Request rate | Requests per second, new connections per second | Load level and sudden spikes or drops |
| Errors | Count of 4xx and 5xx responses, split by who generated them | Whether failures come from clients, the balancer, or backends |
| Latency | Request time, backend response time, queue time | Where time is being spent |
| Concurrency | Active connections, connections per backend | Saturation and how evenly load is spread |
| Backend state | Number of healthy and unhealthy servers, state changes | Capacity and flapping |
| Queueing | Requests waiting for a free backend slot | Overload before errors appear |
| TLS | Handshake rate, handshake failures, protocol versions | Certificate and client compatibility problems |
Percentiles, not averages
Average latency hides problems. If 99 requests take 50 ms and one takes 5 seconds, the average is about 100 ms, which looks fine. Track the 50th, 95th and 99th percentiles (p50, p95, p99). A p99 of 5 seconds means one request in a hundred is very slow, and at scale that is many users.
Per-backend breakdowns
Totals can look healthy while one backend is failing. Always break request count, error rate and latency down by backend. Three patterns are worth recognizing:
- One backend with a much higher error rate than its peers usually means a bad deploy or a sick host.
- One backend with much higher latency and more active connections often means it is slow, so least-connections or queue buildup is piling work onto it.
- One backend receiving far more traffic than its peers points at the algorithm, weights, or session persistence.
Where to get the numbers
HAProxy exposes a statistics page and a Prometheus endpoint, and it also has a runtime socket. NGINX open source offers a small stub_status page with basic counters. Per-upstream metrics in NGINX usually come from log analysis or from the commercial version's API. Cloud load balancers publish metrics to the provider's monitoring service.
This NGINX example exposes basic counters on a local-only port:
server {
listen 127.0.0.1:8081;
location /nginx_status {
stub_status;
allow 127.0.0.1;
deny all;
}
}Requesting it returns active connections, accepted and handled connection counts, and total requests:
curl -s http://127.0.0.1:8081/nginx_statusThe output looks like this:
Active connections: 291
server accepts handled requests
16630948 16630948 31070465
Reading: 6 Writing: 179 Waiting: 106If accepts is larger than handled, NGINX dropped connections, usually because it hit a resource limit such as the worker connection limit. Binding the status page to localhost and denying other addresses keeps internal data away from the public internet.
Logs: one line per request
Default access logs often leave out the fields you need most. For a load balancer, add the selected backend, the timing breakdown, and the upstream status.
NGINX log format
log_format lb '$remote_addr [$time_local] "$request" '
'$status $body_bytes_sent '
'rt=$request_time '
'upstream=$upstream_addr '
'us=$upstream_status '
'urt=$upstream_response_time '
'uct=$upstream_connect_time';
access_log /var/log/nginx/lb_access.log lb;The fields have specific meanings:
$request_timeis the total time from the first byte read from the client until the last byte sent back.$upstream_response_timeis how long the backend took.$upstream_connect_timeis how long it took to open the connection to the backend.$upstream_statusis the status the backend returned. It can differ from$statusif NGINX replaced the response, for example with a 502 or 504 of its own.
If a request is retried on another server, NGINX lists several values separated by commas, for example upstream=10.0.0.11:8080, 10.0.0.12:8080. Those retries are a useful signal on their own. A rising share of multi-value lines means a backend is failing and traffic is being absorbed by retries.
HAProxy log format
HAProxy in HTTP mode writes a rich default log. A key piece is the termination state, a four-character code that explains how and why a session ended. Add option httplog to a frontend or defaults section to enable it:
defaults
mode http
log global
option httplog
timeout connect 5s
timeout client 30s
timeout server 30sA line then includes timers in the form Tq/Tw/Tc/Tr/Tt:
Tqis time to receive the client's request.Twis time spent waiting in queue.Tcis time to connect to the backend.Tris time waiting for the backend's response.Ttis total time.
A large Tw means the backend is saturated and requests are queuing. A large Tc suggests network trouble or a backend that is slow to accept. A large Tr means the application itself is slow.
The first two characters of the termination state matter most. The first says which side caused the end, and the second says what stage the session was in.
| Code | Meaning |
|---|---|
| `--` | Normal completion |
| `sH` | Server timeout while waiting for response headers |
| `SC` | Server refused or reset the connection at connect time |
| `cD` | Client timeout during the data phase |
| `CD` | Client closed the connection during data transfer |
| `sQ` | Request spent too long in the queue |
| `PH` | Proxy rejected the response headers as invalid |
Logging X-Request-Id helps trace a request across the balancer and the application. If the client did not supply one, generate it at the balancer and pass it to the backend, then log it on both sides.
Reading status codes at the balancer
Which component produced an error matters more than the number itself. Most balancer-related errors are 5xx codes.
| Status | Common meaning at a load balancer | First place to look |
|---|---|---|
| 502 Bad Gateway | The balancer got an invalid response, or the connection was refused or reset | Is the backend process running and listening on that port? |
| 503 Service Unavailable | No healthy backend, or the backend is overloaded | Health check state and backend count |
| 504 Gateway Timeout | The backend did not answer in time | Backend latency and timeout settings |
| 499 (NGINX only, in logs) | The client closed the connection before the response | Client-side timeouts, slow responses |
| 400 or 413 | Request too large or malformed, rejected by the balancer | Header and body size limits |
A 503 with an empty backend list is the clearest failure. All servers are marked down, so there is nothing to send traffic to. A common cause is a health check that tests the wrong thing, such as a path that requires authentication, which makes every server look unhealthy at the same moment.
A systematic way to troubleshoot
Work from the outside in, and test one hop at a time. The following diagram shows the questions to ask.
Step 1: Can you reach the balancer?
Test from a client network. Separate DNS from connectivity from TLS.
dig +short app.example.com
curl -sv --connect-timeout 5 https://app.example.com/healthz -o /dev/nullIf DNS returns an unexpected address, the problem is before the balancer. If the connection hangs, suspect a firewall, a security group, or a virtual IP that is not active on any node. If the TLS handshake fails, check the certificate chain and the protocol versions offered.
Step 2: Can the balancer reach the backend?
Log in to the balancer host and test the backend directly, using the same address and port as the configuration.
curl -sv --connect-timeout 3 http://10.0.0.11:8080/healthzThis often finds the real fault. A backend that works from your laptop may be unreachable from the balancer because of a firewall rule or a different network segment. Also check that the application listens on the address the balancer uses. A service bound only to 127.0.0.1 cannot be reached from another host.
Step 3: Compare the two sides
Request the same URL through the balancer and directly to a backend, and compare the results. If the direct request is fast and correct but the balanced one is slow or wrong, the cause is in the balancer layer: timeouts, buffering, header handling, or TLS. If both are bad, the application is at fault.
Step 4: Use the logs to find a pattern
Filter by status and group by backend. This shell command counts 5xx responses per upstream from the NGINX format shown earlier:
awk '$0 ~ / 5[0-9][0-9] / { for (i=1;i<=NF;i++) if ($i ~ /^upstream=/) c[$i]++ } END { for (k in c) print c[k], k }' /var/log/nginx/lb_access.log | sort -rnOne address dominating the output points at one bad server. An even spread points at a shared dependency, such as a database, or at the balancer itself.
Common problems and their signatures
Uneven load
Symptoms are one server at high CPU while others idle. Causes include sticky sessions pinning heavy users to one server, round robin with requests of very different cost, mismatched weights, or long-lived connections such as WebSockets that stay on their original server. Least connections helps with the second and third cases. For long-lived connections, watch connection counts per backend and rebalance by draining.
Flapping backends
A server cycles between up and down. In HAProxy the log shows repeated state changes. Common causes are health check timeouts shorter than the application's occasional slow responses, a check that exercises an expensive code path, or a backend that restarts in a crash loop. Raise the number of failures needed to mark a server down, make the check cheap, and look at the application's own logs.
Intermittent 502 errors after idle periods
The backend closed an idle keep-alive connection at about the same moment the balancer reused it. The balancer sends a request on a connection the server has already closed and gets a reset. The fix is to make the balancer's idle timeout for backend connections shorter than the backend's own keep-alive timeout, so the balancer closes first.
504 errors on specific endpoints
Large reports or exports can exceed the proxy's read timeout. Check timeout server in HAProxy or proxy_read_timeout in NGINX. Raise it for that route only, or move the work to an asynchronous job, rather than raising it globally.
Wrong client IP in application logs
Backends see the balancer's address instead of the client's. The balancer must pass the original address in a header such as X-Forwarded-For, and the application must be configured to trust that header only from the balancer's address. Trusting it from anyone lets clients forge their IP.
Sessions lost or users logged out
Check whether persistence is configured, whether the cookie is set and returned, and whether the balancer is sending the same user to different servers after a backend change. Also confirm that your health check does not mark the user's server down briefly, which breaks the stickiness mapping.
Alerts that are worth having
Alert on conditions that need a person to act, not on every fluctuation.
- No healthy backends in a pool, or fewer than the number needed to carry peak load.
- 5xx rate above a threshold for several minutes, measured as a share of all requests.
- p95 or p99 backend latency well above its normal level.
- Queue depth above zero for a sustained period.
- Frequent backend state changes within a short window.
- Certificate expiry within a set number of days.
- Connection count approaching the configured limit.
Pair each alert with a link to the relevant dashboard and a short runbook that starts with the steps in the diagram above.
Putting it together
When a report arrives that "the site is slow", you can follow a sequence. Check the dashboard for a change in request rate, error share, or backend latency. Look at per-backend panels to see whether the problem is one server or all of them. Pull a sample of slow log lines and read the timing fields to see whether time went to queueing, connecting, or the backend's response. Then reproduce the request directly against one backend. Each step narrows the cause from the whole system to one component.
Exercise
An NGINX access log line shows rt=30.002 upstream=10.0.0.12:8080 us=504 urt=30.001 uct=0.001. Where is the fault most likely to be, and what is your first action?
Show answer
The connection to the backend opened in 1 ms (uct), so the network path and listener are fine. The backend then spent about 30 seconds without answering (urt), which matches a 30-second read timeout, so the balancer returned 504. The fault is in the application on 10.0.0.12 being slow or stuck. First, request the same URL directly against 10.0.0.12:8080 and compare with other backends. Then check that server's application logs and its per-backend latency and error panels. Raise the timeout only if the request is legitimately long-running.
Exercise
Users report occasional 502 errors, mostly on requests that come after a quiet period. Backends are healthy and CPU is low. What is a likely cause, and how do you fix it?
Show answer
The backend probably closes idle keep-alive connections before the balancer does, so the balancer reuses a connection that is already closed and gets a reset. Set the balancer's idle timeout for backend connections lower than the backend's keep-alive timeout, or raise the backend's keep-alive timeout above the balancer's, so the balancer always closes first.
Exercise
Total 5xx rate is 2%, but the dashboard shows all errors come from one of four backends. Which two checks would you run next?
Show answer
First, request a known URL directly against that backend and compare the response with the other three, to see whether it fails on its own. Second, look at its application logs and recent deploy history for a bad release or a failing dependency. If it fails, remove it from the pool, preferably by draining it, while you fix it. Also review its health check, because a check that passes while real requests fail needs to test something closer to real traffic.