Production DeploymentVol. 16 · Part XVI
0 / 0

Shelves / Production Deployment

DP·193

Disaster Recovery

Surviving the failures that redundancy doesn't cover: the recovery chain (failure → detect → mitigate → failover/restore → validate → recover → postmortem); RPO and RTO from first principles and how they follow from business impact; the disaster catalogue (data deletion and corruption, ransomware, zone, region, provider, dependency and people failures); backup design (3-2-1-1-0, frequency versus RPO, immutability, separate accounts, encryption-key escrow); point-in-time recovery demonstrated on PostgreSQL 16 by undoing an accidental DELETE; restore testing as a scheduled job; DR strategies (backup-and-restore, pilot light, warm standby, active-active) with cost and RPO/RTO; regional failover mechanics (replication, DNS, data consistency, failback); dependency failure and graceful degradation; DR runbooks, drills and game days; and postmortems.

24 topics · ~21 min read · 31-question quiz
Updated Suggest a correction

Start here: when something goes badly wrong

Disaster recovery (DR) is how you get a service and its data back after a failure that ordinary redundancy doesn't cover: a deleted table, a corrupted database, a region outage, ransomware, a bad migration, a lost encryption key. Redundancy (replicas, multiple servers) protects against machines failing; it happily copies a mistaken DELETE to every replica in milliseconds. Recovery needs backups you can restore, and practice restoring them.

Two numbers define every DR plan

  • RPO (recovery point objective): how much data you can afford to lose, measured in time. "RPO 5 minutes" means at most the last 5 minutes of changes.
  • RTO (recovery time objective): how long you can afford to be down while recovering.

They're business decisions with costs: a smaller RPO or RTO needs more infrastructure and practice.

What the lab did

A PostgreSQL database of 1,000,000 orders. A nightly-style logical backup (pg_dump) and a physical base backup were taken; then 25,000 more orders arrived, and then someone ran DELETE FROM orders by mistake:

Recovery method Time to restore Orders recovered Lost
restore the earlier pg_dump 0.9 s 1,000,000 all 25,000 orders since the backup
point-in-time recovery: base backup + replaying the archived WAL to just before the DELETE 1.0 s 1,025,000 none of the orders before the accident

Point-in-time recovery (PITR) works because PostgreSQL writes every change to a write-ahead log (WAL); archiving those WAL files continuously lets you replay history up to any moment. The dump's RPO was "since the last dump"; PITR's was "seconds". (At this size both restores took about a second; real databases of hundreds of gigabytes take hours, which is why RTO must be measured, not assumed.)

How deep to go in disaster recovery

Volume 17 defines six mastery levels; for disaster recovery they look like this:

Level You can…
L1 explain RPO, RTO, backups vs redundancy and DR strategies
L2 configure backups and restore a database to a point in time
L3 explain WAL archiving, snapshots, cross-region replication and failover mechanics
L4 run a restore or failover under pressure and diagnose what slows it
L5 design DR for a system to meet stated RPO/RTO at acceptable cost, with drills
L6 run an organisation's DR programme: audits, game days, ransomware resilience

Redundancy is not recovery

Chapters 188–192 made TiffinBox redundant: replicas across zones, a synchronous standby, rolling deploys. Redundancy handles expected, local failures automatically. It doesn't handle:

  • Logical failures that replicate: a bad migration, a buggy backfill, an operator's DELETE without WHERE, an application bug that corrupts credits. The standby faithfully applies the damage within milliseconds.
  • Correlated failures: a whole region down, a provider-wide control-plane outage, a bad config pushed everywhere.
  • Malicious failures: ransomware, a compromised admin account deleting resources and backups.
  • Loss of a dependency you don't control: payment provider, SMS gateway, model API, identity provider.
  • Loss of people or knowledge: the one engineer who knew how the restore works is on leave.

Disaster recovery (DR) is the plan, tooling and practice for getting back to a working, correct state after those. Its defining property is that it's rarely exercised by real events, so it rots unless exercised deliberately.

The recovery chain

The roadmap's sequence, each step with its question:

