SENIORCHAPTER 20

Synthetic monitoring and black-box probes

Ask the system from outside whether it works, and learn which faults a probe sees first and which it will never see in time

55 MINOBSERVABILITYUPDATED 2026-11-02
PREDICT

Payments starts failing 2% of charges. The gateway handles 5 requests per second, and a blackbox probe runs one checkout every 15 seconds. Which signal shows the fault first?

The chapters before this one built white-box telemetry: metrics, logs and traces that the services report about themselves. White-box telemetry is rich, cheap per question, and explains causes. It has one structural weakness. It depends on the system being alive enough to report. When the process is frozen, the network path from users is broken, or the bug is in something the service cannot see about itself, white-box telemetry goes quiet, and quiet looks like healthy.

Black-box monitoring tests the system from outside, as a user would, and reports only whether it worked and how long it took. It knows nothing about causes. In exchange it is honest about the one thing users care about.

Black-box and white-box, precisely

The Google SRE book (chapter 6) defines the two:

  • White-box monitoring is based on metrics exposed by the internals of the system: logs, interfaces like Prometheus /metrics, or an HTTP handler that emits internal statistics.
  • Black-box monitoring tests externally visible behaviour as a user would see it.

The book then says the useful thing: black-box monitoring is symptom-oriented and represents active, not predicted, problems. It recommends heavy use of white-box monitoring with modest but critical use of black-box monitoring. The reason for “modest” is arithmetic, which the next sections make concrete.

You already run one black-box check without naming it. Prometheus’s up metric is 1 when a scrape of /metrics succeeded and 0 when it did not. That is an external HTTP request with a pass/fail answer. It tests the wrong endpoint, though: /metrics can answer while /checkout hangs, because one is a counter dump and the other needs Postgres, Redis and two downstream services.

How a probe sees a fault

A probe is a sampler with a very low sampling rate. If a fault fails a fraction f of requests and the probe sends one request every T seconds, the number of probes until the first failure follows a geometric distribution with mean 1/f. The expected time to first failure is T / f.

fault f probe every 15 s: expected time to first failed probe gateway at 5 rps: failed requests per minute
gateway down 1.0 15 s or less 0 reported (nobody is counting)
payments fails 20% 0.2 75 s 60
payments fails 2% 0.02 12.5 min 6
payments slow for 5% 0.05 5 min to see one slow probe 15 slow requests

The two columns are opposites. For a total outage the probe answers in one interval and the white-box column is blank, because the thing that counts errors is the thing that is down. For a partial fault the white-box signal has hundreds of samples a minute and the probe has four.

Probes also cannot alert on one failure. A single probe over a real network fails occasionally for reasons unrelated to your service: a dropped packet, a DNS hiccup at the probe’s location, a garbage-collection pause. So you alert on several consecutive failures, or on failures from several locations at once, which pushes the detection time for partial faults out even further. The standard pattern is to require a quorum: page only when two of three probe locations have failed for two minutes.

Slowness is worse. A probe has a timeout, typically 5 to 10 s. A request that takes 2.5 s instead of 50 ms still succeeds, so probe_success stays at 1. You see it only in probe_duration_seconds, one point every 15 s, and one slow point is noise. Tail latency belongs to histograms.

The blackbox_exporter

The Prometheus project’s black-box prober is the blackbox_exporter. It is a small Go binary that listens on port 9115 and does nothing until asked. A request to /probe?target=<url>&module=<name> makes it run the probe defined by that module against that target, and the response is a Prometheus exposition of the result. Prometheus scrapes it like any exporter.

A module names a prober (http, tcp, icmp, dns or grpc) and its settings. For HTTP the settings you use most are:

setting what it does
timeout (module level) how long the probe waits before giving up; also capped by the scrape timeout
valid_status_codes accepted status codes; defaults to any 2xx
method, headers, body the request to send
fail_if_body_not_matches_regexp fail unless the body matches; the cheapest correctness check there is
fail_if_body_matches_regexp fail if the body contains, for example, an error page’s text
preferred_ip_protocol ip6 by default; set ip4 inside Docker networks, which are IPv4 only unless configured otherwise

