Skip to content

Capacity Planning, Failure Scenarios & Disaster Recovery ​

"No one really wants to make backups; what people really want are restores." — Site Reliability Engineering, chapter 26 "Data Integrity", sre.google

Summary: Capacity planning decides how much you must own before demand arrives; failure scenarios list what can take it away; disaster recovery (DR) decides how much data you may lose (RPO) and how long you may be down (RTO), buys exactly that much redundancy, and proves it by restoring. Focus: demand forecast, headroom, N+1 and N+2 per failure domain, load-tested per-replica capacity, the failure-mode table, active-active vs active-passive, warm standby, pilot light, RPO and RTO per data class, 3-2-1 backups with Object Lock, PITR, cross-region replication, DNS failover arithmetic, failback, DR drills and business continuity. Learning goal: Size a service for a forecast with N+1 across availability zones, write a failure-mode table with likelihood and impact, choose a DR strategy per data class from RPO and RTO and its cost, build a backup that has been restored at least once, and run a game day that proves the numbers.

This chapter closes the operations path. Scaling Strategies covers autoscaling mechanics and Back-of-the-Envelope Capacity Estimation the arithmetic of traffic, storage and bandwidth; here we turn those numbers into spare capacity and recovery plans. Database mechanics of base backups and WAL live in Backup, PITR & Disaster Recovery and Replication, Read Replicas & Failover. Chaos Engineering & Game Days tests failures; this chapter decides which ones to survive.

Page map ​

If you are looking forGo to
The whole page in a few tablesEverything in one minute
Why plan for loss and growthWhy it exists
Google SRE, AWS DR whitepaper, NISTWhere it comes from
Forecasting demand, growth, seasonalityDemand forecast
Headroom, N+1, N+2, utilisation targetHeadroom
Measuring per-replica capacityLoad test
Google's intent-based approach, costIntent-based planning
Quotas, IP exhaustion, certificate expiryLimits
The failure-mode tableFailure scenarios
Multi-AZ, multi-region, cellsRedundancy models
RPO, RTO, data classesRPO and RTO
3-2-1, Object Lock, PITR, restore testBackups
Backup and restore, pilot light, warm standby, active-activeDR strategies
Replication lag, promotion, DNS failover TTLFailover
Databases, Kafka, object storage, caches, searchStateful services
Failback and reconciliationFailback
Runbooks, drills, game days, BCPRunbooks and drills
MTTR, restore time, backup success rateMeasuring
CodeGo, Laravel
Classic mistakesSolving the classic problems
Which strategyChoosing
Monolith to multi-regionIn architecture
Run itLab
Wrong beliefs, summary, quiz, termsMisconceptions, Cheat sheet, Self-check, Glossary

Everything in one minute ​

QuestionShort answer
How many replicas?peak demand / (per-replica capacity x utilisation target), spread so losing one failure domain still leaves enough
What is N+1?Enough capacity to carry the load after losing one unit (here: one availability zone)
What is RPO?Recovery Point Objective: how much recent data you may lose, as a time window
What is RTO?Recovery Time Objective: how long you may be down
Is replication a backup?No: it copies a bad delete to every replica within seconds
When is a backup real?After you restored it into a scratch environment and checked it
Cheapest DR that works?The cheapest strategy whose RPO and RTO meet the target for that data class
DR strategyRuns in recovery regionTypical RPOTypical RTOCost vs production
Backup and restoreNothingHoursUp to 24 hoursA few percent
Pilot lightData stores replicated, app tier offMinutesTens of minutesLow
Warm standbyScaled-down full stackSecondsMinutesMedium
Multi-site active-activeFull stack serving trafficNear zeroNear zeroHighest
FailureTypical blast radiusFirst defence
Process or hostOne replicaRedundancy, health checks
Rack or AZA failure domainN+1 across AZs
Region or providerA whole deploymentDR region at the strategy your RTO needs
Bad deploy, human errorEverything, fastCanary, rollback, PITR
Data corruption, ransomwareAll copies that syncImmutable, versioned backups
Expired certificate, quota, IP exhaustionEverything using itMonitoring and expiry alerts
NumberMeaning
60%A common utilisation target: room for spikes and for lost capacity
33%Idle fleet share with 3 zones to survive 1 (N+1)
3-2-13 copies, 2 media or accounts, 1 offsite
Worst-case DNS failovercheck interval x threshold + TTL + client overrun

Why it exists ​

Systems fail in two ways that look alike to users: they run out of capacity (demand arrived faster than machines) or they lose capacity (a zone, a database, a certificate). Capacity planning handles the first, redundancy the second, and disaster recovery handles the case where redundancy itself was destroyed (a region, the data, the account). All three ask the same question: what does being wrong cost, and how much of that cost do you pay up front?

Cheaper and simplerMore resilient and costlier
Run at 90% utilisationRun at 40-60% so a zone loss is survivable
One regionTwo regions with a tested failover
Daily backupsContinuous WAL archiving, PITR to the second
Manual recovery from a wiki pageAutomated, drilled runbook

Everyday picture: a theatre. Capacity planning is how many seats you have for tomorrow's sell-out; redundancy is the second fire exit; DR is the rehearsed plan for the day the theatre burns down and the show moves to the gym next door.

Three common misunderstandings, up front ​

  1. "We are multi-AZ, so we have DR." Multi-AZ survives a data centre; it does not survive a bad delete, a bad deploy, ransomware, an expired certificate or a regional event.
  2. "We have backups." Untested backups are archives. The SRE book's point is that restores are the deliverable.
  3. "Autoscaling means no capacity planning." Autoscaling reacts within quota, lead time and cold-start limits; it cannot create machines the cloud lacks or quota you never requested.