failure detect mitigate failover /restore validate recover post-mortem prevention and better recovery RTO: failure → validated service RPO: data written in this window before the failure may be lost
The disaster recovery chain. A failure must be detected, its impact mitigated, service restored by failover or restore, the result validated, normal operation recovered (including failback and backlog processing), and lessons captured in a postmortem that feeds back into prevention. Time from failure to validated restoration is measured against RTO; data lost is measured against RPO.
  1. Failure: something breaks. You can't control when; you can control how prepared you are.
  2. Detect: how quickly do you know? Alerts on symptoms (SLO burn, synthetic checks), not just causes. Data corruption is the hardest to detect: credits silently wrong can go unnoticed for days, which is why invariant checks (chapter 191's validation queries, run continuously) matter.
  3. Mitigate: stop the bleeding before fixing: stop the job that's corrupting data, put the app in read-only or maintenance mode, revoke the compromised credential, shed load, disable the feature flag. Mitigation limits how much needs recovering.
  4. Failover or restore: switch to the standby/other region (fast, if prepared) or restore from backups (slower, always possible if backups exist).
  5. Validate: is the restored system correct? Data checks (counts, invariants, sampled comparisons), synthetic journeys, reconciliation with external systems (payment provider's records).
  6. Recover: return to normal: replay or reconcile work done during the outage (orders taken offline, queued messages), fail back to the primary region (a planned, second failover), restore redundancy (a new standby; until then you're running without a safety net).
  7. Postmortem: blameless analysis, timeline, contributing factors, action items with owners; feed prevention.

RPO and RTO

Two numbers define what "recovered" must mean:

  • Recovery Point Objective (RPO): the maximum acceptable data loss, measured as time. RPO 5 minutes means losing at most the last 5 minutes of writes. Determined by how often data is copied somewhere safe (backup frequency, replication lag).
  • Recovery Time Objective (RTO): the maximum acceptable time to restore service. Determined by detection time + decision time + failover or restore time + validation.

They come from business impact, not from technology: what does an hour of downtime, or an hour of lost data, cost? Different data and services get different objectives:

TiffinBox data / service Impact of loss/outage RPO RTO
Credit ledger, payments, subscriptions Money; disputes; trust ≈ 0 (no committed write lost) 1 h
Delivery schedule and skips Wrong lunches cooked/delivered ≤ 1 min 30 min, before 07:00 cut-off
Menu, images Annoying; can be re-uploaded 24 h 4 h
Analytics warehouse Reports delayed 24 h 3 days
Search index Rebuild from Postgres n/a (derived) 2 h
AI assistant Help links fallback n/a 1 day

Note the time-of-day dimension: an outage at 06:40 is far worse than at 15:00, because skips must land before cut-off. Recovery plans can include business mitigations: "if skip is down after 06:30, extend today's cut-off" (chapter 189's flag), which is often cheaper than engineering a lower RTO.

Measured actuals matter more than objectives. The RTO you demonstrated in the last drill is your real RTO.

Python
# Does the plan meet the objectives? Estimate RTO and RPO from component times (minutes), then compare.
plans = {
    "restore from nightly snapshot":     {"detect": 10, "decide": 15, "provision": 20, "restore": 90, "replay": 0,  "validate": 20, "rpo": 24 * 60},
    "PITR from snapshot + WAL archive":  {"detect": 10, "decide": 15, "provision": 20, "restore": 90, "replay": 25, "validate": 20, "rpo": 5},
    "promote cross-region replica":      {"detect": 5,  "decide": 10, "provision": 0,  "restore": 3,  "replay": 0,  "validate": 10, "rpo": 1},
}
objectives = {"rto": 60, "rpo": 1}   # ledger: RTO 1 h, RPO ~0 (≤ 1 min for async replication)
for name, p in plans.items():
    rto = sum(v for k, v in p.items() if k != "rpo")
    ok = "meets" if rto <= objectives["rto"] and p["rpo"] <= objectives["rpo"] else "MISSES"
    print(f"{name:<36} RTO≈{rto:>4} min  RPO≈{p['rpo']:>5} min  → {ok}")
Text
restore from nightly snapshot        RTO≈ 155 min  RPO≈ 1440 min  → MISSES
PITR from snapshot + WAL archive     RTO≈ 180 min  RPO≈    5 min  → MISSES
promote cross-region replica         RTO≈  28 min  RPO≈    1 min  → meets

Notice that detection and decision time are often bigger than the technical step. Deciding to fail over a region is a serious call; pre-agreed criteria ("if the primary region's API is down for 15 minutes and the provider's status page confirms a regional event, the incident commander fails over") remove the hesitation.

The disaster catalogue

Scenario Example Primary defence Recovery
Accidental data deletion / corruption DELETE without WHERE; buggy backfill Least privilege, review, invariant checks PITR to before the event, then copy back affected rows
Ransomware / malicious deletion Compromised admin deletes DB and backups Separate backup account, immutable backups (S3 Object Lock, AWS Backup Vault Lock), MFA, break-glass Restore from immutable copies into a clean account
Zone failure AZ power event Multi-AZ (chapter 188) Automatic
Region failure Provider regional outage Cross-region replica / backups Regional failover
Provider-wide failure IAM/control-plane global outage Static stability (data plane keeps working without control plane), multi-provider for the most critical bits Ride it out degraded; failover if possible
Bad deploy / config Global config pushed with a bug Progressive rollout, validation Rollback (chapter 192)
Dependency failure Payment provider down Timeouts, fallbacks, queues Degrade, retry later, reconcile
Secret/cert loss Expired cert, lost KMS key Automation, key escrow, deletion protection Re-issue; restore keys
DNS/registrar compromise Domain hijacked Registry lock, MFA, monitoring Registrar recovery process
People/knowledge loss Only one person can restore Runbooks, drills, rotation Documented, practiced procedures

Static stability (an AWS term): design so that, when a dependency (especially a control plane) fails, the already-running system keeps working as it is, without needing to make changes. Examples: pre-provision capacity in each zone instead of relying on autoscaling during a zone failure; cache credentials and config with long validity; don't make the request path depend on service discovery calls.

Backups

Design rules

  • 3-2-1-1-0: at least 3 copies of data, on 2 different media/services, 1 off-site (another region), 1 offline or immutable, and 0 errors in restore verification.
  • Frequency follows RPO: daily snapshots alone give RPO up to 24 h. Continuous WAL archiving (PostgreSQL), binlog (MySQL), or oplog (MongoDB) gives minutes or seconds.
  • Separate blast radius: backups in a different account with different credentials (AWS Backup cross-account copy into a tiffinbox-backup account), so a compromised production account can't delete them.
  • Immutability: write-once retention locks (S3 Object Lock in compliance mode, Azure immutable blob storage, GCS bucket lock) that even the root account can't shorten.
  • Encryption with recoverable keys: backups encrypted with KMS keys you'll still have after a disaster (keys in the backup account or multi-region keys; a deleted key makes every backup unreadable).
  • Retention: enough history to recover from slow-to-detect corruption (35 days of PITR plus monthly snapshots for a year is a common pattern), balanced against data-protection obligations to delete personal data.
  • Everything, not just the database: object storage (S3 versioning + replication), secrets (exported securely), infrastructure definitions (in Git), container images (registry replication), DNS zone files, configuration in SaaS tools, and the runbooks themselves (not only in the wiki that's down).

Point-in-time recovery, demonstrated

PostgreSQL PITR combines a base backup (a copy of the data directory) with the write-ahead log archived since. To restore to any moment, restore the base backup and replay WAL up to a target time, transaction id or named restore point. Managed services (RDS, Cloud SQL, Azure) do exactly this behind a "restore to time" button, always into a new instance.

The experiment, on PostgreSQL 16: a primary with WAL archiving, a base backup, more writes, then an accidental DELETE that removes half the credit ledger, followed by recovery into a new data directory to the moment before the accident:

Shell
# 1. primary with continuous WAL archiving (postgresql.conf)
#    wal_level = replica
#    archive_mode = on
#    archive_command = 'test ! -f /backups/archive/%f && cp %p /backups/archive/%f'
#    archive_timeout = 5        # demo only: force a WAL segment switch at least every 5 s
pg_basebackup -h /tmp -p 5434 -U app -D /backups/base -Ft -z -Xs      # 2. base backup (tar, gzip, with WAL)
psql -c "INSERT INTO credit_entry ... 20,000 rows"                     # 3. more writes after the backup
psql -Atc "select now()"                                               #    record the last good moment
psql -c "DELETE FROM credit_entry WHERE subscription_id < 500"         # 4. the accident
# 5. restore into a NEW data directory — never over the damaged primary
mkdir restore && tar -xzf /backups/base/base.tar.gz -C restore && tar -xzf /backups/base/pg_wal.tar.gz -C restore/pg_wal
cat >> restore/postgresql.conf <<'C'
restore_command = 'cp /backups/archive/%f %p'
recovery_target_time = '2026-10-25 08:04:31.819822+00'
recovery_target_action = 'promote'
C
touch restore/recovery.signal
pg_ctl -D restore -o "-p 5435" start
Text
base backup took 97s, size 4.3M
last good moment: 2026-10-25 08:04:31.819822+00 rows=120000
after accidental DELETE rows=60000
PITR restore + replay took 2s
restored rows=120000
LOG: starting point-in-time recovery to 2026-10-25 08:04:31.819822+00
LOG: recovery stopping before commit of transaction 744, time 2026-10-25 08:04:32.931704+00
LOG: archive recovery complete

All 120,000 rows are back, including the 20,000 written after the base backup (replayed from archived WAL); recovery stopped just before the DELETE's commit. (The 97 s base backup is mostly pg_basebackup waiting for a spread checkpoint by default; --checkpoint=fast starts immediately.) Then, rather than switching production to the restored instance (which would discard every legitimate write since the accident), copy the deleted rows back into production:

SQL
-- On production, with the restored instance reachable via postgres_fdw (or dump/restore just these rows)
INSERT INTO credit_entry (id, subscription_id, delta, created_at)
OVERRIDING SYSTEM VALUE
SELECT r.id, r.subscription_id, r.delta, r.created_at
FROM restored.credit_entry r
LEFT JOIN credit_entry p ON p.id = r.id
WHERE p.id IS NULL AND r.subscription_id < 500;     -- only the rows the accident removed

In production, use a backup tool rather than hand-written cp: pgBackRest or Barman (parallel, compressed, encrypted backups and archive to S3/GCS/Azure, retention policies, verification), WAL-G, or the managed service's built-in PITR. Cloud-native Postgres operators (CloudNativePG) integrate them.

Restore testing as a job

A backup is only as good as the last successful restore. Automate it: on a schedule, restore the latest backup into an isolated environment, run validation queries, record timings, alert on failure, and tear down.

Python
# restore_drill.py — scheduled restore verification (sketch of the orchestration; cloud calls stubbed)
import datetime as dt, json, time

def restore_latest(target):           # e.g. AWS: restore_db_instance_to_point_in_time(UseLatestRestorableTime=True)
    time.sleep(0.01); return {"instance": target, "restored_to": dt.datetime.now(dt.timezone.utc).isoformat()}

def validate(instance):               # run invariants and compare with production's published counts
    checks = {
        "ledger_rows_vs_prod_within_1pct": True,
        "no_negative_credit_balances": True,
        "latest_delivery_date_is_today_or_later": True,
        "schema_version_matches_prod": True,
    }
    return checks

started = time.time()
info = restore_latest("drill-" + dt.date.today().isoformat())
checks = validate(info["instance"])
report = {
    **info,
    "restore_minutes": round((time.time() - started) / 60, 2),
    "checks": checks,
    "passed": all(checks.values()),
}
print(json.dumps(report, indent=2))
# Emit restore_minutes and passed as metrics; alert if passed is false or restore_minutes exceeds the RTO budget.

TiffinBox runs this weekly (Sunday, quiet), monthly with a full DR runbook walk-through by whoever is on call that week, so the knowledge isn't concentrated in one person.

DR strategies

The standard spectrum (AWS's DR whitepaper uses these names; the trade-offs are universal):

Strategy What runs in the recovery region RPO RTO Cost
Backup and restore Nothing; backups copied there hours (snapshots) or minutes (PITR logs) hours to a day lowest
Pilot light Data replicated (DB replica, S3 replication); app infrastructure defined in code but off or minimal seconds–minutes tens of minutes to hours low
Warm standby A scaled-down but fully working copy, receiving replicated data seconds minutes medium
Multi-site active-active Full capacity in both, serving traffic ≈ 0 (with careful data design) ≈ 0 (seconds) highest; most complex
backup/restorepilot lightwarm standbyactive-active primary: full backups only primary: full DB replicaapp off (IaC) primary: full DB replicaapp at 20% region A: full region B: full lower RPO and RTO → higher cost and complexity
Disaster recovery strategies from cheapest to most resilient. Backup and restore keeps only copies of data in the recovery region; pilot light replicates the data and keeps infrastructure ready to switch on; warm standby runs a small working copy; active-active serves traffic from both regions at full capacity. Moving right lowers RPO and RTO and raises cost and complexity.

TiffinBox's choice: it serves one city, and a Mumbai-region outage is rare. Primary in ap-south-1 (Mumbai), recovery in ap-south-2 (Hyderabad) (keeps data in India). Pilot light for most components (cross-region read replica of RDS, S3 replication, ECR replication, Terraform able to create the EKS stack in under 30 minutes), plus immutable backups in the backup account. Measured in drills: RTO ≈ 45 minutes, RPO ≈ seconds (replica lag). Plus the business mitigation: cut-off extension and a "skip by SMS" fallback for the morning window. Active-active would cost roughly double and introduce multi-region write conflicts for a single-city product; it isn't justified (Volume 15's build-vs-buy reasoning applied to resilience).

Regional failover mechanics

Failing over a region is a sequence of decisions and steps, scripted and rehearsed:

  1. Declare: the incident commander invokes the DR plan against pre-agreed criteria.
  2. Fence the old primary if it might come back: stop writes there (revoke app access, set read-only), to avoid split brain (two primaries accepting divergent writes).
  3. Promote the database in the recovery region (promote the cross-region replica: aws rds promote-read-replica, or Aurora Global Database switchover/failover). Note the replication position: writes after it are lost (that's your actual RPO) and must be reconciled later if the old region returns.
  4. Bring up compute (pilot light: apply Terraform for EKS and node groups; Argo CD syncs the same manifests with recovery-region values).
  5. Repoint configuration: database endpoints, queue URLs, buckets (prefer region-agnostic names via DNS CNAMEs you control, so config doesn't change).
  6. Shift traffic: DNS failover (Route 53 health checks or a manual record change; mind the TTL) or global load balancer / CDN origin failover.
  7. Validate: synthetic journeys, data checks, payment reconciliation.
  8. Communicate: status page, support macros, partner kitchens.
  9. Failback later, as a planned operation: rebuild replication in the reverse direction, wait for catch-up, switch in a quiet window. Reconcile any writes stranded in the old region.

Asynchronous cross-region replication means RPO > 0. Synchronous cross-region replication gives RPO = 0 at the cost of adding the inter-region round trip (Mumbai–Hyderabad ≈ 10–20 ms) to every commit, and of availability (if the other region is unreachable, commits stall). Most systems choose async plus reconciliation for the rare regional event; ledgers sometimes justify sync, or a design where money movements are confirmed by the external payment provider (which then becomes the reconciliation source).

Dependency failure

Most "disasters" users experience are a dependency failing. For each external dependency, decide in advance:

Dependency If it's down Design
Payment provider Renewals fail Queue renewals with retries; grace period keeps plans active; reconcile with the provider's records
SMS/WhatsApp gateway OTP and notifications fail Secondary provider; email OTP fallback; in-app notifications
Identity provider (if external) Nobody can log in Long-lived refresh tokens; existing sessions keep working (static stability)
Maps/geocoding Rider routing degraded Cache office coordinates; manual batching fallback
Model provider Assistant fails Secondary model/provider; help-centre links
CDN Assets slow/unavailable Multi-CDN for large products; origin can serve directly (rate-limited)
Cloud region Everything Regional DR above

Every dependency call has a timeout, a circuit breaker, and a defined fallback (chapter 189). Test them with fault injection: block the dependency in staging (network policy, a toxiproxy, a chaos tool such as AWS Fault Injection Service, Chaos Mesh, or LitmusChaos) and watch what users see.

DR runbook, drills and game days

A DR runbook is a checklist for a stressful moment: short sentences, exact commands, decision points with criteria, owners, and verification steps. It lives somewhere available during the disaster (a copy outside the primary region and outside the wiki that might be down: a printed copy is not absurd).

Markdown
# DR runbook: regional failover (ap-south-1 → ap-south-2)
Invoke when: API unavailable from ap-south-1 > 15 min AND AWS Health confirms a regional event, OR data plane
unrecoverable. Decision: incident commander (IC). Expected RTO 45 min; RPO = replica lag at failover.
0. IC opens #inc-dr, assigns Ops (executes), Comms (status page, kitchens), Scribe (timeline).
1. Fence: set ap-south-1 app deployments to 0 replicas if reachable; revoke app DB user writes (`ALTER ROLE app NOLOGIN`).
2. Note replica position: `SELECT pg_last_wal_replay_lsn(), pg_last_xact_replay_timestamp();` → scribe records it.
3. Promote: `aws rds promote-read-replica --db-instance-identifier tiffinbox-dr --region ap-south-2`  (≈ 5–10 min)
4. Compute: `cd infra/terraform/envs/dr && terraform apply -var enabled=true` (EKS + nodes, ≈ 20 min)
5. Argo CD: sync app-of-apps `tiffinbox-dr` (same manifests, dr values).
6. Traffic: Route 53 — set api.tiffinbox.in failover record to DR (TTL 60 s); CloudFront origin group switches automatically.
7. Validate: synthetic suite `make synth ENV=dr`; ledger invariants; payment reconciliation for the last 2 h.
8. Comms: status page "Operating from backup region; some changes made after HH:MM may need re-entry".
9. Recovery tasks: create new standby in ap-south-1 when available; plan failback (separate change, quiet window).

Drills, by increasing realism:

  1. Tabletop: walk through the runbook verbally with the team on a scenario; find gaps in knowledge and documentation.
  2. Component drills: restore a backup (weekly, automated), promote a replica in staging, fail over the RDS standby.
  3. Game day: a planned, time-boxed exercise injecting a realistic failure into staging (or carefully into production) with the on-call team responding as if real, observers taking notes, and a debrief. Netflix's Chaos Monkey and Chaos Kong popularised doing this in production for systems designed to tolerate it.
  4. Full DR exercise: fail over to the recovery region for real (in production, during a quiet window), run there for a while, fail back. Few organisations do this regularly; those that do discover the problems the others find during real disasters.

Measure each drill: detection time, decision time, each step's duration, deviations from the runbook. Fix the runbook immediately after.

Postmortems

After any significant incident or drill, a blameless postmortem: the goal is learning, and people only share what really happened when they won't be punished for it. Structure:

  • Summary and impact (users affected, duration, data lost, money).
  • Timeline (from logs and the incident channel, in UTC/IST, including detection and decision points).
  • Contributing factors (systems, processes, assumptions; "human error" is a starting point for asking why the system allowed it, not a conclusion).
  • What went well (worth keeping) and where we got lucky.
  • Action items: specific, owned, dated, prioritised; tracked to completion. Prefer fixes that make the failure impossible or automatic to handle over "be more careful".

Track postmortem action-item completion as a metric. Recurring incidents with open action items are the most avoidable outages there are.

Lab: an accidental DELETE and two ways back

Setup. A separate PostgreSQL 16 cluster on the lab machine with wal_level=replica, archive_mode=on and an archive_command copying each completed WAL segment to an archive directory (standing in for object storage), archive_timeout=10. An orders table with 1,000,000 rows (database 79 MB). Everything below is real: real backups, a real DELETE, real restores; only the scale is small.

The timeline

Step What happened
backup 1 pg_dump -Fc: 0.85 s, 7.3 MB (compressed logical dump)
backup 2 pg_basebackup: 1.38 s, 94 MB (physical copy of the data directory)
business continues 20,000 and then 5,000 new orders: 1,025,000 rows
last good moment 09:31:56.096
accident 09:31:58.554: DELETE FROM orders: 0 rows left
after the accident 1 new order arrives; the WAL switch archives the segment (19 segments in the archive)

Recovery 1: restore the dump

pg_restore into a fresh database: 0.91 s, 1,000,000 rows. Every order placed after the dump (25,000) is gone; with a nightly dump, the RPO is "up to 24 hours".

Recovery 2: point-in-time recovery

Copy the base backup, set restore_command to fetch from the archive, recovery_target_time to the last good moment and recovery_target_action = 'promote', create recovery.signal, start:

Text
consistent recovery state reached at 0/B000100
recovery stopping before commit of transaction 734, time 2026-11-05 09:31:58.530101+00
redo done at 0/12C61EA0 … elapsed: 0.52 s

Start plus replay: 1.04 s, 1,025,000 rows: every order up to the moment before the DELETE. PostgreSQL found the deleting transaction's commit in the WAL and stopped just before it. The one order placed after the accident isn't in the restored copy; recovering it means extracting it from the damaged database (or the WAL) and merging, which is why real recoveries usually restore to a separate instance and copy back what's needed, rather than overwriting production.

What scales, and what to measure for real

Quantity Grows with Lab
dump time and restore time database size; restore also rebuilds indexes ~1 s for 79 MB
base backup time database size, disk and network throughput 1.4 s
PITR replay time WAL volume since the base backup 0.5 s for ~18 segments
RPO with WAL archiving archive_timeout and archive lag (or 0 with streaming to a backup server) seconds

At 500 GB, a logical restore can take many hours, and replaying a week of WAL can take longer than the outage you can afford. That's why production setups take frequent base backups (daily) with continuous archiving, use tools such as pgBackRest, Barman or WAL-G (parallel, compressed, verified, with retention), and time a full restore regularly: the measured restore time is the RTO.

Try it yourself

  1. Repeat with 10 million rows and measure dump, restore, base backup and replay times; plot against size.
  2. Set recovery_target_xid instead of a time and recover to exactly before transaction 734.
  3. Run pg_verifybackup on the base backup, then corrupt one file and see it fail.
  4. Script the whole restore drill so it runs weekly in CI and reports the measured RTO.

Revision sheet: disaster recovery

Key ideas

  • Redundancy ≠ recovery: replicas and multi-AZ protect against hardware failure, not deletion, corruption, ransomware or bad deploys.
  • RPO/RTO per system, agreed with the business; tiers by criticality.
  • Disaster catalogue: data loss, corruption, zone/region outage, provider outage, credential compromise, ransomware, key loss, human error.
  • Backups: logical (dumps), physical (base backups, snapshots) + continuous WAL/binlog archiving for PITR; encrypt, verify, retain, and keep them isolated (separate account, immutable storage, different credentials); follow 3-2-1.
  • DR strategies: backup and restore → pilot light → warm standby → active-active (cost rises, RTO/RPO fall).
  • Failover mechanics: DNS/traffic manager, promoting replicas, fencing the old primary, data reconciliation, failback.
  • Dependencies: third parties fail too; degrade gracefully, queue, fail over providers.
  • Runbooks, drills, game days, then blameless postmortems with action items.

Numbers to remember

  • Lab: dump restore lost 25,000 orders (everything since the dump); PITR lost none before the accident.
  • Lab: 1 M rows: dump 0.85 s, base backup 1.4 s, restore 0.9 s, PITR 1.0 s; production scale is hours.
  • RPO with WAL archiving ≈ archive interval (seconds to minutes).

Pitfalls

  • Never testing restores.
  • Backups readable and deletable with production credentials.
  • Restoring over production instead of beside it.
  • RTO assumed rather than measured.
  • Failover without fencing (two primaries, split brain).

Glossary

  • RPO / RTO: recovery point / time objective.
  • PITR: point-in-time recovery from base backup plus log replay.
  • WAL archiving: shipping completed write-ahead log segments to durable storage.
  • Fencing: guaranteeing the old primary can't accept writes after failover.
  • 3-2-1 rule: three copies, two media types, one off-site (often plus one immutable).