The metrics it returns per probe include probe_success (1 or 0), probe_duration_seconds, probe_http_status_code, probe_failed_due_to_regex, and probe_http_duration_seconds with a phase label of resolve, connect, tls, processing or transfer. The phase split is what turns “the probe was slow” into “DNS was slow” or “the server took 2 s to send the first byte”. For HTTPS targets probe_ssl_earliest_cert_expiry gives the expiry time of the certificate chain, and alerting on it 14 days ahead prevents one of the most common self-inflicted outages there is.

The exporter sets User-Agent: Blackbox Exporter/<version> unless you override it. Override it. Your synthetic traffic should identify itself so every downstream system can tell it from users.

The relabelling trick

Prometheus normally scrapes the target. Here it has to scrape the exporter and pass the target as a URL parameter. The scrape config does this with relabelling. You list the URLs you want probed as targets, then:

  1. copy __address__ (the URL) into __param_target, which Prometheus sends as ?target=;
  2. copy __param_target into instance, so the series say what was probed rather than where the exporter runs;
  3. overwrite __address__ with the exporter’s host:port, so the scrape goes there.

The module can be fixed per job with params:, or chosen per target by putting it in a target label and copying that into __param_module. You will write the second form in the lab.

Multi-step synthetic checks

A single request answers “does this URL return 200 with the right body”. Real user journeys are sequences: log in, add to basket, pay, see the receipt. A fault in the hand-off between steps is invisible to a single-request probe and to every per-service metric, because each request on its own succeeds.

The demo app has such a hand-off. Payments stores each charge in Redis under its idempotency key, charge:order-<id>, for 24 hours. A retried charge with the same key must return the original charge and must not charge again. If Redis loses its data (a failover to an empty replica, an eviction policy that someone changed, a FLUSHALL in the wrong terminal), every new checkout still works and every metric stays green. What breaks is the promise: a retry now charges the customer twice. Only a check that remembers what happened before can see that.

A multi-step check is a script. The blackbox_exporter cannot run one; it probes one request per module. Hosted products run scripted journeys (Grafana Cloud Synthetic Monitoring, Datadog Synthetics, Checkly and others, often in a headless browser), and for an API journey a few dozen lines of Python that expose their result as Prometheus metrics do the same job. The lab writes one with three steps: buy, confirm the charge was stored, and replay the previous run’s charge and require the same charge id.

Design rules that hold for any multi-step check:

  • Report per step. synthetic_step_success{step="replay_previous"} tells the on-call engineer which promise broke. A single pass/fail for the whole journey does not.
  • Report staleness. Export the time of the last completed run. A probe that has stopped running looks exactly like a probe that is passing, unless you alert on its age.
  • Assert on content, not status. A 200 with "status": "failed" in the body is a failure.
  • Keep it deterministic. A reserved synthetic user, fixed inputs, and no dependence on data that real users change.

Synthetic traffic has side effects

Every probe is a real request. In the lab, a probe every 15 s creates 5,760 orders a day for user 999. In production the probe’s checkout creates real orders, reserves real stock, and, unless you stop it, charges a real card. The usual answers:

  • A test tenant or account whose orders are filtered out of reports and whose payments go to the provider’s sandbox.
  • An identifying header or user agent, so the probe can be excluded from analytics and, if you choose, from SLIs.
  • Clean-up, either a scheduled job or a probe step that cancels what it created.

Whether to count probes in your SLI is a real choice. Probes are not users, so counting them dilutes the user experience you promised. But at 4 am in a single-region product the probes may be most of the traffic, and they are the only reason the SLI has any samples at all. A common compromise: exclude synthetic traffic from the request-based SLI and keep a separate availability SLO measured by probes, which the alerting chapters can treat as a second, independent signal.

Where the probe runs

A probe tells you about the path between it and the target, and nothing else. The lab’s probe runs inside the same Docker network as the gateway, so it skips DNS, TLS, load balancers, CDNs and the public internet, which are where many real outages happen. In production:

  • Run probes from outside your failure domain: another region, another cloud, or a hosted service with probe locations on several continents.
  • Probe the public URL users hit, through the same DNS name, CDN and load balancer.
  • Run from at least three locations and require a quorum, so one location’s network trouble does not page you.
  • Remember that the probe’s result still flows through your alerting pipeline. If Prometheus and Alertmanager live in the cluster that is down, the probe sees the outage and nobody hears about it. Something outside has to watch the watcher; the platform module returns to that with dead-man switches.

