AlgoViz

Prerequisites of a monitoring system

easy 28 min

A monitoring system collects numbers from every program and machine, stores them with a time, answers questions about them and calls a person when something is wrong.

Chapter mnemonic

Four golden signals

How long is the wait? How many orders? How many wrong? How full is the grill?

The order rate stays flat, but every grill is busy. Which signal reveals that?

Saturation. It measures how much capacity is already in use.

Video lesson · Chapter 1 of 6

From one process to a time series

0:00 / 4:12

Theory

Read or listen first. About 2 min.

What it is

A metric is a number that describes a system at a moment, for example 120 requests a second or 67% of the processor in use. A monitoring system collects metrics again and again, stores each with its time, draws them, and checks rules against them.

The same metric over time is a time series. A monitoring system is mostly a store for time series with four jobs around it: collect, store, alert and show.

Why it exists

It answers three questions before users ask them: does it work, how fast is it, and is something about to break?

Numbers are cheap. One sample needs one or two bytes when stored well, so you can keep weeks of history for every service. Log lines are hundreds of times bigger. That is why people are called by metrics and then read logs to find the reason.

History also helps to plan: a disk that grows by 2% a week will be full in a known week.

A short history

  1. July 1999

    Tobias Oetiker releases RRDtool, a store of fixed size that keeps newer data finer than older data.

  2. 2012

    Prometheus is started at SoundCloud.

  3. 2016

    Prometheus joins the Cloud Native Computing Foundation as its second project, after Kubernetes.

  4. 18 July 2016

    Prometheus 1.0 is announced.

Words to know

Sample
One value with its time.
Time series
All samples of one metric with one set of labels.
Counter
A number that only grows, or starts again at zero after a restart.
Gauge
A number that goes up and down.
Histogram
Counts per bucket, such as how many requests took up to 0.1 s.
Summary
Percentiles that the program calculated itself.
Label
A name and a value that split a metric, such as method = GET.
Cardinality
How many label combinations, so how many time series exist.
Scrape
Fetching the current numbers from a program.

Understand it

Start here

The school nurse

Thermometers and charts
373738

The nurse does not follow every child all day. A few numbers on a schedule are enough.

At schoolIn the system
ThermometerMetric
The roundScrape
ChartTime series store and dashboard
Red line and bellAlert rule and message
Empty placeTarget down
BasketsHistogram buckets

The idea

Four jobs

Every monitoring system does these

  • Collect

    From programs, servers and databases. Prometheus, Telegraf, StatsD.

  • Store

    A time series database. Prometheus, InfluxDB, TimescaleDB.

  • Alert

    Check rules, send messages. Alertmanager, PagerDuty.

  • Show

    Charts and tables. Grafana, Kibana, Datadog.

And one language to ask with: "what was the processor doing yesterday at 3 pm?" or "how many errors a second, per service?". In Prometheus it is PromQL.

Kinds

Four kinds of metric

KindBehaviourUse it forLook at
CounterOnly grows, zero after a restartRequests, errors, bytes sentIts rate
GaugeUp and downMemory, queue length, open connectionsIts value
HistogramCounts per bucket, plus sum and countDurations, sizes of answersPercentiles over all servers
SummaryPercentiles made in the programOne program with fixed percentilesThe value of that one program
Text
# HELP http_requests_total Total HTTP requests# TYPE http_requests_total counterhttp_requests_total{method="GET",route="/api",status="200"} 1222http_requests_total{method="POST",route="/api",status="500"} 12# HELP http_request_duration_seconds Duration# TYPE http_request_duration_seconds histogramhttp_request_duration_seconds_bucket{le="0.1"} 950http_request_duration_seconds_bucket{le="0.5"} 1180http_request_duration_seconds_bucket{le="+Inf"} 1234http_request_duration_seconds_sum 160.4http_request_duration_seconds_count 1234
What a program shows on its page. The text format of Prometheus.

Buckets add up: the 1,180 requests of up to 0.5 s include the 950 of up to 0.1 s. le means less than or equal. The last bucket holds all requests, so it equals the count.

Which kind?

Rate

Reading a counter

The value 10,234 of a counter says little. Its growth says a lot. Take two samples, subtract, divide by the seconds between them.

Rate

rate=10,234−8,434300 s=6 requests per second\text{rate} = \frac{10{,}234 - 8{,}434}{300\,\text{s}} = 6\ \text{requests per second}
Two samples, five minutes apart.

If the second value is smaller, the program restarted. A good rate function sees that and counts from zero. This is why the rate is taken for each series first and added up after: adding counters first hides the restart.

Labels

Labels and their price

Labels split a metric so that you can filter and group: method, route, status. Each new combination is a new series that takes memory.

LabelsSeries
5 methods x 40 routes x 6 status codes1,200
the same on 20 servers24,000
plus 100,000 user ids2,400,000,000
The third row shows the worst case. Never use user ids, e-mail addresses or raw paths as labels.

