AlgoViz

Load balancer monitoring

medium 30 min

Every request passes the load balancer, so it is the best place to see how the whole system feels from outside.

Video lesson · Chapter 1 of 5

The dashboard goes green as a server disappears

0:00 / 3:53

Theory

Read or listen first. About 2 min.

What it is

Monitoring a load balancer means collecting numbers and records about the traffic that passes it and about the servers behind it, and calling a person when users are affected.

Three kinds of data help. Metrics are numbers over time, such as requests per second. Logs are one record per event, such as one line per request. Traces follow one request through all the services it touches. They are often called the three pillars of observability.

Why it exists

The balancer sees every request, also those that never reach a server: refused connections, requests without a healthy server, broken certificates. The servers' own dashboards cannot show those.

It also compares. With twenty servers side by side it is easy to see that number seven is slower than the rest. Without that view one sick server hides in the average.

And somebody must notice before the users write. A good alert says that users are hurt, not that a processor is busy.

A short history

  1. 2010

    Google publishes the paper on Dapper, its tracing system, which shaped later tracing tools.

  2. 2012

    Brendan Gregg publishes the USE method. Prometheus is started at SoundCloud.

  3. July 2016

    Prometheus 1.0 is released.

  4. February 2017

    Peter Bourgon's article draws metrics, tracing and logging as three overlapping circles.

  5. August 2018

    Grafana Labs publishes an account of Tom Wilkie's RED method.

  6. February 2020

    W3C Trace Context becomes a web standard for passing a trace id between services.

Words to know

RED
Rate, Errors, Duration: three numbers for anything that serves requests.
USE
Utilization, Saturation, Errors: three questions for any resource.
Golden signals
Latency, traffic, errors and saturation, from Google's SRE book.
Percentile
P99 is the value that 99% of requests do not exceed.
Histogram
Counts per bucket of duration. Percentiles are calculated from it.
Cardinality
The number of different label combinations, so the number of time series stored.
SLO and error budget
The promised share of good requests, and the share that may fail.
Burn rate
How many times faster than allowed the error budget is used.
Active and passive check
Asking a server on purpose, and watching how real requests fare.

Understand it

Start here

A lifeguard, flags and a logbook

Watching the beach

The flag warns everybody at a glance. The book explains it later.

At the beachIn the system
Counting swimmers, height of wavesMetrics
FlagAlert level
LogbookLogs
Way of one swimmerTrace
Looking at each swimmer in turnHealth checks

The idea

Three pillars, three questions

What each one answers

  • Metrics

    Is something wrong, and since when? Cheap, kept long, no detail.

  • Traces

    Where in the chain is it? One request through all services.

  • Logs

    What exactly happened? Full detail, expensive, kept shortly.

  • Alerts

    Must a person act now? Built on metrics.

Where the data goes

Users send requests to a load balancer, which sends them to servers. The balancer gives metrics to a metrics store, which feeds dashboards and alerts, and access logs to a log store.
Solid: requests. Dashed: what we learn about them.

RED

Rate, errors, duration

LetterQuestionQuery in Prometheus style
RateHow many requests a second?sum(rate(lb_requests_total[5m]))
ErrorsWhich share fails?the rate with status=~"5.." divided by the rate of all
DurationHow long do they take?histogram_quantile over the bucket rates, see below
promql
sum by (service) (rate(lb_requests_total[5m]))sum by (service) (rate(lb_requests_total{status=~"5.."}[5m]))  / sum by (service) (rate(lb_requests_total[5m]))histogram_quantile(0.99,  sum by (service, le) (rate(lb_request_duration_seconds_bucket[5m])))
Three queries. A counter only grows, so always take its rate first. Keep the label le when you add up buckets.

What counts as an error needs a decision. 5xx always. 4xx are mostly the caller's mistake, but a jump of 401 or 404 after a release is a fault of ours. Show both, alert on 5xx.

Three lists that fit together