Which one catches which fault

fault black-box white-box
process frozen or crashed first, within one probe interval up drops; ratio alerts go to no data and do not fire
DNS, TLS certificate, load balancer, CDN first, if the probe goes through them blind: requests never reach the service
a small fraction of requests fail minutes to tens of minutes first, within a minute
tail latency (a few % slow) almost never, as a page first, from the histogram
broken invariant across requests first, with a multi-step check blind: every request succeeds
one customer or one region only if a probe happens to be that customer first, with the right labels or wide events

Read it as a division of labour. Black-box probes catch the “is it up at all, from where users are” class, and they catch it fast and with no dependency on the system’s own telemetry. White-box telemetry catches everything partial and explains everything. Page on both, for different reasons, and do not let either pretend to be the other.

LAB Probe the checkout from outside, then see what each side catches first ~60 MIN
YOU NEEDDocker Desktop or Docker Engine with Compose v2the ATLAS repo cloned, working in labs/observabilitycurl and jqabout 45 minutes, most of it watching

You will add the blackbox_exporter to the demo stack, probe the gateway, add a three-step synthetic checkout, then flip the fault flags and record which side notices first.

1. Start the stack with telemetry on.

cd labs/observability
printf 'OTEL_SDK_DISABLED=false\nLOG_FORMAT=json\nOTEL_SEMCONV_STABILITY_OPT_IN=http/dup\n' > .env
docker compose --profile telemetry up -d --build
curl -s 'localhost:8080/checkout?user=999&items=1'
{"order_id":...,"status":"paid","ms":...}. User 999 is the synthetic user for this lab: inside the 1 to 1000 range, and not VIP because 999 is not divisible by 97.

2. Add the blackbox_exporter, pinned. Create blackbox/blackbox.yml:

modules:
  http_2xx:
    prober: http
    timeout: 5s
    http:
      preferred_ip_protocol: ip4
      valid_status_codes: [200]
      headers:
        User-Agent: atlas-synthetic/1.0
  http_checkout:
    prober: http
    timeout: 5s
    http:
      method: GET
      preferred_ip_protocol: ip4
      valid_status_codes: [200]
      headers:
        User-Agent: atlas-synthetic/1.0
      fail_if_body_not_matches_regexp:
        - '"status":\s*"paid"'

In compose.yaml, under services:, next to the other telemetry services (same indentation as prometheus:), add:

  blackbox:
    image: prom/blackbox-exporter:v0.26.0
    profiles: ["telemetry"]
    restart: unless-stopped
    command: ["--config.file=/etc/blackbox/blackbox.yml"]
    volumes: ["./blackbox/blackbox.yml:/etc/blackbox/blackbox.yml:ro"]
    ports: ["9115:9115"]

Start it and run one probe by hand with debug output:

docker compose --profile telemetry up -d blackbox
curl -s 'localhost:9115/probe?module=http_checkout&debug=true' \
  --data-urlencode 'target=http://gateway:8080/checkout?user=999&items=1' -G | sed -n '1,40p'
A log of the probe (resolving gateway, connecting, the request with your user agent, Received HTTP response status_code=200, the body regex matching) followed by the metrics it would return: probe_success 1, probe_http_status_code 200, probe_failed_due_to_regex 0 and five probe_http_duration_seconds{phase=...} lines with tls at 0 because this is plain HTTP. The debug=true view is the first thing to open when a probe fails and you do not know why.

3. Scrape it from Prometheus. In prometheus/prometheus.yml, add this job at the end of scrape_configs::

  - job_name: blackbox
    metrics_path: /probe
    scrape_interval: 15s
    scrape_timeout: 10s
    static_configs:
      - targets: ["http://gateway:8080/checkout?user=999&items=1"]
        labels: { module: http_checkout }
      - targets: ["http://gateway:8080/health"]
        labels: { module: http_2xx }
    relabel_configs:
      - source_labels: [__address__]
        target_label: __param_target
      - source_labels: [module]
        target_label: __param_module
      - source_labels: [__param_target]
        target_label: instance
      - target_label: __address__
        replacement: blackbox:9115

