Pidoku

Archive

This learning material is in the archive. It is not currently maintained and has not been updated with the latest information, so tool versions, prices and dates may be out of date.

Black-Box Probing

Module 3 Lesson 3.b 40 min Difficulty 2/5

Prerequisites 3.a

The idea in one minute#

White-box monitoring is what a service reports about itself: its metrics, logs and traces. Black-box monitoring tests the service from the outside, as a user would: resolve the DNS name, open a TLS connection, send a real request, check the answer. White-box tells you why; black-box tells you whether — including when the service is so broken it cannot report anything at all.

A prober (or synthetic monitor) runs scripted checks on a schedule from several locations. It is essential for low-traffic services, for catching DNS, certificate and network failures, and for testing whole user journeys end to end.

An analogy#

A shop can count its own sales (white-box), but a mystery shopper walking in from the street finds out that the front door is locked — something the till will never report.

A picture#

flowchart LR
  subgraph PROBES["Probers in three regions"]
    P1[":i-radar: eu-west"]
    P2[":i-radar: us-east"]
    P3[":i-radar: ap-south"]
  end
  P1 & P2 & P3 --> DNS[":i-globe: DNS"]
  DNS --> TLS[":i-lock: TLS handshake<br/><small>cert valid? days left?</small>"]
  TLS --> LB[":envoyproxy: Load balancer"]
  LB --> APP[":go: Service"]
  APP -.->|"white-box metrics"| PROM[":prometheus: Prometheus"]
  P1 & P2 & P3 -.->|"probe_success, probe_duration"| PROM
  PROM --> AM[":pagerduty: Alert if 2 of 3<br/>regions fail"]
  class P1,P2,P3 queue
  class DNS,TLS,LB io
  class APP compute
  class PROM memory
  class AM warn

How it really works#

What probes catch that metrics miss#

FailureService metricsBlack-box probe
Process crashed, no metrics scrapedup == 0 at bestFails immediately
DNS record deleted or misconfiguredNothing — no traffic arrivesFails at resolve
Certificate expiredNothing — handshake fails before your codeFails, and can warn 30 days early
Load balancer misroutingMetrics look normal (no traffic)Fails or gets the wrong response
Firewall / security group changeNothingFails from outside
CDN serving stale or error pagesOrigin is healthyContent check fails
Zero traffic at 3 a.m.No data, no alertConstant probe traffic, constant signal

Kinds of probe#

ProbeWhat it checksExample
ICMP / TCP connectHost reachable, port openDatabase port 5432 accepts connections
DNSName resolves to expected recordsapi.example.com has an A record
HTTP(S)Status, latency, body content, TLS validityGET /healthz returns 200 and contains "ok"
gRPC healthStandard health-check protocolgrpc.health.v1.Health/Check is SERVING
Scripted journeyMulti-step user flowLog in → add item → reach payment page (browser via Playwright, or API calls)

Designing good probes#

  1. Probe the real path. Through public DNS, CDN and load balancer — not the pod IP.
  2. Check content, not just status. A 200 with a “maintenance” page is a failure.
  3. Use a deep endpoint carefully. A health endpoint that checks every dependency will fail when any of them hiccups. Separate liveness (process is alive), readiness (can serve), and a journey probe that does real work with a test account.
  4. Probe from several places, and alert on a quorum (2 of 3 regions failing) so one prober’s bad network does not page anyone.
  5. Mark probe traffic (a header like x-synthetic: 1) so it can be excluded from — or deliberately included in — SLIs, and does not pollute business analytics.
  6. Probe frequently enough to be the SLI for quiet services. At one probe a minute from three regions, a low-traffic API gets 4,320 data points a day.
  7. Use test accounts and idempotent operations. A journey probe that really charges a card will eventually be noticed by finance.

The Prometheus blackbox exporter#

The standard open-source tool. Prometheus asks the exporter to probe a target; the exporter returns probe_success, probe_duration_seconds, probe_ssl_earliest_cert_expiry and more.

YAML
# blackbox.yml
modules:
  https_ok:
    prober: http
    timeout: 5s
    http:
      valid_status_codes: [200]
      fail_if_body_not_matches_regexp: ['"status":\s*"ok"']
      fail_if_not_ssl: true
      headers:
        x-synthetic: "1"
YAML
# prometheus.yml — scrape config
scrape_configs:
  - job_name: blackbox-checkout
    metrics_path: /probe
    params:
      module: [https_ok]
    static_configs:
      - targets: ["https://shop.example.com/api/healthz"]
    relabel_configs:
      - source_labels: [__address__]
        target_label: __param_target
      - source_labels: [__param_target]
        target_label: instance
      - target_label: __address__
        replacement: blackbox-exporter:9115

Two alerts every service should have:

YAML
- alert: EndpointDown
  expr: avg_over_time(probe_success{job="blackbox-checkout"}[5m]) < 0.5
  labels: { severity: page }
- alert: CertificateExpiresSoon
  expr: probe_ssl_earliest_cert_expiry - time() < 21 * 24 * 3600
  labels: { severity: ticket }

