Skip to main content
CRUCIBLE
Legacy Reference Archive: This 44-chapter book reference has been distilled into Academy A01 (8 Executable Modules) with Tier-Adaptive Productive Failure, Kore/Puck voice, and live Firecracker labs.
Open Academy A01 →
COURSE 0 · SERVER BUILDING & LIFECYCLE MASTERY

Zero-to-Production Linux, Containers, Networking & Recovery

PROGRESS: 0 / 72 (0%)0/44L · 0Q · 0VM
CH 16 · PART IV · WORKED LABS & FULL LIFECYCLE (CH 14–24) · 941 WORDS (5 MIN)

16 Prove monitoring and disaster recovery

GET /metrics requires a separate MONITOR_TOKEN. A tenant API token does not grant monitoring access. The endpoint exports jobs by state and oldest queued age without per-user or per-job labels.

FULL WAR-ROOM →
INTERACTIVE OBSERVABILITY · CLICK ANY STAGE TO TEST

Golden Signals Loop: /metrics -> Prometheus -> Alert Rules -> Runbook

How production teams catch silent degradation before customers tweet about it.

scrapesfirespagesApp /metricsLatency · Errors · PoolsPrometheus TSDB15s Scrape IntervalAlertmanagerDedup · Route · SilenceVerified RecoveryObserve -> Fix -> Prove
SELECTED LAYER · APP /METRICS
Exposes real-time counters and histograms (request p99, 5xx rate, PgBouncer cl_waiting, open FDs).
Common failure: High-cardinality labels (like user_id) exploding Prometheus memory usage.
$ curl -s http://127.0.0.1:8000/health

Files: monitoring/, curl -sf http://127.0.0.1:8000/health, pg-xray. Environment: isolated local sockets and temporary data directories. The receipts in proof/ identify what actually ran.

From metric to delivered alert

GET /metrics requires a separate MONITOR_TOKEN. A tenant API token does not grant monitoring access. The endpoint exports jobs by state and oldest queued age without per-user or per-job labels. Keep the monitoring endpoint private, and give Prometheus its credential through a restrictive file. A monitoring system that cannot authenticate should alert as a scrape failure rather than pretend the queue is empty.

monitoring/prometheus.yml scrapes the local Compose API. alerts.yml declares APIUnavailable after two minutes of failed scrapes and QueueStalled after two minutes with queue age over 120 seconds. Their thresholds are example operational choices, not universal service objectives. alerts.test.yml proves both firing and clearing behavior using synthetic series:

bash
cd monitoring
promtool check rules alerts.yml
promtool test rules alerts.test.yml

alertmanager.yml routes to a local webhook receiver and sends resolved notifications. Set the receiver to an approved incident destination before remote use, protect its credentials, and test delivery during an actual controlled fault. An alert rule turning red in Prometheus does not prove anyone was notified.

The local integration script starts real API processes, a TLS endpoint, Prometheus, Alertmanager and a loopback receiver. It submits work while the worker is stopped, waits for an accelerated alert, records the firing delivery, starts the worker, then records the resolved delivery. Production-duration rules are tested separately with promtool. All owned processes and temporary secrets are cleaned up.

Install native Prometheus and Alertmanager from their official releases, verify checksums, then run from the example directory:

bash
ALERTMANAGER_BINARY=/absolute/path/to/alertmanager   uv run python ../../curl -sf http://127.0.0.1:8000/health

The Grafana dashboard JSON supplies a starting view; import it and choose the intended Prometheus datasource. Its UI import has not been exercised by the integration script. Extend observability with request/error/latency metrics, worker heartbeat, host disk and inode monitoring, DB connections, backup age and restore freshness. Correlate request/job IDs in protected logs. A complete tracing backend is an optional deployment extension, not supplied evidence.

Operate on a schedule

Daily: inspect user-visible completion, alert delivery, oldest queued work, backup success and disk growth. Weekly: review dependency updates, failed jobs, capacity trends and stale credentials; test one low-risk failure. Monthly: restore a selected backup, review access, patch through staging, rehearse rollback and update the inventory. These cadences are starting points; shorten them where data-loss tolerance or exposure requires it.

For patching, identify the affected layer, read compatibility notes, test the exact artifact against a restored staging dataset, take a recovery point, schedule the change, monitor, and retain the previous compatible artifact. Do not automatically reboot a machine hosting unrelated work. Plan a maintenance window and verify service recovery after an approved reboot.

For an incident, first preserve the impact timestamp, release, symptom and relevant logs. Stop a bad rollout before attempting multiple speculative fixes. Record the mitigation separately from the root cause. Assign follow-up tests and owners so the incident produces a durable improvement.

Encrypted backup and fresh-cluster restore

The native PostgreSQL drill creates two private temporary database clusters on free loopback ports. It runs migrations, grants a restricted runtime role, writes and completes a job, then stops and restarts the database process. It verifies the completed result is still readable. This proves persistence across database process restart without using Docker tmpfs.

Next it obtains a custom-format logical dump, encrypts it to a newly generated age recipient, decrypts it with the matching private identity, compares plaintext digests, restores into the second cluster, and reads the result through a new application instance. It also proves duplicate-request identity survived and corrupted ciphertext is rejected. The receipt reports measured restore-and-verification duration for this tiny fixture.

From the example directory, with matching native PostgreSQL client/server tools and age installed:

bash
uv run python ../../pg-xray

The script never targets an existing database. It keeps fixture credentials private and removes only its own temporary clusters and keys. A real backup system must retain the decryption identity separately from the machine and test operator recovery. Losing the only key makes an encrypted backup unusable.

What the drill does and does not prove

The local second cluster is a genuinely separate data directory and database process, but it is still on the same Mac. It does not prove recovery after losing that Mac, cloud credentials, a region, a key-management account or offsite storage. It does not reboot the host. Its logical snapshot includes pre-dump committed fixture rows; it does not implement continuous WAL archiving or point-in-time recovery.

For an actual fresh-host drill: provision an isolated replacement, retrieve the approved backup and keys from independent storage, verify ciphertext integrity, restore roles/schema/data, install the recorded application artifact, validate counts and representative behavior, compare the last recovered timestamp to the agreed RPO, and measure from incident declaration to verified service restoration for RTO. Keep external side effects disabled until reconciled. Route traffic only after explicit recovery acceptance.

Recovery decisions under pressure

If the app is broken but data is sound, roll back compatible application code. If data is corrupted, stop further damage, preserve evidence and restore to a separate target. If only one tenant record is wrong, prefer a reviewed surgical repair over whole-database restoration. If a provider may have completed an external action before timeout, reconcile by downstream request ID before replaying.

A backup job exiting0 is only one signal. Verify expected size, encryption, remote retention, restore freshness, identity access and application usability. Alert when the latest usable restore evidence exceeds your policy. Document who can declare recovery complete and who communicates any confirmed data loss.

ACTIVE-RECALL MASTERY CHECKPOINT · CH 16

Lock in what you just learned (3 quick questions)

PASS 2/3 FOR +30 XP
Q1.What is the critical difference between "we have nightly backups" and "we passed a fresh-cluster restore drill"?
Q2.Why inspect BOTH firing AND resolution (recovery) transitions in an alert drill?
Q3.What does a local recovery drill NOT prove by itself?
Answered 0 / 3