Reload and look:

curl -s -X POST localhost:9090/-/reload
sleep 30
curl -sG localhost:9090/api/v1/query --data-urlencode 'query=probe_success' \
  | jq -r '.data.result[] | "\(.metric.module)  \(.metric.instance)  \(.value[1])"'
curl -sG localhost:9090/api/v1/query \
  --data-urlencode 'query=probe_http_duration_seconds{module="http_checkout"}' \
  | jq -r '.data.result[] | "\(.metric.phase)\t\(.value[1])"'
Two probes, both 1, with the instance label set to the URL that was probed. The phase breakdown shows nearly all the time in processing (server think time, the full gateway to orders to payments round trip, tens of milliseconds) and well under a millisecond in resolve and connect. On a public URL resolve, connect and tls are often half the total.

4. Add the multi-step check. Create synthetic/checkout_probe.py:

"""Multi-step synthetic check for the demo app. Every PROBE_INTERVAL_S seconds:
  1. checkout         GET gateway /checkout as the synthetic user; body must say "paid"
  2. charge_recorded  replay that order's idempotency key at payments; must come back cached
  3. replay_previous  replay the previous run's order; must return the same charge_id, cached
Results are exposed for Prometheus on :9116/metrics."""
from __future__ import annotations

import os
import time

import httpx
from prometheus_client import Gauge, start_http_server

GATEWAY = os.getenv("GATEWAY_URL", "http://gateway:8080")
PAYMENTS = os.getenv("PAYMENTS_URL", "http://payments:8082")
INTERVAL = float(os.getenv("PROBE_INTERVAL_S", "15"))
USER = 999  # reserved synthetic user; not VIP
HEADERS = {"User-Agent": "atlas-synthetic/1.0"}

SUCCESS = Gauge("synthetic_step_success", "1 if the step passed on its last run", ["step"])
DURATION = Gauge("synthetic_step_duration_seconds", "How long the step took on its last run", ["step"])
LAST_RUN = Gauge("synthetic_last_run_timestamp_seconds", "Unix time the probe last completed a run")


def check(ok: bool, message: str) -> None:
    if not ok:
        raise RuntimeError(message)


def run_step(name, fn):
    start = time.perf_counter()
    try:
        result = fn()
        SUCCESS.labels(name).set(1)
        return result
    except Exception as exc:  # any failure, including timeouts and bad JSON, fails the step
        SUCCESS.labels(name).set(0)
        print(f"step {name} FAILED: {exc}", flush=True)
        return None
    finally:
        DURATION.labels(name).set(time.perf_counter() - start)


def main() -> None:
    start_http_server(9116)
    previous = None  # (order_id, charge_id) from the last run that got that far
    with httpx.Client(headers=HEADERS, timeout=10.0) as client:

        def replay(order_id: int) -> dict:
            r = client.post(f"{PAYMENTS}/charge", json={
                "order_id": order_id, "amount": 0, "idempotency_key": f"order-{order_id}"})
            r.raise_for_status()
            return r.json()

        while True:
            def checkout():
                r = client.get(f"{GATEWAY}/checkout", params={"user": USER, "items": 1})
                body = r.json()
                check(r.status_code == 200 and body.get("status") == "paid", f"{r.status_code} {body}")
                return body["order_id"]

            current = None
            order_id = run_step("checkout", checkout)
            if order_id is not None:
                def charge_recorded():
                    body = replay(order_id)
                    check(body.get("cached") is True, f"order {order_id} has no stored charge")
                    return body["charge_id"]

                charge_id = run_step("charge_recorded", charge_recorded)
                if charge_id:
                    current = (order_id, charge_id)

            if previous is not None:
                old_order, old_charge = previous

                def replay_previous():
                    body = replay(old_order)
                    check(body.get("cached") is True and body.get("charge_id") == old_charge,
                          f"order {old_order} charged again: {old_charge} -> {body.get('charge_id')}")

                run_step("replay_previous", replay_previous)

            previous = current or previous
            LAST_RUN.set_to_current_time()
            time.sleep(INTERVAL)