Hosted alternatives include Datadog Synthetics, Grafana Cloud Synthetic Monitoring (built on k6), Checkly and Pingdom. They give you probers in many regions without running them.

A worked example#

An internal admin API gets about 30 requests a day. Last month it was broken for 9 hours over a weekend after a certificate rotation went wrong: no traffic meant no errors, so no alert, and the first person to notice was a support agent on Monday.

Fix:

  1. A prober in two regions calls GET /api/v1/ping and a read-only journey (GET /api/v1/customers?limit=1 with a test token) every minute.
  2. The SLI for the admin API becomes probe success over a rolling 28 days — 2,880 probes a day instead of 30 real requests.
  3. A ticket fires 21 days before any certificate on the path expires.

The next broken rotation was caught 3 weeks early by the certificate alert, and the one after that (a wrong intermediate certificate) paged within 2 minutes.

Code#

A small multi-check prober: DNS resolve time, TLS handshake and days to certificate expiry, HTTP status, latency and body content. It talks to the network, so gocheck -run skips it; run it yourself with go run probe.go.

Go
// probe.go — a black-box prober: DNS, TLS expiry, HTTP status, latency and body content.
package main

import (
	"context"
	"fmt"
	"io"
	"net"
	"net/http"
	"net/url"
	"strings"
	"time"
)

type result struct {
	target       string
	ok           bool
	dns, total   time.Duration
	status       int
	certDaysLeft int
	reason       string
}

func probe(ctx context.Context, target, mustContain string) result {
	r := result{target: target, certDaysLeft: -1}
	u, err := url.Parse(target)
	if err != nil {
		r.reason = err.Error()
		return r
	}
	start := time.Now()
	if _, err := net.DefaultResolver.LookupHost(ctx, u.Hostname()); err != nil {
		r.reason = "dns: " + err.Error()
		return r
	}
	r.dns = time.Since(start)

	client := &http.Client{
		Timeout: 5 * time.Second,
		// Never follow a redirect to a login page and call it success.
		CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse },
	}
	req, _ := http.NewRequestWithContext(ctx, http.MethodGet, target, nil)
	req.Header.Set("x-synthetic", "1")
	req.Header.Set("User-Agent", "sre-prober/1.0")
	resp, err := client.Do(req)
	r.total = time.Since(start)
	if err != nil {
		r.reason = "request: " + err.Error()
		return r
	}
	defer resp.Body.Close()
	r.status = resp.StatusCode
	if resp.TLS != nil && len(resp.TLS.PeerCertificates) > 0 {
		leaf := resp.TLS.PeerCertificates[0]
		r.certDaysLeft = int(time.Until(leaf.NotAfter).Hours() / 24)
	}
	body, _ := io.ReadAll(io.LimitReader(resp.Body, 1<<20))
	switch {
	case resp.StatusCode != http.StatusOK:
		r.reason = fmt.Sprintf("status %d", resp.StatusCode)
	case mustContain != "" && !strings.Contains(string(body), mustContain):
		r.reason = fmt.Sprintf("body does not contain %q", mustContain)
	case r.certDaysLeft >= 0 && r.certDaysLeft < 21:
		r.ok = true
		r.reason = fmt.Sprintf("WARNING: certificate expires in %d days", r.certDaysLeft)
	default:
		r.ok = true
	}
	return r
}

func main() {
	checks := []struct{ url, contains string }{
		{"https://example.com/", "Example Domain"},
		{"https://go.dev/", "Go"},
		{"https://expired.badssl.com/", ""}, // a deliberately expired certificate
		{"https://does-not-exist.invalid/", ""},
	}
	for round := 1; round <= 2; round++ {
		fmt.Printf("── round %d ──\n", round)
		for _, c := range checks {
			ctx, cancel := context.WithTimeout(context.Background(), 8*time.Second)
			r := probe(ctx, c.url, c.contains)
			cancel()
			mark := "FAIL"
			if r.ok {
				mark = " ok "
			}
			fmt.Printf("[%s] %-34s dns %-7v total %-9v status %3d cert %3dd  %s\n",
				mark, r.target, r.dns.Round(time.Millisecond), r.total.Round(time.Millisecond),
				r.status, r.certDaysLeft, r.reason)
		}
		if round == 1 {
			time.Sleep(2 * time.Second)
		}
	}
}

Remember this#

  • White-box says why; black-box says whether — including when the service cannot report.
  • Probe the real path, check content, probe from several regions and alert on a quorum.
  • For low-traffic services, probe success can be the SLI.
  • Alert on certificate expiry weeks ahead; mark synthetic traffic.

Try it#

  1. Run probe.go. Which check fails at DNS, and which at TLS?
  2. Add a check against a service you own, with a mustContain string from its health endpoint.
  3. Write a journey probe for one critical user journey, using a test account. Which steps must be idempotent?

Check yourself#

  1. Name three failures a black-box probe catches that service metrics do not.
  2. Why should a probe not follow redirects blindly?
  3. Why alert on 2 of 3 probe regions rather than any one?
  4. What is the risk of a health endpoint that checks every dependency?

Sources#

↑↓ navigate↵ openesc close

100% drag to pan · scroll or pinch to zoom · double-click to zoom in