Where it comes from {#history} Good to know ​

SourceWhat it gave us
Google SRE Book, chapter 18Traditional capacity planning as a cycle (forecast, plan, sign off, deploy) that is brittle; intent-based capacity planning and the Auxon case study
Google SRE Book, chapter 26Backups versus archives, "delivering a recovery system rather than a backup system", replication is not backup, diversity of layers
AWS "Disaster Recovery of Workloads on AWS"The four strategies, and control plane versus data plane
AWS Well-Architected Reliability pillarDR strategy (backup and restore, pilot light, warm standby, multi-site) by RPO and RTO
NIST SP 800-34 Rev. 1Contingency-planning vocabulary: information system contingency plan, disaster recovery plan

The AWS whitepaper advises: "you should use only data plane operations as part of your failover operation", because data planes have higher availability goals than control planes. We use this in the failure table.

The concept catalogue ​

Demand forecast Must-know ​

In plain words: A demand forecast is a number with a date: "peak 9,000 requests per second in November". It is built from what you measured, how fast it grows and what you know is coming.

Common misunderstanding: "Take last month's peak and add a buffer." Growth compounds, seasonality multiplies, and a launch is a step that history never shows.

Definition: forecast = current peak x (1 + organic growth)^months x inorganic steps x seasonality factor. Organic growth is the trend from existing users; inorganic growth is a discrete change you cause (a market launch, a migration, a campaign, an acquisition); seasonality is a repeating calendar effect (Black Friday, payroll day, Nowruz, exams).

month 0   peak 5,000 rps (p99 of per-minute peaks over 4 weeks)
month 3   x 1.06^3                        = 5,955
month 6   x 1.06^6 x 1.25 (new market)    = 8,866
month 10  x 1.06^10 x 1.25 x 1.8 (Nov)    = 20,147    -> order capacity for THIS number early

Real scenario: a ticketing site doubles for 20 minutes at on-sale moments; a bank peaks on the 25th; a food app peaks at 20:00 local time, not at the daily average. Plan for the peak and its shape: a 20-minute spike needs buffering and load shedding, not just machines (see Load Shedding).

InputWhere it comes from
Current peakMetrics (Prometheus, CloudWatch): per-minute peaks over several weeks
Organic growthQuarter-over-quarter trend of users or requests
Inorganic growthProduct and sales roadmap, interviewed, not guessed
SeasonalitySame calendar month last year divided by the trend
Efficiency changeRelease notes: a feature may cost 20% more CPU per request

Fix: keep the forecast in code, rerun it monthly and track forecast error. The Go package in Go does the arithmetic; business inputs still need a human.

Headroom, N+1 and N+2 across failure domains Must-know ​

In plain words: Headroom is capacity you deliberately leave unused. N+1 means the system still meets its load after losing one failure domain; N+2 after losing two.

Common misunderstanding: "N+1 means one spare server." Across three zones the spare is a whole zone's worth, a third of the fleet.

Definition: a failure domain is a set of components that fail together: process, host, rack, availability zone, region, provider. With D domains and S spare domains, replicas = ceil(needed / (D - S)) x D, where needed = ceil(demand / (per-replica rps x utilisation target)). The utilisation target is the fraction of measured per-replica capacity you plan to use normally. Lead time is the delay between deciding to add capacity and it serving traffic (procurement, quota approval, image build, warm-up).

Normal: 45 replicas, 3 zonesAZ a40% busyAZ b40% busyAZ c40% busyAZ a lostDegraded: 30 replicas carry all loadAZ agoneAZ b60% busyAZ c60% busyutilisation target 60%replicas = ceil( ceil(peak / (per-replica rps x target)) / surviving zones ) x zones9000 rps / (500 x 0.6) = 30 needed; 30 / 2 surviving = 15 per zone; 15 x 3 = 45The "spare" capacity is the 33% you pay for so a zone failure is a non-event.
needed     = ceil(9000 / (500 x 0.6))   = 30 replicas of useful work
N+1, 3 AZ  = ceil(30 / 2) x 3           = 45 replicas  (40% busy normally, 60% after losing an AZ)
N+1, 4 AZ  = ceil(30 / 3) x 4           = 40 replicas  (45% busy normally, 60% after)
N+2, 4 AZ  = ceil(30 / 2) x 4           = 60 replicas
DomainsExtra capacity to survive 1 lossShare of fleet idle
2100% (each carries all)50%
350%33%
433%25%
620%17%

More domains make N+1 cheaper until cross-domain traffic, latency and operations cost more than they save. Stateful systems follow quorum rules: a 3-node quorum database tolerates 1 loss, not 2 (see CAP and PACELC). Order by lead time: if quota takes 6 weeks, the decision date is 6 weeks (plus a buffer) before the forecast date; OrderBy in the Go code computes it.

Load testing for per-replica capacity Must-know ​

In plain words: You cannot size a fleet without knowing what one replica really does. Measure it.

Common misunderstanding: "CPU hits 100% at 1,000 rps, so capacity is 1,000." Latency collapses long before CPU saturates; capacity is the rate at which the latency SLO still holds.

Definition: per-replica capacity is the highest sustained request rate at which p99 latency and error rate stay inside the SLO, measured with realistic data and dependencies on the production instance type. A load test ramps traffic in steps and records the knee.

1  ramp 100 rps -> 800 rps in steps of 100, 5 min each (k6, Gatling or vegeta)
2  at 500 rps: p99 180 ms, errors 0.0%     -> inside SLO (p99 <= 300 ms)
3  at 600 rps: p99 420 ms, errors 0.3%     -> outside SLO
4  per-replica capacity = 500 rps; plan for 60% = 300 rps per replica

Real scenario: a connection pool or downstream database caps throughput regardless of CPU; PHP-FPM worker count or a JVM thread pool is the real limit; a cache-cold replica sustains half the rate of a warm one. Test cold and warm, with a realistic read/write mix, and repeat after every major release.

Intent-based capacity planning and the cost model Important ​

In plain words: Instead of "give me 400 cores in cluster X", you state why you need capacity ("survive the loss of a region at 99.9%") and software computes the allocation.

Common misunderstanding: "Capacity planning is a yearly spreadsheet." The SRE book calls the traditional cycle brittle: a slipped delivery or a changed assumption ripples through every later quarter.

Definition: intent-based capacity planning encodes service requirements, dependencies and constraints (the intent) and generates the allocation plan automatically; Auxon is Google's implementation described in the SRE book, and its output also lists requirements that could not be met.

ApproachInputOutputWeakness
TraditionalDemand forecast, hand bin-packingResource list per clusterBrittle, loses the reason behind each number
Intent-basedRequirements ("N+2 in two regions, p99 under 300 ms")Generated allocation planNeeds tooling and honest intent
Autoscaling onlyLive metricsReplica count nowBounded by quota, lead time, cold start

Cost model: monthly cost = replicas x unit price + storage + egress + DR environment. Put the DR line in explicitly, otherwise active-active surprises finance. See Go for a linear model.

Quotas, limits and expiry as failure sources Must-know ​

In plain words: Many outages are not hardware: the account hit a limit, an address range ran out, a certificate expired.

Common misunderstanding: "The cloud is elastic." It is elastic inside quotas, per-region capacity and API rate limits.

Definition: quota exhaustion is hitting a provider or system limit (vCPUs per region, API request rate, database connections, pod IPs, file descriptors); IP exhaustion is running out of addresses in a subnet or pod CIDR; certificate expiry is a TLS certificate passing its notAfter date (see Cryptography in Practice).

LimitSymptomGuard
Region vCPU quotaScale-out fails during the incidentRequest quota in the DR region early, test scale-up
API rate limitAutoscaler and deploy tools throttledBackoff, fewer calls
Subnet or pod IPsPods Pending, nodes cannot joinAlert at 70% of addresses, plan CIDRs for 10x
Certificate expiryHandshake failures for everyone at onceAlert at 30 and 7 days, automate renewal
Database connectionsConnection refused during scale-outPooling (see Connection Pooling)
Disk or inode fullWrites failAlert at 80%, auto-expand

Failure scenarios and the failure-mode table Must-know ​

In plain words: List what can break, how often and how bad, then decide which ones you pay to survive.

Common misunderstanding: "Plan for the most likely failure." Rank by likelihood times impact: a rare region loss may deserve a plan, a common host loss deserves automation.

Definition: a failure scenario is a specific loss with a trigger, a blast radius and a recovery path. The failure-mode table ranks scenarios by likelihood and impact and names the control for each.

ScenarioLikelihoodImpactControl
Process crash, host lossHigh (daily)LowRedundancy, supervisor, health checks
Rack or top-of-rack switchMediumLow-mediumSpread replicas across racks
Availability zone outageLow-medium (yearly)HighN+1 across AZs, multi-AZ database
Region outageLowVery highDR region at the strategy your RTO needs
Cloud provider outageVery lowVery highBackups held outside the provider, a minimal escape hatch
Cloud control plane outageLowHigh (cannot scale or launch)Pre-provisioned capacity, data-plane-only failover
DNS provider failureLowVery highSecondary DNS provider, low TTL on critical names
Certificate expiry, CA problemMediumVery highExpiry alerts, short-lived automated certificates
Dependency SaaS outage (payments, auth, email)MediumMedium-highTimeouts, circuit breaker, fallback (see Bulkheads & Graceful Degradation)
Bad deployHighHighCanary, automated rollback, feature flags
Data corruption (bug, bad migration)MediumVery highPITR, restore points before migrations, validation jobs
Ransomware, malicious deletionLow-mediumVery highImmutable, offsite, separate-credential backups
Human error (wrong command, wrong environment)HighHighGuardrails, least privilege, approvals, PITR
Quota or IP exhaustionMediumHighAlerts, pre-requested quota

The data plane serves live requests; the control plane creates and configures resources. Failover should not depend on creating anything new at the moment the control plane is the broken part, which is why pilot light and warm standby keep the data tier and some compute already provisioned.

Redundancy models Must-know ​

In plain words: Redundancy is more than one of everything that matters, placed so one event cannot take out both.

Common misunderstanding: "Active-active is always better than active-passive." It shortens RTO and multiplies consistency problems: two writers need conflict handling (see Replication Topologies).

Definition: active-active serves traffic from several sites at once; active-passive keeps a standby (cold standby: nothing running; pilot light: data tier on; warm standby: scaled-down copy running); multi-AZ spreads one deployment over zones in a region; multi-region spreads it over regions; cell-based architecture splits the system into independent full copies (cells) so one failure or bad deploy touches one cell.

ModelSurvivesDoes not surviveCostComplexity
Single AZProcess, hostAZ, regionLowestLowest
Multi-AZAZ lossRegion loss, bad dataLow-mediumLow
Multi-region active-passiveRegion lossBad data (replicated)MediumMedium
Multi-region active-activeRegion loss, near-zero RTOBad data, bugs deployed to bothHighHigh (conflicts)
Cell-basedOne cell's bad deploy or poison dataShared control planeMedium-highMedium (routing layer)

Cell-based design is the bulkhead idea at deployment scale; see Cascading Failures.

RPO and RTO per data class Must-know ​

In plain words: RPO is how much work you can afford to lose; RTO is how long you can afford to be down. Different data has different answers.

Common misunderstanding: "One RPO and RTO for the whole company." A payments ledger and an analytics cache have different value; one target either overpays or underprotects.

Definition: RPO bounds data loss in time (async replica lag, or time since the last backup or archived WAL segment). RTO bounds downtime from disaster to serving again (detect, decide, promote, redirect, warm up, verify). A data class is a group of data with the same targets.

last goodcopydisasterdetecteddeclaredserving againRPO window: writes lostRTO window: users see errorsdetectdecidepromote + DNS + warm-up + verifyAsync replication: RPO = replication lag at the moment of failure. Backups: RPO = time since last backup or WAL segment.Most of the RTO is detection and the human decision, not the technical failover.
12:00:00  last WAL segment archived / replica applied up to here
12:00:07  primary dies                         -> RPO exposure = 7 s of commits
12:00:37  health checker declares it down      (10 s x 3 failures)
12:03:00  on-call confirms and declares disaster
12:03:40  standby promoted
12:07:10  DNS answers switch (TTL 60 s + clients) -> RTO = 7 min 10 s
Data classExampleTypical RPOTypical RTOStrategy
Financial ledgerPaymentsSeconds, near zeroMinutesWarm standby or active-active
Transactional coreOrders, accountsMinutes15-60 minWarm standby or pilot light
Reference dataCatalogueTens of minutes1 hPilot light
Derived dataSearch index, cachesNone (rebuild)HoursRebuild from source
Analytics, logsWarehouse24 h48 hBackup and restore

Cost curve: each step down in RPO or RTO costs disproportionately more. Ask the business what an hour of downtime and a minute of lost data cost, then compare with the table printed by the Go planner. See SLAs, SLOs, SLIs & Error Budgets.

Backups Must-know ​

In plain words: A backup is a copy you can go back to after something deleted or damaged the original, kept where the damage cannot reach.

Common misunderstanding: "Replication is our backup." The SRE book: datastores that sync replicas guarantee that a corrupt row or errant delete is pushed to all copies.

Definition: a full backup copies everything; an incremental backup copies what changed since the previous backup; point-in-time recovery (PITR) combines a base backup with continuous log archive to restore to any moment; an immutable backup cannot be altered or deleted until a retention date (Amazon S3 Object Lock, a WORM model); the 3-2-1 rule is 3 copies, 2 different media or accounts, 1 offsite.

Copy 1: productionprimary databaselive dataCopy 2: local backupsnapshot + WAL archivedifferent media/accountCopy 3: offsiteother region + providerObject Lock, encryptedScratch restorerows + checksums + timerestore weekly3 copies2 media or accounts1 offsite (and immutable)Replication copies mistakes instantly; a backup keeps history. Ransomware and bad deletes need the immutable copy.Also back up configuration, secrets, IaC state and DNS zones, or the restored data has nothing to run on.
TechniqueProtects againstRestore speedRPO
Full backup (nightly)Total lossSlow (copy everything back)Up to 24 h
Incremental backupTotal loss, cheaper storageSlower (chain of increments)Hours
Base backup + WAL archive (PITR)Bad delete, bad migrationMedium (replay)Seconds to minutes
Storage snapshotHost or volume lossFastSnapshot interval
Logical dump (pg_dump)Single-table recovery, upgradesSlowDump interval
Cross-region replicaRegion lossFast (promote)Replica lag
Object Lock copyRansomware, malicious deleteAs copyCopy interval
1  Sunday 02:00        base backup (pg_basebackup); WAL segments archived continuously
2  Wednesday 14:07     DELETE without WHERE; noticed at 14:20
3  restore base backup to scratch; set recovery target just before 14:07
4  replay WAL to target, verify counts, copy lost rows back (or switch over)
sql
-- Is archiving healthy, and how far behind is the standby? (full file in the Go section)
SELECT failed_count, last_archived_time FROM pg_stat_archiver;
SELECT now() - pg_last_xact_replay_timestamp() AS replay_delay;

PostgreSQL archives WAL with archive_command (or an archive library) and replays it during recovery; mechanics are in Backup, PITR & Disaster Recovery. Also back up what is not in the database: configuration (config backup), secrets and KMS key policy, IaC (Terraform state and modules), DNS zone files, CI/CD definitions and container images. Restored data with no way to run it is not a recovery.

Amazon S3 Object Lock works only in buckets with versioning, offers retention periods and legal holds, and in compliance mode nobody can delete a protected version before its date; it does not stop new versions or delete markers on top. Use it for an immutable backup copy in an account with separate credentials.

The only proof is a restore test: restore on a schedule into a scratch database, check row counts, checksums and a business query, and record the restore time. The SRE book says to motivate the work with the visible payoff, the restore. The Go drill and the Laravel command below do exactly that.

DR strategies Must-know ​

In plain words: Four ways to be ready, from "we can rebuild from backups" to "two sites run all the time".

Common misunderstanding: "Warm standby is a smaller production, so scaling up is instant." Scale-up depends on quota, cold caches and the control plane being up.

Definition (AWS, Disaster Recovery of Workloads on AWS): backup and restore (restore data and redeploy infrastructure from IaC), pilot light (data replicated, core infrastructure provisioned, application servers switched off), warm standby (scaled-down full version always running), multi-site active/active (full workload serving traffic in several Regions). The Well-Architected pillar lists them in increasing cost and complexity and decreasing RPO and RTO.

Backup and restorebackups copied offsitenothing runningIaC rebuilds the stackRPO: hoursRTO: up to 24 hcost: ~5%Pilot lightdata replicated, DB onapp servers switched offscale out on failoverRPO: minutesRTO: tens of minutescost: ~15%Warm standbyscaled-down full copyalways runningscale up on failoverRPO: secondsRTO: minutescost: ~40%Multi-site active-activefull copy, serves trafficboth regions take writesconflicts must be solvedRPO: near zeroRTO: near zerocost: ~100%+RPO and RTO fall, cost and complexity rise. Cost percentages are planning defaults, not a price list.Strategy names and RPO/RTO bands: AWS Well-Architected Reliability pillar (REL13-BP02).
StrategyFailover stepsFails when
Backup and restoreRebuild from IaC, restore data, repointBackups untested, IaC stale, quota missing
Pilot lightScale out app tier, promote DB, switch DNSSwitched-off tier drifted, no quota
Warm standbyScale up, promote, switch DNSStandby never exercised, lag larger than RPO
Active-activeRemove the failed site from routingConflicting writes, survivor too small

Replication for DR, promotion and DNS failover Must-know ​

In plain words: The standby is a copy that is slightly behind; failover is deciding to trust it and pointing users at it.

Common misunderstanding: "DNS failover is instant." Resolvers and clients cache answers for the TTL, and some keep them longer.

Definition: cross-region replication (asynchronous) ships changes to another region; its lag is your RPO exposure. Promotion turns the standby into the primary (PostgreSQL pg_promote). DNS failover removes an unhealthy endpoint from answers when a health check fails (Amazon Route 53 health checks with failover records). Worst case = check interval x failure threshold + TTL + client overrun. See IP, DNS, GeoDNS, TTL, Load Balancing and Leader Election.

t=0     primary region fails
t=30    health check marks it unhealthy         (10 s interval x 3 failures)
t=30    DNS starts answering with the standby
t=90    resolvers honouring TTL 60 re-ask       (typical)
t=210   clients caching beyond TTL catch up     (assumed 120 s overrun)  -> worst case 3 min 30 s
StepWhoTypical timeGuard
DetectHealth checks, alerts30 sCheck from several vantage points
DecideOn-call, incident commander1-5 minPre-agreed criteria, one decision owner
Fence old primaryAutomationSecondsPrevent split brain: revoke writes before promoting
Promote standbyDBA or automationSeconds to minutesCheck replay lag first
Switch trafficDNS, load balancer, routing controlTTL-boundLow TTL on the names that matter
VerifySmoke testsMinutesSynthetic transactions

Stateful services in DR Important ​

In plain words: Each kind of state recovers differently; rebuildable state needs no backup.

Common misunderstanding: "Treat everything as a database." Caches and indices are derived; backing them up wastes money and slows recovery, while queues and object stores need replication designed for them.

Definition: a rebuildable cache is data that can be recomputed from the source of truth; re-index is rebuilding a search index from the database or an event log.

StateDR approachProduct detail
Relational databaseBase backup + WAL, cross-region replica, promotionPostgreSQL streaming replication, pgBackRest or WAL-G; Amazon Aurora Global Database
KafkaReplicate topics to a second clusterKafka MirrorMaker 2 replicates topics, configs, consumer group offsets and ACLs; replicated topics are renamed with the source cluster prefix by default
Object storageVersioning plus cross-region replicationAmazon S3 CRR; Replication Time Control replicates 99.99% of new objects within 15 minutes
Cache (Redis, Memcached)Rebuild, accept cold startProtect the database from the stampede (see Caching)
Search indexRe-index from sourceElasticsearch snapshots only to shorten rebuild time (see Search Systems)
Message queuesReplicate or accept loss of in-flight messagesSee Messaging fundamentals
Secrets, config, IaCVersioned in Git, secrets in a replicated managerKeys must exist in the DR region

MirrorMaker 2 replication is asynchronous, so consumers failing over must translate offsets from checkpoints and may reprocess messages; consumers must be idempotent (see Idempotent Consumers).

Failback and data reconciliation Important ​

In plain words: Getting back to the original region is a second migration, usually harder than the first failover.

Common misunderstanding: "When the old primary comes back, point everything at it." It holds an older timeline; some writes it accepted may never have replicated.

Definition: failback returns service to the original primary after recovery; reconciliation compares and merges divergent writes made on both sides.

1  region A fails at 12:00:07; standby B promoted at 12:03:40
2  A recovers at 14:00 with commits between 12:00:00 and 12:00:07 that never reached B
3  do NOT rejoin A as primary; rebuild A as a standby of B (or rewind, e.g. pg_rewind)
4  export the lost-window rows from A, reconcile against B (business rules, idempotency keys)
5  when A is caught up and verified, schedule a planned switchover back, off-peak

Runbooks, drills and game days Must-know ​

In plain words: A runbook is the step-by-step script; a DR drill proves it works and people can follow it.

Common misunderstanding: "We have a runbook in the wiki." Untested runbooks are fiction; the failover that matters runs at 03:00 with a person who has never done it.

Definition: a runbook lists trigger, owner, commands, verification and rollback; a DR drill executes it (tabletop, then partial, then real failover); a game day is a scheduled, multi-team exercise with injected failure (see Chaos Engineering & Game Days). Chaos tests whether the system tolerates a fault; DR testing tests whether the people and data can recover from loss. Business continuity (BCP) covers the non-technical side: who talks to customers, which manual procedures run while systems are down, the status page, regulators and legal. NIST SP 800-34 is the standard vocabulary for contingency plans.

Drill levelEffortWhat it proves
TabletopHoursPeople know the roles and decisions
Restore drill (scratch)Automated weeklyBackups are usable, restore time known
Partial failoverQuarterlyThe standby serves a slice of traffic
Full region evacuationYearlyRTO and RPO met end to end

Communication: a public status page updated on a schedule, an internal incident channel, a decision log, and a pre-written holding statement. See Alerting That Actually Works and Secure SDLC & Incident Response.

Measuring readiness Important ​

In plain words: If you do not measure recovery, you only hope.

Common misunderstanding: "Uptime proves we are recoverable." Uptime says nothing about the rare event you have never survived.

Definition: MTTR is mean time to recover; RTO achieved vs target compares the last drill with the objective; backup success rate is successful runs over scheduled runs; restore time is the duration of the last scratch restore.

MetricTarget exampleAlert when
Backup success rate100% over 30 daysAny failed or missing run
Backup ageUnder RPONewest backup older than RPO
WAL archive failed_count0Increasing
Replication lagUnder RPOAbove RPO for 5 min
Restore time (last drill)Under RTO / 2Over RTO / 2
RTO achievedUnder targetLast drill missed target
Forecast errorWithin 15%Actual peak above forecast
Capacity headroomAt least N+1Utilisation above target after losing a zone

Mechanics ​

Knobs, in one place ​

ProductKnobMeaning
PostgreSQLarchive_mode, archive_commandShip each WAL segment; the command must return 0 only when the file is safely stored
PostgreSQLpg_basebackupBase backup for PITR
PostgreSQLrecovery_target_time, recovery_target_name, recovery.signalStop recovery at a moment or named restore point
PostgreSQLpg_create_restore_point('name')Mark a point before a risky change
PostgreSQLpg_stat_archiverfailed_count, last_archived_time
PostgreSQLpg_promote()Promote a standby
Route 53Health check, failover routing, record TTLDetection and switch time
S3Object Lock COMPLIANCE or GOVERNANCE, retention date, legal holdImmutability
S3Replication Time Control15-minute replication objective for new objects
Kafka MirrorMaker 2Replication flows A->B, sync of offsets via checkpointsCross-cluster replication
spatie/laravel-backupbackup:run, backup:clean, backup:list, backup:monitorBackup, retention, listing, health

Error names and statuses you will see ​

Message or statusMeaningAction
archive command failed with exit code 1 (PostgreSQL log)WAL segment not archived; pg_wal growsFix target, never delete WAL by hand
requested timeline 2 is not a child of this server's historyStandby and primary divergedRebuild standby or use pg_rewind
database system was interrupted; last known up at ...Recovery started after crash or restoreWait, check logs for recovery target reached
S3 AccessDenied on delete of locked versionObject Lock retention activeWorking as designed; wait or use legal hold release (governance only)
503 Service Unavailable from the read-only regionWrites refused outside the primaryExpected after fencing; promote or switch
VcpuLimitExceeded (EC2 launch error)Quota exhaustionRaise quota before disaster
Backup failed (spatie notification)backup:run exit code 1Investigate; the monitor catches stale backups

Time arithmetic you should be able to do ​

RPO exposure (async)    = replication lag now                    (e.g. 7 s)
RPO exposure (backups)  = time since last backup or archived WAL (e.g. up to 5 min with 5-min segment switch)
DNS worst case          = interval x threshold + TTL + overrun   = 10 x 3 + 60 + 120 = 210 s
RTO                     = detect + decide + fence + promote + switch + verify
Restore time (disk)     = backup size / min(read bandwidth, write bandwidth) + WAL replay time
  e.g. 2 TB at 400 MB/s = 5,000 s = 83 min before any WAL replay

Go ​

Example ​

Three small packages and a command. capacity forecasts demand and sizes replicas per failure domain with N+1 or N+2; drplan picks the cheapest DR strategy that meets RPO and RTO per data class and does the DNS failover arithmetic; restoredrill restores into a scratch database and verifies rows, checksums, backup age and restore time against the targets.

go
// Package capacity is a small, honest capacity model: forecast peak demand,
// turn it into replicas per failure domain with headroom, and say when to order.
package capacity

import (
	"errors"
	"math"
	"time"
)

// Growth describes how demand changes over time.
type Growth struct {
	MonthlyOrganic float64 // 0.08 means +8% per month, compounding
	Seasonality    []Season
	Inorganic      []Step // launches, migrations, marketing pushes
}

// Season multiplies demand in one calendar month (1 = January).
type Season struct {
	Month  time.Month
	Factor float64 // 1.6 means 60% above the organic trend
}

// Step is a one-off change in demand that starts in StartMonth (0 = now).
type Step struct {
	Name       string
	StartMonth int
	Multiplier float64 // 1.3 means +30% from StartMonth onward
}

// Forecast returns the peak requests per second expected `months` from `start`.
func Forecast(currentPeakRPS float64, g Growth, start time.Time, months int) (float64, error) {
	if currentPeakRPS <= 0 || months < 0 {
		return 0, errors.New("capacity: current peak must be positive and months non-negative")
	}
	rps := currentPeakRPS * math.Pow(1+g.MonthlyOrganic, float64(months))
	for _, s := range g.Inorganic {
		if months >= s.StartMonth {
			rps *= s.Multiplier
		}
	}
	target := start.AddDate(0, months, 0).Month()
	for _, s := range g.Seasonality {
		if s.Month == target {
			rps *= s.Factor
		}
	}
	return rps, nil
}

// Service holds what a load test told you about one replica.
type Service struct {
	PerReplicaRPS     float64 // measured at the latency SLO, not at the crash point
	UtilisationTarget float64 // 0.6 means plan to run at 60% of PerReplicaRPS
}

// Plan is the result of sizing one service across failure domains.
type Plan struct {
	DemandRPS         float64
	ReplicasNeeded    int // to carry demand at the utilisation target
	Domains           int
	SpareDomains      int // 1 = N+1, 2 = N+2
	ReplicasPerDomain int
	TotalReplicas     int
	UtilisationNormal float64 // fraction of PerReplicaRPS in normal operation
	UtilisationDegr   float64 // after losing SpareDomains domains
}

// Size computes replicas so that demand is still served at the utilisation
// target after SpareDomains whole failure domains disappear.
func Size(demandRPS float64, s Service, domains, spareDomains int) (Plan, error) {
	switch {
	case demandRPS <= 0, s.PerReplicaRPS <= 0:
		return Plan{}, errors.New("capacity: demand and per-replica capacity must be positive")
	case s.UtilisationTarget <= 0 || s.UtilisationTarget > 1:
		return Plan{}, errors.New("capacity: utilisation target must be in (0, 1]")
	case domains < 2 || spareDomains < 0 || spareDomains >= domains:
		return Plan{}, errors.New("capacity: need at least 2 domains and fewer spare domains than domains")
	}
	needed := int(math.Ceil(demandRPS / (s.PerReplicaRPS * s.UtilisationTarget)))
	surviving := domains - spareDomains
	perDomain := int(math.Ceil(float64(needed) / float64(surviving)))
	total := perDomain * domains
	return Plan{
		DemandRPS:         demandRPS,
		ReplicasNeeded:    needed,
		Domains:           domains,
		SpareDomains:      spareDomains,
		ReplicasPerDomain: perDomain,
		TotalReplicas:     total,
		UtilisationNormal: demandRPS / (float64(total) * s.PerReplicaRPS),
		UtilisationDegr:   demandRPS / (float64(perDomain*surviving) * s.PerReplicaRPS),
	}, nil
}

// OrderBy returns the latest date to place an order so capacity exists on
// needed, given procurement or quota lead time and a safety buffer.
func OrderBy(needed time.Time, leadTime, buffer time.Duration) time.Time {
	return needed.Add(-(leadTime + buffer))
}

// MonthlyCost is a simple linear cost model: replicas times unit price.
func MonthlyCost(replicas int, pricePerReplicaMonth float64) float64 {
	return float64(replicas) * pricePerReplicaMonth
}
go
package capacity

import (
	"math"
	"testing"
	"time"
)

func TestForecastCompoundsAndAppliesSeasonAndSteps(t *testing.T) {
	start := time.Date(2026, time.January, 15, 0, 0, 0, 0, time.UTC)
	g := Growth{
		MonthlyOrganic: 0.10,
		Seasonality:    []Season{{Month: time.November, Factor: 1.5}},
		Inorganic:      []Step{{Name: "partner launch", StartMonth: 6, Multiplier: 1.2}},
	}
	got, err := Forecast(1000, g, start, 10) // November
	if err != nil {
		t.Fatal(err)
	}
	want := 1000 * math.Pow(1.10, 10) * 1.2 * 1.5
	if math.Abs(got-want) > 1e-6 {
		t.Fatalf("got %.2f want %.2f", got, want)
	}
	early, _ := Forecast(1000, g, start, 3) // April, before the launch
	if math.Abs(early-1000*math.Pow(1.10, 3)) > 1e-6 {
		t.Fatalf("launch applied too early: %.2f", early)
	}
}

func TestForecastRejectsBadInput(t *testing.T) {
	if _, err := Forecast(0, Growth{}, time.Now(), 3); err == nil {
		t.Fatal("expected error for zero peak")
	}
}

func TestSizeN1AcrossThreeZones(t *testing.T) {
	// 9000 rps, 500 rps per replica at 60% target => 30 replicas of useful work.
	p, err := Size(9000, Service{PerReplicaRPS: 500, UtilisationTarget: 0.6}, 3, 1)
	if err != nil {
		t.Fatal(err)
	}
	if p.ReplicasNeeded != 30 || p.ReplicasPerDomain != 15 || p.TotalReplicas != 45 {
		t.Fatalf("unexpected plan: %+v", p)
	}
	if math.Abs(p.UtilisationNormal-0.4) > 1e-9 {
		t.Fatalf("normal utilisation %.3f", p.UtilisationNormal)
	}
	if p.UtilisationDegr > 0.6+1e-9 {
		t.Fatalf("after losing a zone utilisation %.3f exceeds target", p.UtilisationDegr)
	}
}

func TestSizeN2NeedsMoreThanN1(t *testing.T) {
	s := Service{PerReplicaRPS: 500, UtilisationTarget: 0.6}
	n1, _ := Size(9000, s, 4, 1)
	n2, _ := Size(9000, s, 4, 2)
	if n2.TotalReplicas <= n1.TotalReplicas {
		t.Fatalf("N+2 (%d) must cost more than N+1 (%d)", n2.TotalReplicas, n1.TotalReplicas)
	}
}

func TestSizeValidation(t *testing.T) {
	good := Service{PerReplicaRPS: 100, UtilisationTarget: 0.6}
	cases := []struct {
		name           string
		demand         float64
		s              Service
		domains, spare int
	}{
		{"one domain", 100, good, 1, 0},
		{"all spare", 100, good, 3, 3},
		{"zero target", 100, Service{PerReplicaRPS: 100}, 3, 1},
		{"zero demand", 0, good, 3, 1},
	}
	for _, c := range cases {
		if _, err := Size(c.demand, c.s, c.domains, c.spare); err == nil {
			t.Errorf("%s: expected error", c.name)
		}
	}
}

func TestOrderBy(t *testing.T) {
	need := time.Date(2026, time.November, 1, 0, 0, 0, 0, time.UTC)
	got := OrderBy(need, 60*24*time.Hour, 14*24*time.Hour)
	if want := need.Add(-74 * 24 * time.Hour); !got.Equal(want) {
		t.Fatalf("got %v want %v", got, want)
	}
}

func TestMonthlyCost(t *testing.T) {
	if MonthlyCost(45, 70) != 3150 {
		t.Fatal("cost model")
	}
}
go
// Package drplan picks a DR strategy from RPO/RTO targets and does the DNS
// failover arithmetic. Numbers in Strategies are planning defaults modelled on
// the AWS Well-Architected reliability pillar wording; replace them with your
// own measured values.
package drplan

import (
	"errors"
	"sort"
	"time"
)

// Strategy is one row of the DR cost curve.
type Strategy struct {
	Name         string
	TypicalRPO   time.Duration // data you can lose
	TypicalRTO   time.Duration // time to serve again
	CostFraction float64       // recovery-site cost as a fraction of production run cost
}

// Strategies is ordered from cheapest to most expensive.
var Strategies = []Strategy{
	{"backup-and-restore", 4 * time.Hour, 24 * time.Hour, 0.05},
	{"pilot-light", 15 * time.Minute, 40 * time.Minute, 0.15},
	{"warm-standby", 30 * time.Second, 10 * time.Minute, 0.40},
	{"active-active", 1 * time.Second, 1 * time.Minute, 1.00},
}

// Cheapest returns the cheapest strategy whose typical RPO and RTO both meet
// the targets for a data class.
func Cheapest(rpo, rto time.Duration) (Strategy, error) {
	if rpo <= 0 || rto <= 0 {
		return Strategy{}, errors.New("drplan: targets must be positive")
	}
	for _, s := range Strategies {
		if s.TypicalRPO <= rpo && s.TypicalRTO <= rto {
			return s, nil
		}
	}
	return Strategy{}, errors.New("drplan: no strategy meets both targets; relax them or engineer beyond the table")
}

// DataClass is one kind of data with its own targets.
type DataClass struct {
	Name         string
	RPO, RTO     time.Duration
	MonthlyRunUS float64 // monthly production run cost of the stack that serves it
}

// Row is one line of the planner output.
type Row struct {
	Class    string
	Strategy string
	ExtraUS  float64
}

// Table sizes the DR strategy per data class and returns rows sorted by cost,
// most expensive first, which is where to challenge the targets.
func Table(classes []DataClass) ([]Row, error) {
	rows := make([]Row, 0, len(classes))
	for _, c := range classes {
		s, err := Cheapest(c.RPO, c.RTO)
		if err != nil {
			return nil, errors.New(c.Name + ": " + err.Error())
		}
		rows = append(rows, Row{c.Name, s.Name, s.CostFraction * c.MonthlyRunUS})
	}
	sort.Slice(rows, func(i, j int) bool { return rows[i].ExtraUS > rows[j].ExtraUS })
	return rows, nil
}

// DNSFailover describes a health-check driven DNS failover.
type DNSFailover struct {
	CheckInterval    time.Duration // seconds between health checks
	FailureThreshold int           // consecutive failures before "unhealthy"
	RecordTTL        time.Duration // TTL on the DNS answer
	ClientOverrun    time.Duration // clients and resolvers that ignore or extend TTL
}

// Detection is the time until the health checker declares the endpoint down.
func (d DNSFailover) Detection() time.Duration {
	return time.Duration(d.FailureThreshold) * d.CheckInterval
}

// WorstCase is detection plus one full TTL plus the overrun some clients add.
func (d DNSFailover) WorstCase() time.Duration {
	return d.Detection() + d.RecordTTL + d.ClientOverrun
}

// MeetsRTO reports whether failover time leaves room for the rest of the
// recovery work (promotion, cache warm-up, validation).
func (d DNSFailover) MeetsRTO(rto, otherSteps time.Duration) bool {
	return d.WorstCase()+otherSteps <= rto
}

// ReplicationRPO is the data-loss window if the primary dies right now. With
// asynchronous replication the exposure is the current replication lag.
func ReplicationRPO(lag time.Duration) time.Duration { return lag }
go
package drplan

import (
	"testing"
	"time"
)

func TestCheapestPicksLowestCostThatMeetsBoth(t *testing.T) {
	cases := []struct {
		rpo, rto time.Duration
		want     string
	}{
		{24 * time.Hour, 48 * time.Hour, "backup-and-restore"},
		{30 * time.Minute, 1 * time.Hour, "pilot-light"},
		{1 * time.Minute, 15 * time.Minute, "warm-standby"},
		{5 * time.Second, 2 * time.Minute, "active-active"},
	}
	for _, c := range cases {
		got, err := Cheapest(c.rpo, c.rto)
		if err != nil || got.Name != c.want {
			t.Errorf("rpo=%v rto=%v got %v err %v want %s", c.rpo, c.rto, got.Name, err, c.want)
		}
	}
}

func TestCheapestRejectsImpossibleTargets(t *testing.T) {
	if _, err := Cheapest(0, time.Hour); err == nil {
		t.Fatal("zero RPO must be rejected")
	}
	if _, err := Cheapest(time.Millisecond, time.Millisecond); err == nil {
		t.Fatal("targets tighter than any row must error")
	}
}

func TestTableSortsByExtraCost(t *testing.T) {
	rows, err := Table([]DataClass{
		{"reports", 24 * time.Hour, 48 * time.Hour, 10000},
		{"payments", 5 * time.Second, 2 * time.Minute, 20000},
		{"catalogue", 30 * time.Minute, time.Hour, 8000},
	})
	if err != nil {
		t.Fatal(err)
	}
	if rows[0].Class != "payments" || rows[0].ExtraUS != 20000 {
		t.Fatalf("first row %+v", rows[0])
	}
	if rows[2].Class != "reports" || rows[2].ExtraUS != 500 {
		t.Fatalf("last row %+v", rows[2])
	}
}

func TestDNSFailoverMath(t *testing.T) {
	d := DNSFailover{CheckInterval: 10 * time.Second, FailureThreshold: 3, RecordTTL: 60 * time.Second, ClientOverrun: 120 * time.Second}
	if d.Detection() != 30*time.Second {
		t.Fatalf("detection %v", d.Detection())
	}
	if d.WorstCase() != 210*time.Second {
		t.Fatalf("worst case %v", d.WorstCase())
	}
	if !d.MeetsRTO(10*time.Minute, 5*time.Minute) {
		t.Fatal("210s + 300s fits in 600s")
	}
	if d.MeetsRTO(5*time.Minute, 5*time.Minute) {
		t.Fatal("must not fit when other steps use the whole RTO")
	}
}

func TestReplicationRPOIsLag(t *testing.T) {
	if ReplicationRPO(8*time.Second) != 8*time.Second {
		t.Fatal("RPO equals lag for async replication")
	}
}
go
// Package restoredrill proves a backup by restoring it into a scratch database
// and comparing row counts and checksums with a manifest written at backup time.
package restoredrill

import (
	"context"
	"database/sql"
	"fmt"
	"strings"
	"time"
)

// Scalar runs one query that returns a single text value.
type Scalar interface {
	Scalar(ctx context.Context, query string) (string, error)
}

// SQLDB adapts *sql.DB (any driver, for example pgx stdlib) to Scalar.
type SQLDB struct{ DB *sql.DB }

// Scalar implements Scalar.
func (s SQLDB) Scalar(ctx context.Context, query string) (string, error) {
	var out sql.NullString
	if err := s.DB.QueryRowContext(ctx, query).Scan(&out); err != nil {
		return "", err
	}
	return out.String, nil
}

// TableCheck is one line of the manifest written when the backup was taken.
type TableCheck struct {
	Table    string
	Rows     int64
	Checksum string // md5 of ordered primary keys, see verify-restore.sql
}

// Manifest describes the source database at backup time.
type Manifest struct {
	TakenAt time.Time
	Tables  []TableCheck
}

// Restorer restores the latest backup into the scratch database. In practice it
// shells out to pg_restore or pgBackRest and replays WAL to a target time.
type Restorer func(ctx context.Context) error

// Targets are the objectives the drill proves.
type Targets struct {
	RPO, RTO time.Duration
	// RowTolerance allows rows written between manifest and backup end.
	RowTolerance float64
}

// Result is the drill outcome.
type Result struct {
	RestoreTime time.Duration
	BackupAge   time.Duration
	Failures    []string
}

// OK reports whether the drill passed.
func (r Result) OK() bool { return len(r.Failures) == 0 }

// Run restores, then verifies. now is injected so tests are deterministic.
func Run(ctx context.Context, restore Restorer, scratch Scalar, m Manifest, t Targets, now func() time.Time) Result {
	start := now()
	res := Result{BackupAge: start.Sub(m.TakenAt)}
	if err := restore(ctx); err != nil {
		res.Failures = append(res.Failures, "restore failed: "+err.Error())
		return res
	}
	res.RestoreTime = now().Sub(start)
	if res.BackupAge > t.RPO {
		res.Failures = append(res.Failures, fmt.Sprintf("backup age %v exceeds RPO %v", res.BackupAge, t.RPO))
	}
	if res.RestoreTime > t.RTO {
		res.Failures = append(res.Failures, fmt.Sprintf("restore took %v, RTO is %v", res.RestoreTime, t.RTO))
	}
	for _, tc := range m.Tables {
		if err := checkTable(ctx, scratch, tc, t.RowTolerance); err != nil {
			res.Failures = append(res.Failures, err.Error())
		}
	}
	return res
}

func checkTable(ctx context.Context, db Scalar, tc TableCheck, tol float64) error {
	if !safeIdent(tc.Table) {
		return fmt.Errorf("%q is not a plain table name", tc.Table)
	}
	got, err := db.Scalar(ctx, "SELECT count(*)::text FROM "+tc.Table)
	if err != nil {
		return fmt.Errorf("%s: count failed: %w", tc.Table, err)
	}
	var rows int64
	if _, err := fmt.Sscan(got, &rows); err != nil {
		return fmt.Errorf("%s: bad count %q", tc.Table, got)
	}
	low := float64(tc.Rows) * (1 - tol)
	if float64(rows) < low {
		return fmt.Errorf("%s: %d rows restored, manifest has %d (tolerance %.1f%%)", tc.Table, rows, tc.Rows, tol*100)
	}
	if tc.Checksum == "" {
		return nil
	}
	sum, err := db.Scalar(ctx, fmt.Sprintf(
		"SELECT md5(string_agg(id::text, ',' ORDER BY id)) FROM (SELECT id FROM %s WHERE id <= %d ORDER BY id) t",
		tc.Table, tc.Rows))
	if err != nil {
		return fmt.Errorf("%s: checksum failed: %w", tc.Table, err)
	}
	if sum != tc.Checksum {
		return fmt.Errorf("%s: checksum %s differs from manifest %s", tc.Table, sum, tc.Checksum)
	}
	return nil
}

func safeIdent(s string) bool {
	if s == "" {
		return false
	}
	for _, r := range strings.ToLower(s) {
		if !(r == '_' || r == '.' || (r >= 'a' && r <= 'z') || (r >= '0' && r <= '9')) {
			return false
		}
	}
	return true
}
go
package restoredrill

import (
	"context"
	"errors"
	"strings"
	"testing"
	"time"
)

type fakeDB map[string]string

func (f fakeDB) Scalar(_ context.Context, q string) (string, error) {
	for prefix, v := range f {
		if strings.HasPrefix(q, prefix) {
			if v == "ERR" {
				return "", errors.New("boom")
			}
			return v, nil
		}
	}
	return "", errors.New("unexpected query: " + q)
}

// clock returns start, then start+step on every later call.
func clock(start time.Time, step time.Duration) func() time.Time {
	n := 0
	return func() time.Time {
		t := start.Add(time.Duration(n) * step)
		n++
		return t
	}
}

var t0 = time.Date(2026, 11, 1, 12, 0, 0, 0, time.UTC)

func manifest() Manifest {
	return Manifest{TakenAt: t0.Add(-30 * time.Minute), Tables: []TableCheck{{Table: "orders", Rows: 1000, Checksum: "abc"}}}
}

func targets() Targets {
	return Targets{RPO: time.Hour, RTO: 20 * time.Minute, RowTolerance: 0.01}
}

func ok(context.Context) error { return nil }

func TestDrillPasses(t *testing.T) {
	db := fakeDB{"SELECT count(*)": "1000", "SELECT md5": "abc"}
	r := Run(context.Background(), ok, db, manifest(), targets(), clock(t0, 12*time.Minute))
	if !r.OK() || r.RestoreTime != 12*time.Minute {
		t.Fatalf("%+v", r)
	}
}

func TestDrillFailsOnMissingRowsAndChecksum(t *testing.T) {
	db := fakeDB{"SELECT count(*)": "900", "SELECT md5": "zzz"}
	r := Run(context.Background(), ok, db, manifest(), targets(), clock(t0, time.Minute))
	if r.OK() || len(r.Failures) != 1 {
		t.Fatalf("row shortfall should stop before checksum: %+v", r)
	}
	db = fakeDB{"SELECT count(*)": "1000", "SELECT md5": "zzz"}
	r = Run(context.Background(), ok, db, manifest(), targets(), clock(t0, time.Minute))
	if r.OK() || !strings.Contains(r.Failures[0], "checksum") {
		t.Fatalf("expected checksum failure: %+v", r)
	}
}

func TestDrillFailsOnSlowRestoreAndOldBackup(t *testing.T) {
	db := fakeDB{"SELECT count(*)": "1000", "SELECT md5": "abc"}
	m := manifest()
	m.TakenAt = t0.Add(-3 * time.Hour)
	r := Run(context.Background(), ok, db, m, targets(), clock(t0, 25*time.Minute))
	if len(r.Failures) != 2 {
		t.Fatalf("want RPO and RTO failures, got %+v", r.Failures)
	}
}

func TestDrillReportsRestoreError(t *testing.T) {
	bad := func(context.Context) error { return errors.New("archive missing") }
	r := Run(context.Background(), bad, fakeDB{}, manifest(), targets(), clock(t0, time.Minute))
	if r.OK() || !strings.Contains(r.Failures[0], "archive missing") {
		t.Fatalf("%+v", r)
	}
}

func TestRejectsUnsafeTableName(t *testing.T) {
	m := Manifest{TakenAt: t0, Tables: []TableCheck{{Table: "orders; DROP TABLE x", Rows: 1}}}
	r := Run(context.Background(), ok, fakeDB{}, m, targets(), clock(t0, time.Minute))
	if r.OK() {
		t.Fatal("unsafe identifier must fail")
	}
}
go
// Command planner prints a capacity plan and a DR strategy table.
package main

import (
	"fmt"
	"os"
	"time"

	"academy/capacity-planning-disaster-recovery/capacity"
	"academy/capacity-planning-disaster-recovery/drplan"
)

func main() {
	start := time.Date(2026, time.January, 1, 0, 0, 0, 0, time.UTC)
	growth := capacity.Growth{
		MonthlyOrganic: 0.06,
		Seasonality:    []capacity.Season{{Month: time.November, Factor: 1.8}},
		Inorganic:      []capacity.Step{{Name: "new market", StartMonth: 6, Multiplier: 1.25}},
	}
	svc := capacity.Service{PerReplicaRPS: 420, UtilisationTarget: 0.6}

	fmt.Println("month  peak_rps  replicas(N+1,3 AZ)  normal_util  after_AZ_loss  monthly_cost_usd")
	for _, m := range []int{0, 3, 6, 10} {
		rps, err := capacity.Forecast(5000, growth, start, m)
		if err != nil {
			fail(err)
		}
		p, err := capacity.Size(rps, svc, 3, 1)
		if err != nil {
			fail(err)
		}
		fmt.Printf("%5d  %8.0f  %18d  %10.0f%%  %12.0f%%  %16.0f\n",
			m, rps, p.TotalReplicas, p.UtilisationNormal*100, p.UtilisationDegr*100,
			capacity.MonthlyCost(p.TotalReplicas, 70))
	}

	rows, err := drplan.Table([]drplan.DataClass{
		{Name: "payments ledger", RPO: 5 * time.Second, RTO: 2 * time.Minute, MonthlyRunUS: 30000},
		{Name: "orders", RPO: time.Minute, RTO: 15 * time.Minute, MonthlyRunUS: 20000},
		{Name: "catalogue", RPO: 30 * time.Minute, RTO: time.Hour, MonthlyRunUS: 12000},
		{Name: "analytics", RPO: 24 * time.Hour, RTO: 48 * time.Hour, MonthlyRunUS: 15000},
	})
	if err != nil {
		fail(err)
	}
	fmt.Println("\ndata class        strategy             extra_usd_per_month")
	for _, r := range rows {
		fmt.Printf("%-16s  %-19s  %8.0f\n", r.Class, r.Strategy, r.ExtraUS)
	}

	d := drplan.DNSFailover{CheckInterval: 10 * time.Second, FailureThreshold: 3, RecordTTL: 60 * time.Second, ClientOverrun: 120 * time.Second}
	fmt.Printf("\nDNS failover: detection %v, worst case %v, fits a 10m RTO with 5m of other steps: %v\n",
		d.Detection(), d.WorstCase(), d.MeetsRTO(10*time.Minute, 5*time.Minute))
}

func fail(err error) {
	fmt.Fprintln(os.Stderr, err)
	os.Exit(1)
}

The SQL the drill relies on, and the PostgreSQL statements for PITR markers, replication lag and promotion:

sql
-- Run on the SOURCE right after the backup starts (store the output as the manifest).
-- Run the same statements on the RESTORED scratch database and compare.
SELECT 'orders' AS table_name,
       count(*)  AS row_count,
       md5(string_agg(id::text, ',' ORDER BY id)) AS id_checksum
FROM orders
WHERE id <= 1000000;            -- fixed upper bound so late writes do not change the checksum

-- Invariants that must hold after any restore (cheap business checks).
SELECT count(*) AS orphan_order_items
FROM order_items oi
LEFT JOIN orders o ON o.id = oi.order_id
WHERE o.id IS NULL;             -- expect 0

SELECT max(created_at) AS newest_row, now() - max(created_at) AS data_age
FROM orders;                    -- data_age is the RPO you actually got
sql
-- PostgreSQL: is WAL archiving working? (monitor failed_count and last_archived_time)
SELECT archived_count, failed_count, last_archived_wal, last_archived_time, last_failed_time
FROM pg_stat_archiver;

-- PostgreSQL: mark a safe point before a risky migration; recover to it later
-- with recovery_target_name = 'before_migration_042'.
SELECT pg_create_restore_point('before_migration_042');

-- PostgreSQL standby in another region: replication lag in seconds (this is your RPO exposure).
SELECT now() - pg_last_xact_replay_timestamp() AS replay_delay,
       pg_is_in_recovery()                     AS is_standby;

-- On the primary: how many bytes each standby is behind.
SELECT application_name,
       pg_wal_lsn_diff(pg_current_wal_lsn(), replay_lsn) AS bytes_behind
FROM pg_stat_replication;

-- Promotion (run on the standby only after fencing the old primary).
SELECT pg_promote(wait => true, wait_seconds => 60);

The Go angle ​

Go's database/sql gives one interface over any driver, so the drill takes a tiny Scalar interface: production wraps a *sql.DB opened with a PostgreSQL driver, tests pass a fake and inject the clock, which makes failure paths (slow restore, old backup, checksum mismatch) testable without a database. Restore itself is an injected func(ctx) error that shells out to pg_restore or pgBackRest with os/exec and context timeouts. Table names cannot be bound as SQL parameters, so safeIdent allow-lists them. The standard library has no quota or DR concept; the value of the code is that the arithmetic (math.Ceil over domains) is explicit and unit-tested.

Laravel ​

Example ​

Laravel 13 has no backup feature; the common package is spatie/laravel-backup (version 10 supports Laravel 13 per its Packagist metadata). It zips files plus a database dump to any configured filesystem disk, encrypts the archive when password is set, cleans old backups with a retention strategy and monitors age and size. We add a custom command that uploads with S3 Object Lock, a restore drill command, health endpoints for failover, and a region config.

php
<?php

// config/backup.php (excerpt) for spatie/laravel-backup 10.x on Laravel 13.
// Keys follow the package's installation-and-setup page; check your installed version.
return [
    'backup' => [
        'name' => env('APP_NAME', 'laravel-backup'),
        'source' => [
            'files' => [
                'include' => [base_path()],
                'exclude' => [base_path('vendor'), base_path('node_modules'), storage_path('framework')],
            ],
            'databases' => ['pgsql'],
        ],
        'destination' => [
            // Two destinations on different providers or accounts: the "2 media, 1 offsite" part of 3-2-1.
            'disks' => ['s3_backups', 's3_backups_dr'],
        ],
        // Encrypt the archive; keep the password in a secrets manager, not next to the backup.
        'password' => env('BACKUP_ARCHIVE_PASSWORD'),
        'encryption' => 'default',
    ],

    'notifications' => [
        'notifications' => [
            \Spatie\Backup\Notifications\Notifications\BackupHasFailedNotification::class => ['mail', 'slack'],
            \Spatie\Backup\Notifications\Notifications\UnhealthyBackupWasFoundNotification::class => ['mail', 'slack'],
        ],
    ],

    // The monitor turns "the cron stopped" into an alert: stale backups are unhealthy.
    'monitor_backups' => [[
        'name' => env('APP_NAME', 'laravel-backup'),
        'disks' => ['s3_backups', 's3_backups_dr'],
        'health_checks' => [
            \Spatie\Backup\Tasks\Monitor\HealthChecks\MaximumAgeInDays::class => 1,
            \Spatie\Backup\Tasks\Monitor\HealthChecks\MaximumStorageInMegabytes::class => 20000,
        ],
    ]],

    'cleanup' => [
        'strategy' => \Spatie\Backup\Tasks\Cleanup\Strategies\DefaultStrategy::class,
        'default_strategy' => [
            'keep_all_backups_for_days' => 7,
            'keep_daily_backups_for_days' => 30,
            'keep_weekly_backups_for_weeks' => 12,
            'keep_monthly_backups_for_months' => 12,
            'keep_yearly_backups_for_years' => 2,
            'delete_oldest_backups_when_using_more_megabytes_than' => 50000,
        ],
    ],
];
php
<?php

// config/disaster.php - one place for region role, drill targets and failover switches.
return [
    // Which region this deployment is. Set per environment, never guess from DNS.
    'region' => env('APP_REGION', 'eu-west-1'),

    // 'primary' accepts writes; 'standby' serves reads and refuses writes until promoted.
    'role' => env('APP_REGION_ROLE', 'primary'),

    // Flipped by the runbook (config cache or an env change), not by code.
    'writes_enabled' => (bool) env('DR_WRITES_ENABLED', true),

    // Oldest data a standby may serve before /healthz/ready reports it unfit for traffic.
    'max_replica_lag_seconds' => (int) env('DR_MAX_LAG_SECONDS', 30),

    // Objectives proven by `php artisan dr:restore-drill`.
    'rpo_minutes' => (int) env('DR_RPO_MINUTES', 15),
    'rto_minutes' => (int) env('DR_RTO_MINUTES', 30),

    // Connections: the DR region has its own database host and its own S3 bucket.
    'connections' => [
        'eu-west-1' => ['db' => 'pgsql',         'backup_disk' => 's3_backups'],
        'eu-central-1' => ['db' => 'pgsql_dr',   'backup_disk' => 's3_backups_dr'],
    ],
];
php
<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\Storage;

/**
 * Upload an existing backup archive to an S3 bucket that has Object Lock enabled.
 * COMPLIANCE mode: nobody, including the root user, can delete the version until the date.
 * The bucket must be created with Object Lock and Versioning on (S3 requires versioning).
 */
class BackupLocked extends Command
{
    protected $signature = 'backup:lock-upload {path : local path of the archive} {--days=35}';

    protected $description = 'Upload a backup archive with an S3 Object Lock retention period';

    public function handle(): int
    {
        $path = (string) $this->argument('path');
        if (! is_file($path)) {
            $this->error("No such file: {$path}");

            return self::FAILURE;
        }

        $retainUntil = now()->addDays((int) $this->option('days'));
        $key = 'db/'.now()->format('Y/m/d/His').'-'.basename($path);

        /** @var \Illuminate\Filesystem\AwsS3V3Adapter $disk */
        $disk = Storage::disk('s3_locked');

        $disk->getClient()->putObject([
            'Bucket' => config('filesystems.disks.s3_locked.bucket'),
            'Key' => $key,
            'Body' => fopen($path, 'rb'),
            'ChecksumAlgorithm' => 'SHA256',
            'ServerSideEncryption' => 'aws:kms',
            'ObjectLockMode' => 'COMPLIANCE',
            'ObjectLockRetainUntilDate' => $retainUntil->toIso8601String(),
        ]);

        $this->info("Locked until {$retainUntil->toDateString()}: {$key}");

        return self::SUCCESS;
    }
}
php
<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Process;

/**
 * Restore the newest backup into a scratch database and compare it with the source.
 * A backup that was never restored is a hope, not a backup.
 */
class RestoreDrill extends Command
{
    protected $signature = 'dr:restore-drill {--archive= : path to a pg_dump custom-format file}';

    protected $description = 'Restore the latest backup into a scratch database and verify counts and checksums';

    public function handle(): int
    {
        $started = microtime(true);
        $archive = (string) $this->option('archive');
        $scratch = 'drill_'.now()->format('Ymd_His');

        // Scratch database on a separate host or at least a separate database name.
        $create = Process::run(['createdb', $scratch]);
        if ($create->failed()) {
            $this->error('createdb failed: '.$create->errorOutput());

            return self::FAILURE;
        }

        try {
            $restore = Process::timeout(60 * (int) config('disaster.rto_minutes'))
                ->run(['pg_restore', '--no-owner', '--dbname', $scratch, $archive]);
            if ($restore->failed()) {
                $this->error('pg_restore failed: '.$restore->errorOutput());

                return self::FAILURE;
            }

            config(['database.connections.drill' => array_merge(
                config('database.connections.pgsql'),
                ['database' => $scratch],
            )]);
            DB::purge('drill');

            $sql = 'SELECT count(*) AS n, md5(string_agg(id::text, \',\' ORDER BY id)) AS sum
                    FROM (SELECT id FROM orders WHERE id <= ? ORDER BY id) t';
            $expected = DB::connection('pgsql')->selectOne($sql, [1_000_000]);
            $actual = DB::connection('drill')->selectOne($sql, [1_000_000]);

            $seconds = (int) round(microtime(true) - $started);
            $ok = $expected->n === $actual->n && $expected->sum === $actual->sum
                && $seconds <= 60 * (int) config('disaster.rto_minutes');

            $this->table(['check', 'source', 'restored'], [
                ['rows', $expected->n, $actual->n],
                ['checksum', $expected->sum, $actual->sum],
                ['restore seconds', '-', $seconds],
            ]);

            return $ok ? self::SUCCESS : self::FAILURE;
        } finally {
            DB::purge('drill');
            Process::run(['dropdb', '--if-exists', $scratch]);
        }
    }
}
php
<?php

namespace App\Http\Controllers;

use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\DB;

/**
 * Health endpoints for load balancers and DNS failover health checks.
 * live  = the process runs (never touches dependencies; restart on failure)
 * ready = this region can serve traffic now (database reachable, lag acceptable)
 * region = what this deployment believes about itself (for runbooks and dashboards)
 */
class HealthController
{
    public function live(): JsonResponse
    {
        return response()->json(['status' => 'ok']);
    }

    public function ready(): JsonResponse
    {
        try {
            DB::select('select 1');
        } catch (\Throwable $e) {
            return response()->json(['status' => 'down', 'reason' => 'database'], 503);
        }

        if (config('disaster.role') === 'standby') {
            $row = DB::selectOne('select extract(epoch from now() - pg_last_xact_replay_timestamp()) as lag');
            $lag = (int) ($row->lag ?? 0);
            if ($lag > (int) config('disaster.max_replica_lag_seconds')) {
                return response()->json(['status' => 'degraded', 'lag_seconds' => $lag], 503);
            }
        }

        return response()->json(['status' => 'ok']);
    }

    public function region(): JsonResponse
    {
        return response()->json([
            'region' => config('disaster.region'),
            'role' => config('disaster.role'),
            'writes_enabled' => config('disaster.writes_enabled'),
        ]);
    }
}
php
<?php

// routes/web.php (excerpt). Laravel 13 also ships a built-in /up route configured in
// bootstrap/app.php (withRouting(health: '/up')); these add readiness and region detail.
use App\Http\Controllers\HealthController;
use Illuminate\Support\Facades\Route;

Route::get('/healthz/live', [HealthController::class, 'live']);
Route::get('/healthz/ready', [HealthController::class, 'ready']);
Route::get('/healthz/region', [HealthController::class, 'region']);

// Writes are refused outside the primary: a standby that accepts writes causes split brain.
Route::middleware('throttle:60,1')->group(function () {
    Route::post('/orders', function () {
        abort_unless(config('disaster.writes_enabled') && config('disaster.role') === 'primary', 503, 'Region is read-only');

        return response()->noContent(202);
    });
});
php
<?php

// routes/console.php (excerpt): the backup and drill schedule.
use Illuminate\Support\Facades\Schedule;

Schedule::command('backup:clean')->dailyAt('01:00')->onOneServer();

Schedule::command('backup:run')->dailyAt('01:30')->onOneServer()->withoutOverlapping(120)
    ->onFailure(function () {
        logger()->critical('backup:run failed');
    });

// Alert when backups are stale even if the scheduler itself died.
Schedule::command('backup:monitor')->dailyAt('05:00')->onOneServer();

// Prove restores weekly, outside the backup window.
Schedule::command('dr:restore-drill', ['--archive' => storage_path('app/drill/latest.dump')])->weeklyOn(0, '04:00')->onOneServer();

The Laravel angle ​

The scheduler (Schedule::command(...)->dailyAt()->onOneServer()->withoutOverlapping()) runs backups, cleanup, monitoring and the weekly drill; onFailure hooks react to a non-zero exit code. The backup:monitor command exists because a dead scheduler means no failure notification: monitoring checks that a fresh backup exists. The filesystem layer (Flysystem) lets one disks list write to two S3 buckets in different accounts, which is the "2" in 3-2-1; the s3_locked disk uses getClient() to reach the AWS SDK for Object Lock parameters Flysystem does not expose. Laravel's built-in /up route is liveness only; readiness here also checks the database and, on a standby, replica lag, so a load balancer or Route 53 health check does not send traffic to a region that cannot serve it. Writes are refused unless the region is the primary and writes_enabled is on, which prevents split brain during failover.

Solving the classic problems ​

The backup was never restored ​

SymptomCauseFix
Restore fails or data is missing during the incidentBackups never tested; missing extension, key or credentialWeekly scratch restore with dr:restore-drill, alert on failure

Replication copied the mistake ​

Problem: a bad DELETE or migration reached the standby in seconds. Fix: PITR with pg_create_restore_point before risky changes, delayed replica (PostgreSQL recovery_min_apply_delay) or immutable versioned backups, and least-privilege credentials.

Failover meets quota and cold caches ​

Problem: warm standby scales to 10x and hits vCPU quota; caches are cold so the database melts. Fix: request quota in the DR region, run a scale-up drill, pre-warm caches, rate-limit and shed load during the first minutes (see Load Shedding).

The DNS TTL surprise ​

Problem: TTL 3,600 s means up to an hour of traffic to the dead region. Fix: low TTL on failover names (60 s), health-checked records, and clients that re-resolve; compute worst case with the DNSFailover type.

Split brain after failover ​

Problem: old primary returns and accepts writes. Fix: fence first (revoke credentials, block at network, set writes_enabled=false), promote second; use fencing tokens (see Distributed Locking).

Everything was in one account ​

Problem: ransomware or a compromised admin deletes backups with the data. Fix: backups in a separate account with Object Lock COMPLIANCE, separate credentials, no delete permission for production roles.

Choosing ​

Which DR strategy ​

SituationStrategyExtra techniqueReason
Internal tool, tolerates a dayBackup and restoreIaC, scratch restore monthlyCheapest; RTO hours
Business app, hour-scale RTO, minutes RPOPilot lightContinuous replication, drilled scale-outData safe, compute on demand
Customer-facing, minutes RTOWarm standbyQuota in DR region, health-checked DNSFast recovery without paying double
Money movement, near-zero lossActive-active or sync replicationConflict rules, idempotencyHighest cost, only for what needs it
Regulated, ransomware concernAny plus immutable offsiteObject Lock COMPLIANCE, separate accountBackups must survive credential theft

Which redundancy ​

RequirementChoice
Survive host or AZ lossMulti-AZ, N+1
Survive a bad deploy blast radiusCells and canaries
Survive region lossMulti-region with a strategy above
Survive provider lossBackups and a minimal rebuild elsewhere

In architecture: from a single process to a distributed system ​

Monolith: one process, one database ​

One application server and one PostgreSQL. Capacity: load test one server, keep 40% headroom, vertical scale first. DR: nightly pg_basebackup plus WAL archive to an S3 bucket in another region with versioning; weekly scratch restore; RPO minutes, RTO an hour or two. Config in Git, secrets in a manager, IaC for the server. Laravel: spatie/laravel-backup plus dr:restore-drill.

Modular monolith: boundaries without the network ​

One deployable, several schemas or databases. Each data class gets its own RPO and RTO (orders tight, reports loose), and restore order matters: reference data before orders. Backups must be consistent across databases (take them at the same logical moment or restore to a common point with restore points).

Microservices: every arrow is a decision ​

checkout -> payments (db A)     RPO 5 s,  warm standby
checkout -> catalogue (db B)    RPO 30 min, pilot light
checkout -> search (index)      rebuild from catalogue events

Each service owns its data class and DR strategy, but a user journey is only as recoverable as its weakest dependency: payments in warm standby with catalogue in backup-and-restore means checkout fails for hours. Independent backups of several datastores restore to inconsistent states unless reconciled (the SRE book's warning). Use outbox and idempotency to replay (see Messaging fundamentals).

Distributed data: replicas, caches, regions ​

Async cross-region replicas give RPO equal to lag; quorum across regions gives near-zero RPO at the price of cross-region write latency (see CAP and PACELC and Replication Topologies). Caches are rebuildable but the stampede is not: warm them. Kafka needs MirrorMaker 2 and offset translation. DNS and global load balancing decide who sees which region.

Scaling path: 1x, 10x, 100x ​

ScaleCapacity practiceDR practice
1x: one teamLoad test once, 40% headroom, manual forecastBackups offsite, restore monthly
10x: tens of servicesN+1 across AZs, forecast in code, quotas trackedPilot light or warm standby for tier 1, quarterly drill
100x: many regionsIntent-based planning, cells, automated quota and lead-time trackingActive-active for the few services that need it, game days, evacuation drills, status page and BCP rehearsed

Lab: forecast, size, break and restore ​

Experiment 1: run the planner (run) ​

cd docs/snippets/system-design/capacity-planning-disaster-recovery/go
go run ./cmd/planner
# month  peak_rps  replicas(N+1,3 AZ)  normal_util  after_AZ_loss  monthly_cost_usd
#     0      5000                  30          40%            60%              2100
#    10     20147                 120          40%            60%              8400
# payments ledger  active-active 30000 ... analytics backup-and-restore 750
# DNS failover: detection 30s, worst case 3m30s, fits a 10m RTO with 5m of other steps: true

Experiment 2: the tests (run) ​

go test ./...
# ok  .../capacity
# ok  .../drplan
# ok  .../restoredrill

Experiment 3: PITR to just before a bad delete (expected, not run) ​

psql -c "SELECT pg_create_restore_point('before_delete');"
psql -c "DELETE FROM orders;"                       # the mistake
# on a scratch host: restore base backup, then in postgresql.conf
#   restore_command = 'cp /archive/%f %p'
#   recovery_target_name = 'before_delete'
touch $PGDATA/recovery.signal && pg_ctl start
# expect: log line "recovery stopping at restore point" then the table has its rows back

Experiment 4: Object Lock refuses a delete (expected, not run) ​

aws s3api put-object --bucket locked-backups --key db/x.dump --body x.dump \
  --object-lock-mode COMPLIANCE --object-lock-retain-until-date 2027-01-01T00:00:00Z
aws s3api delete-object --bucket locked-backups --key db/x.dump --version-id <id>
# expect: AccessDenied (the version is protected until the retain-until date)

Experiment 5: Laravel drill (expected, not run) ​

php artisan backup:run --only-db
php artisan dr:restore-drill --archive=storage/app/drill/latest.dump
# expected table: rows and checksum equal, restore seconds under the RTO; exit code 0

Experiment 6: a tabletop (no tools) ​

State: "Region A is down at 14:00." Walk the runbook aloud: who declares, who fences, who promotes, what the status page says at 14:10, when you fail back. Time each step and write down every unknown.

Common misconceptions ​

BeliefReality
Multi-AZ is disaster recoveryIt covers a data centre loss, not bad data, bad deploys or regions
Replication is a backupReplication propagates deletes and corruption
Backups are done when the job is greenOnly a restore proves them
N+1 is one extra serverIt is one extra failure domain of capacity
Autoscaling replaces planningQuota, lead time and cold starts bound it
DNS failover is instantIt is health-check time plus TTL plus clients
Active-active needs no DRBad data and bad deploys hit both sites
One RPO/RTO fits all dataTargets belong to data classes
CPU at 100% is capacityCapacity is the rate that keeps the SLO
DR is an infrastructure projectIt includes people, decisions, communication and BCP
Failback is just failover reversedThe old primary has diverged data and must be rebuilt

Cheat sheet ​

TopicRemember
Replicasceil(ceil(demand / (rps x target)) / surviving domains) x domains
Forecastpeak x growth^months x steps x season
Utilisation targetAround 60% as a starting point; measure your own
Lead timeOrder date = need date minus lead time minus buffer
RPOReplica lag or time since last backup/WAL
RTODetect + decide + fence + promote + switch + verify
3-2-13 copies, 2 media or accounts, 1 offsite, make one immutable
PITRBase backup + WAL + recovery target
StrategiesBackup and restore, pilot light, warm standby, active-active
DNS worst caseinterval x threshold + TTL + overrun
Control planeFailover with data plane only
FailbackRebuild old primary as standby, reconcile, switch at a quiet time
ProofScratch restore with row counts and checksums
CultureDrill, game day, blameless review

Self-check: questions & answers ​

Show:
  • Must-know asked in almost every interview
  • Important frequent; expected at senior level
  • Good to know extra depth that sets you apart

1 — Why is N+1 across three zones 50% more capacity, not one extra server? Important ​

Answer

Answer: Losing a zone removes a third of the fleet; the other two zones must carry all the load, so each needs 1.5x its normal share.

2 — What do you need to measure before sizing a fleet? Must-know ​

Answer

Answer: Per-replica capacity at the latency SLO from a load test, plus the demand forecast peak.

3 — Why is replication not a backup? Must-know ​

Answer

Answer: It copies deletes and corruption to all replicas within seconds; backups keep history.

4 — Define RPO and RTO and give each a measurement. Must-know ​

Answer

Answer: RPO: data loss window, measured as replication lag or backup age. RTO: downtime, measured from failure to verified serving.

5 — Which DR strategy fits RPO 30 s and RTO 5 minutes? Important ​

Answer

Answer: Warm standby, with active-active if the RTO must be near zero.

6 — What is the worst-case DNS failover time with 10 s checks, 3 failures, TTL 60 s and 120 s overrun? Good to know ​

Answer

Answer: 30 + 60 + 120 = 210 seconds.

7 — Why use a separate account and Object Lock for backups? Important ​

Answer

Answer: Ransomware or stolen admin credentials cannot delete an immutable copy held under different credentials.

8 — Why fence the old primary before promoting? Important ​

Answer

Answer: Otherwise both accept writes (split brain) and failback needs painful reconciliation.

9 — How does a Kafka consumer fail over with MirrorMaker 2? Good to know ​

Answer

Answer: Read the replicated, prefixed topics, translate offsets from checkpoints, and tolerate duplicates because replication is asynchronous.

10 — What does a restore drill check? Must-know ​

Answer

Answer: Restore succeeds, row counts and checksums match, backup age is within RPO and restore time within RTO.

Glossary ​

TermMeaning
Capacity planningDeciding how much capacity to have, when
Demand forecastProjected peak load over time
Organic growthTrend growth from existing behaviour
Inorganic growthStep change caused by a launch or campaign
SeasonalityRepeating calendar effect on demand
HeadroomDeliberately unused capacity
N+1 / N+2Capacity survives loss of one / two units
Failure domainComponents that fail together
Lead timeDelay from decision to capacity serving
Utilisation targetPlanned fraction of per-replica capacity in use
Per-replica capacityRate one replica sustains inside the SLO
Load testRamped traffic experiment to find capacity
Intent-based capacity planningGenerating allocations from stated requirements (Google Auxon)
Cost modelFormula for monthly spend including DR
Failure scenarioSpecific loss with trigger and recovery path
Control plane / data planeConfigures resources / serves live traffic
Active-activeSeveral sites serve traffic
Active-passiveOne site serves, one waits
Cold standby / pilot light / warm standbyNothing running / data tier running / scaled-down copy running
Multi-AZ / multi-regionSpread over zones / regions
Cell-based architectureIndependent full copies limiting blast radius
RPO / RTOTolerated data loss / downtime
Data classData grouped by recovery targets
Full / incremental backupEverything / changes since last
PITRPoint-in-time recovery from base backup plus WAL
3-2-1 rule3 copies, 2 media, 1 offsite
Immutable backup / Object LockCannot be changed or deleted until a date
Restore testRestoring to prove a backup works
PromotionTurning a standby into the primary
DNS failover / TTLHealth-check driven DNS switch / answer cache lifetime
Failback / reconciliationReturning to the original site / merging divergent writes
MirrorMaker 2Kafka cross-cluster replication
Runbook / DR drill / game dayScript / rehearsal / multi-team exercise
BCPBusiness continuity plan
MTTRMean time to recover
laravel-backupThe spatie/laravel-backup package

References ​

Built by Morteza Negahi