MethodLooks atLetters
REDServices that answer requestsRate, Errors, Duration
USEResources: CPU, memory, disk, connectionsUtilization, Saturation, Errors
Golden signalsUser-facing systemsLatency, traffic, errors, saturation
RED tells you that users suffer. USE helps you find which resource is the cause.

Whose error

The balancer's errors and the servers' errors

A 503 can come from a server, or from the balancer because there is no server. The two need different people. Cloud balancers count them apart: on an AWS application balancer HTTPCode_ELB_5XX_Count and HTTPCode_Target_5XX_Count.

You seeUsual meaning at an AWS application balancerLook at
502The server closed or answered nonsenseCrashes, keep-alive times, response headers
503No usable serverRegistration, health checks, deploys
504The server did not answer in timeSlow queries, timeouts
500 from the serverThe program failedIts logs
Connections refusedLimit reachedSaturation of the balancer

Errors go up: whose?

Duration

Percentiles, not averages

P50 is the normal user. P95 and P99 are the slow ones. P99 = 800 ms means that 1 request in 100 takes longer. The average of 99 requests of 50 ms and one of 5 seconds is about 100 ms, a duration that nobody had.

Why 1% matters to many users

P(at least one slow)=1−0.9920≈18%P(\text{at least one slow}) = 1 - 0.99^{20} \approx 18\%
A page that makes 20 requests meets the slowest 1% in nearly every fifth view.

A histogram is only as exact as its buckets. With borders 0.1, 0.25, 0.5 and 1 second, a P99 of 0.3 and one of 0.45 both lie between 0.25 and 0.5. Put borders where your promise is, for example at 300 ms.

Measure two durations: the total seen by the client and the server's part. If total grows and the server's part does not, the time goes into queues, the network or the client's own connection.