Names matter too. Prometheus advises base units and the unit in the name: seconds, not milliseconds; _total for counters. http_request_duration_seconds explains itself, latency does not.

What to measure

RED and USE

RED, for servicesQuestionQuery
RateHow many requests a second?rate(http_requests_total[5m])
ErrorsWhich share fails?errors divided by all
DurationHow long?histogram_quantile
USE, for resourcesQuestionExample
UtilizationHow busy?CPU 75%
SaturationHow much waits?Disk queue of 12
ErrorsWhat fails?23 network errors

Which one where

ThingMethodNumbers
API gatewayREDRequests a second, error share, P99
Database serverUSE, and RED for its queriesCPU, connections, disk queue
MicroserviceREDThroughput, failures, response time
Kubernetes nodeUSECPU, memory, evicted pods

RED says that users suffer. USE shows which resource is the reason. The errors part of RED should be a share: 50 errors a second are a disaster at 100 requests and nothing at a million. Both methods in detail: load balancer monitoring.

Collect

Pull or push

Pull: Prometheus fetches

  • One place decides what is fetched and how often.
  • A failed fetch shows that a target is down.
  • Anybody can open the page and look.
  • Needs a list of targets and a way through the network.

Push: programs send

  • Works through firewalls.
  • Fits short jobs that end before a visit.
  • Events arrive at once.
  • Can flood the collector. Silence may mean dead or idle.

A scrape

Prometheus writes the series up for each target by itself.

The default interval of Prometheus is 1 minute. Many teams use 15 seconds. For short batch jobs there is a Pushgateway; its authors say that the outcome of a batch job is usually the only valid use for it.

How the collector knows its targets

SourceHow
KubernetesAsks the API server for pods and services
ConsulAsks the service registry
FilesReads a list that another tool writes
More in service discovery.

The whole

A usual stack

Prometheus, Alertmanager and Grafana

Prometheus fetches numbers from three services. It sends alerts to Alertmanager, which messages a person. Grafana reads from Prometheus. Prometheus copies samples to a long-term store.
Blue: reading. Orange: alerts. Pink: copies for long storage.

Prometheus itself evaluates the rules. Alertmanager receives the alerts and handles what follows: it groups equal ones, removes duplicates, respects silences and sends to e-mail, chat or a pager.

Life of an alert

The word for in a rule makes it wait, so that one spike wakes nobody.

Requirements

What to agree on first

It mustMeaning
CollectFrom programs, databases, machines
StoreBillions of samples with times
AnswerFilter, group, rate, percentile
AlertRules and messages
ShowCharts and tables
Separate teamsOne team cannot see or harm another's data
QualityA target to discuss
Writing1,000,000 samples a second
Simple questionUnder 100 ms
Space1 to 2 bytes per sample
Kept15 to 90 days fine, years coarse
Available99.9%, better than what it watches
AlertWithin 1 minute
Alert within 1 minute is not possible with a 1 minute interval plus a 5 minute wait in the rule. Choose them together.

Numbers

How big will it be?

Samples

1,000 services×100 series15 s≈6,667 samples/s=576 million per day\frac{1{,}000\ \text{services} \times 100\ \text{series}}{15\,\text{s}} \approx 6{,}667\ \text{samples/s} = 576\,\text{million per day}
100,000 series, one sample every 15 seconds: 5,760 samples a day for each.

Space

576 million×2 B≈1.15 GB per day576\,\text{million} \times 2\,\text{B} \approx 1.15\,\text{GB per day}
Prometheus says 1 to 2 bytes per sample on average. Its default is to keep 15 days: about 17 GB. With ten processes per service it is ten times as much.

The disk is rarely the problem. Memory is, because the newest samples of every active series are kept there. So count series, not services. One histogram with 12 buckets is 14 series per label combination, with sum and count.

To keep years, store averages of 5 minutes or 1 hour for old data. This is downsampling. Keep minimum and maximum too, or short spikes disappear.

Fail

Who watches the watcher?

FailureAnswer
Prometheus stopsTwo equal servers fetch the same targets; duplicates of alerts are removed
Both stop, or the networkA heartbeat alert that always fires; an outside service calls when it stops
It runs in the cluster it watchesPut the alert path elsewhere
Series explodeLimits per target, alert on growth
The page /metrics is publicOnly the inside may read it

A number or a log line?

Summary

The whole topic in one minute.

Programs count and show their numbers, a collector fetches them every few seconds, a time series store keeps them small, rules watch them and dashboards draw them.

Use counters for what happens, gauges for what is, and histograms for how long. Watch services with RED and resources with USE. Keep labels few, alert on what users feel, and watch the monitoring system from outside.

  • Collect, store, alert, show.
  • Counter for events, gauge for state, histogram for durations.
  • Rate first, then add up.
  • Few labels with few values.
  • RED for services, USE for resources.
  • Watch the monitoring from outside.

Sources