if __name__ == "__main__":
    main()

The gateway image already has httpx and prometheus_client, so reuse it rather than building another. Add to compose.yaml under services::

  synthetic:
    image: atlas-observability/gateway
    profiles: ["telemetry"]
    restart: unless-stopped
    command: ["python", "/probe/checkout_probe.py"]
    volumes: ["./synthetic:/probe:ro"]
    environment:
      GATEWAY_URL: http://gateway:8080
      PAYMENTS_URL: http://payments:8082
    depends_on:
      gateway: { condition: service_healthy }

and to prometheus/prometheus.yml:

  - job_name: synthetic
    static_configs:
      - targets: ["synthetic:9116"]
docker compose --profile telemetry up -d synthetic
curl -s -X POST localhost:9090/-/reload
sleep 45
curl -sG localhost:9090/api/v1/query --data-urlencode 'query=synthetic_step_success' \
  | jq -r '.data.result[] | "\(.metric.step)\t\(.value[1])"'
checkout 1, charge_recorded 1, replay_previous 1. docker compose logs synthetic is empty, because the script prints only failures. Each run made one real order for user 999 and two replays that payments answered from Redis without charging.

5. A fault black-box sees first: the gateway freezes. Define a helper that prints the current value of a PromQL query, then freeze the gateway process and watch three signals for 90 seconds:

q() { curl -sG localhost:9090/api/v1/query --data-urlencode "query=$1" | jq -r '[.data.result[].value[1]] | join(",")'; }
ERR='(sum(rate(http_requests_total{job="gateway",route="/checkout",status=~"5.."}[1m])) or vector(0)) / sum(rate(http_requests_total{job="gateway",route="/checkout"}[1m]))'
docker compose pause gateway
for i in $(seq 1 18); do
  printf '%s  probe=%-3s up=%-3s error_ratio=%s\n' "$(date +%T)" \
    "$(q 'probe_success{module="http_checkout"}')" "$(q 'up{job="gateway"}')" "$(q "$ERR")"
  sleep 5
done
docker compose unpause gateway
Within 15 to 20 seconds probe=0: the blackbox request times out after 5 s. up drops to 0 at the next 5 s scrape, because /metrics is frozen too. The error ratio keeps its last value, about 0, for up to a minute (the samples from before the pause are still in the [1m] window) and then prints nothing at all. An alert of the form error_ratio > 0.01 never fires during a total outage: there is no number to compare. Unless you page on up (and most teams do not, because a missed scrape is not a user symptom), the probe is the only thing that knows.

6. A fault only a multi-step check sees: Redis loses its data.

docker compose exec redis redis-cli flushall
sleep 30
q 'synthetic_step_success{step="replay_previous"}'
docker compose logs --since 1m synthetic
q "$ERR"
replay_previous was 0 for one run (it may already be back to 1 when you look, so read the log): step replay_previous FAILED: order 123 charged again: ch_... -> ch_.... Payments no longer had the idempotency key, so it treated the replay as a new charge and returned a new charge id. Every request returned 200, the error ratio stayed at 0, and payments’ latency did not move. In production this is a customer charged twice on retry, and the only signal is a check that remembers the previous answer. It fails once and then passes again, which is why the alert in step 8 fires on a single failure.

7. Faults white-box sees first: a few slow and failing charges.

FAULT_SLOW_PAYMENTS_PCT=5 FAULT_ERROR_RATE=0.02 docker compose --profile telemetry up -d payments
sleep 600
q 'count_over_time(probe_success{module="http_checkout"}[10m]) - sum_over_time(probe_success{module="http_checkout"}[10m])'
q 'max_over_time(probe_duration_seconds{module="http_checkout"}[10m])'
q "$ERR"
q 'histogram_quantile(0.99, sum by (le) (rate(http_request_duration_seconds_bucket{job="gateway",route="/checkout"}[5m])))'
Over ten minutes the blackbox job made 40 probes; the first query (failed probes) is most often 0 or 1, since you expect 40 × 0.02 = 0.8. The worst probe duration may or may not show a 1.5 to 3 s request; with 40 probes and 5% slow you expect two, and both count as success because they finished inside the 5 s timeout. Meanwhile the white-box error ratio sits near 0.02 and the gateway p99 is between 2 and 3 s, both visible within a couple of minutes of the change. Turn the faults off with docker compose --profile telemetry up -d payments.

