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.

Backups and Restores

Module 9 Lesson 9.a 50 min Difficulty 3/5

Prerequisites 1.d

The idea in one minute#

Nobody needs backups. Everybody needs restores. A backup that has never been restored is a hope, not a backup — and many organisations discover during a disaster that theirs were empty, corrupt, incomplete, encrypted by ransomware, or far too slow to restore.

Two numbers frame every decision: the RPO (recovery point objective — how much data you can afford to lose, measured in time) and the RTO (recovery time objective — how long you can afford to be down while recovering). A sound backup strategy follows 3-2-1-1-0: three copies, on two kinds of media, one off-site, one immutable or offline, and zero errors in regularly tested restores.

An analogy#

A fire extinguisher hanging on the wall for ten years is reassuring. Whether it works is another matter — which is why buildings must have them inspected and discharged on a schedule.

A picture#

flowchart LR
  DB[(":postgresql: <b>Primary</b>")] -->|"continuous WAL"| PITR[":s3: <b>Object storage</b><br/><small>WAL archive: PITR, RPO ~ seconds</small>"]
  DB -->|"nightly full / incremental"| SNAP[":i-archive: <b>Snapshots</b><br/><small>same region</small>"]
  SNAP -->|"copy"| OFF[":i-globe: <b>Other region / account</b><br/><small>off-site</small>"]
  OFF --> IMM[":i-lock: <b>Immutable copy</b><br/><small>object lock, separate credentials</small>"]
  IMM --> TEST[":i-check: <b>Automated restore test</b><br/><small>daily: restore, verify, time it</small>"]
  class DB memory
  class PITR,SNAP,OFF io
  class IMM queue
  class TEST compute

How it really works#

RPO and RTO#

RPO = the age of the newest data you are guaranteed to be able to restore
RTO = the time from "disaster declared" to "service working again"
DataTypical RPOTypical RTO
Payments ledger0 (synchronous replication)Minutes
Customer orders≤ 5 minutes≤ 1 hour
Product catalogue (reproducible from source)24 hoursHours
Analytics warehouse24 hours1–2 days
LogsBest effortBest effort

Set them per dataset with the business owner. RPO 0 and RTO 0 are possible only with synchronous multi-site replication — and even that does not protect you from a logical disaster (a bad migration, an UPDATE without a WHERE), because replication copies the mistake instantly.

What you are protecting against#

ThreatProtection
Disk / host failureReplication (not a backup)
Zone or region lossOff-site copies, cross-region replication
Logical corruption (bug, bad migration, operator error)Point-in-time recovery to before the mistake; delayed replicas
Ransomware or a malicious insiderImmutable copies (object lock / WORM), separate accounts and credentials, offline copies
Provider or account lossA copy outside the provider or account
Silent corruption (bit rot)Checksums, scrubbing, verified restores

Replication is not a backup. It protects against losing a copy, not against writing the wrong data into all copies.

Backup types#

  • Full: a complete copy. Simple to restore, expensive to take.
  • Incremental / differential: only changes since the last backup. Cheap to take; a restore needs the chain.
  • Snapshots: storage-level copies (EBS, persistent disks). Fast; make them application- consistent (freeze or flush first) or crash-consistent at least.
  • Continuous archiving / PITR: stream the database’s write-ahead log (PostgreSQL WAL, MySQL binlog) to object storage. Restore a base backup and replay to any second. Tools: pgBackRest, WAL-G, Barman; managed databases do this built in.
  • Logical dumps (pg_dump): portable and good for single tables, slow for big databases.

Restore testing is the backup#

Automate a restore test, daily or weekly:

  1. Pick the latest backup (and periodically a random older one).
  2. Restore it into an isolated environment.
  3. Verify it: row counts against the source, checksums of key tables, the newest timestamp (that is your real RPO), application-level checks (can the app start against it?).
  4. Time it — that is your real RTO for restore-based recovery.
  5. Alert if any step fails, or if the restore time or data age exceeds the objective.

And at least yearly, run a full restore drill with people following the runbook (10.c).

The GitLab lesson (2017)#

On 31 January 2017, an engineer working on a replication problem ran a deletion command against the primary database instead of the secondary, removing about 300 GB of data. GitLab then found that of its five backup and replication mechanisms, none worked as expected: regular backups had been silently failing (the failure emails were being rejected), and replication had broken. It recovered from a staging snapshot taken six hours earlier, losing about six hours of data. GitLab live-streamed the recovery and published a famously candid postmortem, whose main action item was simple: test restores automatically.

A worked example#