How many requests are open (Little's law)

L=λ⋅WL = \lambda \cdot W
1,000 requests a second that take 80 ms: 80 open. If they take 2 seconds: 2,000. Open connections are therefore an early sign of slowness.

Health

Active and passive checks

ActivePassive
HowAsks on purpose, for example every 5 to 30 sWatches real requests
Extra trafficYesNo
DetectsAlso without usersOnly with traffic, then often faster
Based onTCP connect, HTTP status, gRPC answerErrors and timeouts
MissesFaults only some requests hitA server nobody calls
Use both. Ejection of bad servers is explained in load balancing patterns.

Shallow check

  • Is the process able to serve?
  • Cheap and fast.
  • One sick server leaves, the rest stay.

Deep check

  • Also asks the database and the cache.
  • Finds broken connections.
  • A shared fault makes all servers unhealthy together.

One failure is not enough

Counting in a row keeps a server from flapping in and out.

A good answer is to have both and use them differently: the balancer asks the shallow one, the dashboard reads the deep one. A detailed answer such as the one below belongs to the inside only: versions and dependencies are useful to attackers.

JSON
{  "status": "healthy",  "checks": { "database": "ok", "cache": "ok", "disk": "ok" },  "version": "1.2.3",  "uptime_seconds": 86400}
GET /health/details, reachable from the inside only.

More on the circuit that opens when a server fails: circuit breaker. How names and lists of servers are kept: service discovery.

Logs

One structured line per request

A structured log is a record with named fields, usually JSON. A program can search, filter and count it. A sentence in free text needs a pattern for every question.

JSON
{  "timestamp": "2026-01-15T10:30:45.123Z",  "level": "info",  "type": "access",  "request_id": "abc-123-xyz",  "trace_id": "4bf92f3577b34da6a3ce929d0e0e4736",  "method": "GET",  "route": "/api/users/:id",  "status": 200,  "duration_ms": 45,  "backend_ms": 38,  "client_net": "192.0.2.0/24",  "backend": "server-01",  "user_agent": "Mozilla/5.0"}
An access log line. The client address is shortened on purpose.

The fields that save you at night: request id (to connect lines), duration in total and at the server, status, backend. Never log passwords, tokens or full query strings with personal data. Addresses of clients are personal data in many countries, so shorten them and delete early.

Collect them in one place: Elasticsearch with Logstash and Kibana, Splunk, Datadog, or Loki with Grafana. Cloud balancers can deliver them to storage. AWS says its access logs are best effort and arrive in files about every 5 minutes, so they are for analysis, not for counting money.

What logs cost

100,000,000×500 B=50 GB per day100{,}000{,}000 \times 500\,\text{B} = 50\,\text{GB per day}
100 million requests a day, 500 bytes a line. Keep all errors and slow requests, and a sample of the rest: at 5% that is about 2.5 GB.

Traces

Follow one request

An id that travels

The trace shows at once that payments took 900 of the 960 ms.

The W3C standard header is traceparent. An AWS application balancer adds its own, X-Amzn-Trace-Id. Recording every trace is costly. Head sampling decides at the start, tail sampling at the end, so that errors and slow requests are kept.

Labels

Cardinality: how metrics become expensive

Each combination of labels is a separate series. A label with the raw path, a user id or an address has no limit, and one day the metrics store runs out of memory.

Labels on a histogram with 12 series eachSeries
5 methods x 50 routes x 20 servers60,000
Raw paths: 5 x 100,000 x 20120,000,000
5 methods x 50 routes3,000
12 = 9 buckets, the last one to infinity, the sum and the count. Use the route pattern such as /users/:id, never the path.

Alerts

When to wake somebody

Useful first thresholds

Critical: act nowWarning: look today
Error rate over 5% for 5 minutesError rate over 1% for 10 minutes
All servers unhealthyOne or more servers unhealthy
P99 over 5 secondsP99 over 1 second
Certificate expires in 7 daysConnection pool over 80% used
Numbers to start with. Replace them by your own promise to users.

Send critical ones to a pager such as PagerDuty or to SMS, warnings to a chat such as Slack or to e-mail, and use a webhook for machines that can react by themselves.

Fixed limits have two faults. 4.9% for a whole day never alerts, and a short spike at night with ten requests does. A burn rate repairs both.

Burn rate

burn=error rate1−SLO\text{burn} = \frac{\text{error rate}}{1 - \text{SLO}}
Promise 99.9%, so 0.1% may fail. An error rate of 1.44% burns 14.4 times too fast: in one hour 14.4 / 720 = 2% of a 30-day budget.

Windows from Google's SRE workbook, for 99.9%

ActionLong windowShort windowBurn rateBudget used
Page1 hour5 minutes14.42%
Page6 hours30 minutes65%
Ticket3 days6 hours110%
Both windows must be over the rate. The short one makes the alert end soon after the repair.

Does it wake somebody?

Dashboard

One screen for the first minute

  1. 1

    Top row

    Rate, error share, P50 and P99, with the same hour last week for comparison.

  2. 2

    Second row

    Balancer errors and server errors apart, healthy servers out of all.

  3. 3

    Third row

    Per server: rate, errors, P99. Outliers stand out.

  4. 4

    Fourth row

    The balancer itself: connections, new connections a second, CPU, rejected connections, days until the certificate ends.

  5. 5

    Marks

    A line at every deploy. Most incidents begin at one.

Summary

The whole topic in one minute.

Measure rate, errors and duration at the balancer, per service and per server, with percentiles from histograms. Split its own errors from the servers' errors: they have different causes and different people.

Metrics say that something is wrong, traces say where, logs say what exactly. Alert on what users feel, with a burn rate, and let everything else be a ticket or a chart.

  • RED for services, USE for resources.
  • Separate the balancer's own errors from the servers'.
  • Percentiles from histograms; never average them.
  • Active and passive checks; shallow for the balancer.
  • Structured logs with request id, trace header passed on.
  • Alert on what users feel, with burn rates, and probe from outside.

Sources