8. Write the alerts each side is good for. Save as prometheus/rules/synthetic.yml:

groups:
  - name: synthetic
    rules:
      - alert: CheckoutProbeFailing
        expr: max_over_time(probe_success{module="http_checkout"}[1m]) == 0
        for: 1m
        labels: { severity: page }
        annotations:
          summary: "Synthetic checkout failed every probe for 2 minutes ({{ $labels.instance }})"
      - alert: IdempotencyBroken
        expr: synthetic_step_success{step="replay_previous"} == 0
        labels: { severity: page }
        annotations:
          summary: "A replayed charge was charged again: idempotency keys are not being honoured"
      - alert: SyntheticProbeStale
        expr: time() - synthetic_last_run_timestamp_seconds > 120 or absent(synthetic_last_run_timestamp_seconds)
        for: 2m
        labels: { severity: ticket }
        annotations:
          summary: "The synthetic checkout has not completed a run for 2 minutes"
curl -s -X POST localhost:9090/-/reload
curl -s localhost:9090/api/v1/rules | jq -r '.data.groups[] | select(.name=="synthetic") | .rules[] | "\(.name)\t\(.health)\t\(.state)"'
Three rules, health ok, state inactive. CheckoutProbeFailing needs four consecutive failed probes plus one minute, so a single dropped request does not page; pause the gateway for three minutes and it fires. IdempotencyBroken has no for: on purpose: one double charge is the incident. SyntheticProbeStale catches the probe itself dying, which would otherwise look like a probe that passes.
Stop Prometheus with docker compose stop prometheus, then pause the gateway again. The probe still fails every 15 s, and nobody is told: the blackbox_exporter only answers when asked, and the thing that asks, evaluates the rule and would send the alert is the thing you stopped. Black-box probing is only as independent as the pipeline that evaluates it. In production that is why hosted probes alert through their own path, and why the platform module adds a dead-man switch that pages when the alerting pipeline goes silent. Start Prometheus and unpause the gateway when you are done.
DECIDE

You run a checkout API in one cloud region at 400 requests per second, with burn-rate alerts on the gateway's error ratio and latency SLOs. The platform team offers hosted synthetic probes from five locations, every 60 seconds, and asks what you want them to page on.

READING
  1. BOOK
    Monitoring Distributed Systems (Site Reliability Engineering, chapter 6) Rob Ewaschuk, ed. Beyer et al., 2016

    The source of the black-box and white-box definitions and the advice to use black-box monitoring modestly but critically. Short, and still the clearest statement of what should page. Read: the sections 'Definitions', 'Black-Box Versus White-Box' and 'The Four Golden Signals'.

  2. CODE
    blackbox_exporter README and CONFIGURATION.md Prometheus project

    The authoritative list of prober modules and their settings, plus the example Prometheus scrape config with the relabelling this lab uses. Check the configuration file against the tag you pin; settings move between releases.

  3. DOC
    Understanding and using the multi-target exporter pattern Prometheus docs

    Walks through the blackbox_exporter's /probe endpoint and the __param_target relabelling step by step. Read it if the relabel block in step 3 felt like magic.

  4. BOOK
    Practical Alerting from Time-Series Data (Site Reliability Engineering, chapter 10) Jamie Wilkinson, ed. Beyer et al., 2016

    Describes Borgmon, the ancestor of Prometheus, and Prober, Google's black-box checker that validates response payloads and exports results as time series. It is the design this lab rebuilds with the blackbox_exporter. Read: the sections 'Black-Box Monitoring' and 'Alerting'; skim the rest for history.

All companies and people in these examples are fictional. Any resemblance to a real business or person is unintended.

RECALL CARDS Tap to flip. They join your review deck when you mark the lesson complete.
NEXT: Debugging with traces: exemplars, span links, critical path →