An orders database: 800 GB, RPO 5 minutes, RTO 1 hour.

  • Plan: continuous WAL archiving to object storage (RPO ≈ seconds); daily base backup; copies replicated to a second region in a separate account with object lock (30 days).
  • First restore test: restoring 800 GB from the other region takes 3 h 10 min — the RTO is not met. Network throughput from object storage is the bottleneck.
  • Fix: keep a warm standby replica in the second region for region loss (9.b); use PITR from local snapshots for logical errors, which restores in 38 minutes. Both paths are now tested weekly.

The program models backup schedules to compute worst-case RPO, and verifies a “restore” with checksums — the core of an automated restore test.

Code#

Go
// backups.go — worst-case RPO for backup schedules, and a checksum-verified restore test.
package main

import (
	"crypto/sha256"
	"encoding/hex"
	"fmt"
	"time"
)

type schedule struct {
	name        string
	interval    time.Duration // how often a backup completes
	duration    time.Duration // how long a backup takes to complete
	restoreRate float64       // GB per minute when restoring
	shipDelay   time.Duration // time before the copy is off-site
}

func main() {
	const sizeGB = 800.0
	const rpo, rto = 5 * time.Minute, time.Hour
	schedules := []schedule{
		{"nightly full", 24 * time.Hour, 2 * time.Hour, 4.2, 30 * time.Minute},
		{"hourly incremental", time.Hour, 10 * time.Minute, 4.2, 15 * time.Minute},
		{"continuous WAL (PITR)", 30 * time.Second, 5 * time.Second, 21, time.Minute},
	}
	fmt.Printf("dataset %.0f GB, objectives: RPO %v, RTO %v\n\n", sizeGB, rpo, rto)
	fmt.Printf("%-24s %16s %16s %8s\n", "schedule", "worst-case RPO", "restore time", "meets?")
	for _, s := range schedules {
		// Worst case: disaster just before the next backup completes, and the last one not yet shipped.
		worstRPO := s.interval + s.duration + s.shipDelay
		restore := time.Duration(sizeGB/s.restoreRate) * time.Minute
		ok := "no"
		if worstRPO <= rpo && restore <= rto {
			ok = "yes"
		}
		fmt.Printf("%-24s %16v %16v %8s\n", s.name, worstRPO, restore.Round(time.Minute), ok)
	}

	// A restore test: compare per-table checksums and row counts between source and restored copy.
	fmt.Println("\nrestore verification")
	source := map[string][]string{
		"orders":    {"o-1|42.00|paid", "o-2|13.50|paid", "o-3|99.99|refunded"},
		"customers": {"c-1|ana", "c-2|raj"},
	}
	restored := map[string][]string{
		"orders":    {"o-1|42.00|paid", "o-2|13.50|paid"}, // a missing row
		"customers": {"c-1|ana", "c-2|raj"},
	}
	sum := func(rows []string) string {
		h := sha256.New()
		for _, r := range rows {
			h.Write([]byte(r + "\n"))
		}
		return hex.EncodeToString(h.Sum(nil))[:12]
	}
	failed := false
	for _, table := range []string{"customers", "orders"} {
		s, r := source[table], restored[table]
		status := "ok"
		if len(s) != len(r) || sum(s) != sum(r) {
			status = "MISMATCH"
			failed = true
		}
		fmt.Printf("  %-10s rows %d/%d  checksum %s / %s  %s\n", table, len(r), len(s), sum(r), sum(s), status)
	}
	if failed {
		fmt.Println("  → restore test FAILED: page the data owner; the backup cannot be trusted")
	}
}

Remember this#

  • Restores matter, not backups; an untested backup is a hope.
  • Set RPO and RTO per dataset with its owner; measure the real ones in restore tests.
  • 3-2-1-1-0: three copies, two media, one off-site, one immutable/offline, zero restore errors.
  • Replication is not a backup; logical corruption needs point-in-time recovery.
  • Automate restore tests: restore, verify, time, alert. Run a human drill at least yearly.

Try it#

  1. Run backups.go. What restore rate would the nightly full need to meet the RTO? Is it realistic?
  2. For a database you know, write its RPO and RTO and the last date a restore was tested.
  3. Restore last night’s backup of a test database into a scratch instance and time it.

Check yourself#

  1. Why does synchronous replication not protect against a bad migration?
  2. What does an immutable backup protect against that an off-site one does not?
  3. What should an automated restore test verify besides “the restore command succeeded”?
  4. What was the key lesson of the GitLab 2017 incident?

Sources#

↑↓ navigate↵ openesc close

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