Skip to content
Tech Interview Prep
Technical interview guide

High Availability & Disaster Recovery

Designing for component failure as the expected case, and the RTO/RPO trade-off that shapes disaster-recovery strategy.

Minutes to read
3
Practice MCQs
25
Interview Q&A
25
Edition
v7
Editorial status
Reviewed

Scope: AWS Well-Architected reliability and DR guidance, Google Cloud DR architecture, and Azure reliability guidance accessed 2026-08-30..

Interview Q&A

Treat each question like a live interview question: answer out loud first (structure, assumptions, tradeoffs), then open the model answer to spot gaps and rehearse a tighter follow-up.

Curated: · Written: · Reviewed:

25 questions

Q&A-1

Explain the difference between high availability and disaster recovery.

Answer

What a strong candidate says first (60–120s). These are two different objectives, and the interview answer names the objective before the technology. High availability keeps a service serving through the failures you designed for (a host, an instance, an AZ, a bad deploy) by running redundant capacity and moving traffic to it automatically. Its budget is seconds to a couple of minutes, and its RPO is usually zero because the standby is synchronous. Disaster recovery restores service and data after an event that exceeds that design: a region, a control plane, or the data itself. Its budget is RTO and RPO, and it is a capability you rehearse, not a property of the running system. I'd pin the numbers first: what RPO and RTO does the business actually need, and which failure classes are in scope.

Mechanism: how each one actually works.

HA failover is a detection-and-routing loop. A health check samples the target; after N consecutive failures the load balancer stops sending traffic; a standby takes over. Every stage costs time, and the defaults are the budget:

  • ALB target group defaults: 30s interval, unhealthy threshold 2 → 60s to mark a target unhealthy.
  • A Route 53 failover record with a 60s TTL → clients re-resolve within about a minute.
  • Total: roughly 120s of errors before traffic lands on healthy capacity.

RDS Multi-AZ is the data-side version: synchronous replication to a standby in another AZ, so RPO is 0 for an AZ failure, and AWS documents failover as typically 60–120s.

DR is a replication-mode decision, and the mode sets the RPO. Synchronous replication gives RPO 0 but adds a round trip to every write. Asynchronous replication gives a small RPO and no write penalty. Aurora Global Database documents RPO around 1 second and RTO typically under a minute; S3 Cross-Region Replication with Replication Time Control replicates 99.99% of objects within 15 minutes. The RTO side is the restore or promote path, and that is the part people forget to measure.

Capacity arithmetic for HA. Three AZs each sized at 50% of peak means you run 150% of minimum; losing one AZ leaves 100% and the service holds. Size each AZ at 33% and losing one leaves 66%: the service degrades. That headroom is the HA bill.

Trade-offs and deciding criteria.

HADR
Failure scopehost, AZ, deployregion, control plane, data corruption
Budgetseconds–minutesRTO/RPO in the contract
Replicationusually synchronoussync or async, chosen by RPO
Costextra AZ headroom (1.5× minimum above)pilot light ~10–20% of prod; backup/restore near storage cost
Verified byfailover drillsrestore game days

The deciding criterion is RPO. If the business cannot lose a committed write, you pay for synchronous replication and accept the latency. If it can lose a minute, async is cheaper and simpler. If RTO is hours, backup-and-restore is a legitimate posture: a DR-only design is fine for internal tooling, batch jobs, and anything where a day of downtime costs less than a second region.

Failure modes.

  • Split brain: two nodes both believe they are primary and accept writes. Detect with a quorum/witness node; fence the loser (STONITH) rather than trusting the network.
  • Failover to a stale replica: async lag means promotion loses the last N seconds. Watch replication lag as a first-class metric and alert before it crosses your RPO.
  • HA that replicates corruption: a synchronous standby faithfully copies a bad DELETE. HA cannot help; point-in-time recovery can. This is the case that proves the two are not substitutes.
  • Untested DR: the plan restores in 6 hours because nobody measured, and the RTO was 1 hour. Run a restore game day quarterly and record the actual time.
  • Backup that exists but does not restore: missing KMS key, wrong region, or an IAM role that no longer exists. Restore into a scratch account to prove the path.

The one-line close. HA is about not going down; DR is about coming back, and the numbers, not the architecture diagram, tell you which one you bought.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-2

How do you derive RTO and RPO for a business service?

Answer

I start by asking what the business loses per minute, not what the DR vendor sells. RTO is the longest outage the service can take before that loss becomes unacceptable. RPO is the oldest write the business can tolerate losing, expressed as time since the last durable write. Both are business decisions; engineering's job is to say what each one costs and where it breaks.

Assume a checkout service. I'd run a tabletop with product, finance, support, and compliance. We walk three failure scenarios: single AZ, whole region, and data corruption. For each, we write the impact curve. Hypothetical: 0–5 min, no revenue loss but support tickets; 5–30 min, checkout fails, $4k/min lost; 30–60 min, SLA credits and regulatory notification; beyond 60 min, brand damage and contract breach. That curve gives a candidate RTO of 15 min if we can fail over before the revenue line steepens. For RPO, we ask which writes are unrecoverable: payment authorizations, order state, audit events. If losing 1 min of orders is acceptable but losing an audit event is not, checkout gets RPO 1 min and the audit log gets RPO 0.

Then I map dependencies. A service RTO cannot be shorter than the slowest critical dependency unless we have a degraded mode. If checkout needs auth, inventory, and payment, and payment's own RTO is 30 min, checkout's 15 min is fiction. I draw the chain and either renegotiate payment's RTO or add a local queue that accepts orders and reconciles later. That degraded mode changes the RTO definition: checkout is "up" for order capture but not for authorization.

The numbers then translate into architecture. RPO 1 min with async replication means replication lag must stay under 1 min, including during bulk loads. For a PostgreSQL primary, I'd watch pg_stat_replication replay lag and alert at 50% of RPO. RTO 15 min means warm standby with automated failover, not restore from backup. A backup/restore path might have RTO 4 h and RPO 24 h; that's fine for internal admin, not for checkout. Sync replication gives RPO 0 but adds write latency; measure p99 before promising it. Active-active can give near-zero RTO/RPO but moves the problem to conflict resolution and data ownership.

tierexample serviceRTORPOmechanismcost
1checkout15 min1 minwarm standby, async replicationhigh
2admin8 h24 hbackup/restorelow
3audit4 h0sync replication, PITRhigh

These are hypothetical, not defaults.

Failure modes I watch: replication lag grows silently during bulk import; alert at 50% of RPO and page before breach. Backup restore is untested; run a timed restore drill quarterly and record actual RTO. DNS TTL keeps clients on the dead region; measure client reconnect time after failover. A dependency fails over separately; game day the whole chain. Data corruption replicates to standby; RPO 0 doesn't save you, so keep point-in-time recovery and a delayed replica.

Finally, I test achieved RTO/RPO, not designed. A failover game day measures detection, decision, promotion, DNS, app reconnect, and data loss. If achieved RTO is 40 min against a 15 min objective, the objective is not met; either fix the chain or go back to the business with the real cost.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-4

How do you identify hidden correlated failures in a redundant architecture?

Answer

"Hidden" correlated failure means the replicas look independent at the layer you designed (separate processes, separate AZs) but share something below that layer, so one event removes both. My assumption: redundancy is at the process or AZ level, and I'm hunting for shared ancestors underneath. The core answer: build the dependency graph, enumerate every ancestor both replicas share, then prove each one with fault injection.

Two replicas are independent only if no single event can remove both. So the question isn't "are there two of them" but "what do they both depend on." I walk the graph from each replica up through network path, account, identity, keys, quotas, deploy pipeline, capacity pool, third parties, and observability, and mark every node with two or more replicas under it. Each marked node is a candidate correlated failure.

Worked example: shared KMS quota. Two replicas, us-east-1a and us-east-1b, same account, same KMS key for envelope-encrypting session tokens. KMS symmetric requests are quota'd per account per region: say 5,500 req/s (hypothetical). Each replica peaks at 3,000 req/s during a login storm. Individually fine. Together 6,000 > 5,500, so both throttle at once. Detection: the KMS ThrottledRequests metric and the app's decrypt-error rate. Cost: logins fail in both AZs simultaneously. The "redundant" pair fails as one. Fix: separate keys per AZ, or cache the data key and fail open on throttle.

Shared ancestorConcrete exampleDetectionCost
Network pathBoth AZs egress via one BGP session to one transit providerBGP session state, route-leak alertsBoth AZs lose egress together
QuotaSame KMS key/account quotaThrottledRequestsBoth throttle together
Deploy pipelineOne pipeline, one release waveDeploy event vs error spikeBad config hits both
IdentityOne IAM role, one certCert expiry, AssumeRole errorsBoth lose auth
Capacity poolBoth replicas on one rack/PDURack topology, power feedOne PDU trip kills both
Third partyOne SaaS dependencyVendor status, error rateVendor outage takes both
ObservabilityOne metrics backendAlert silenceYou can't see the failure

Failure modes and how I catch them. BGP: both AZs on one transit session. Detected by session-state monitoring and route-leak detection, cost is full region egress loss. Deploy: one pipeline ships both replicas in the same wave. Detected by correlating deploy events with error spikes, cost is a bad config taking both. Observability: if the metrics backend is the shared ancestor, the failure is silent. Detected by a dead-man's-switch alert that fires when metrics stop arriving.

Trade-offs. You can't remove every shared ancestor: cost and operability grow. So rank by blast radius and likelihood, then separate (different accounts, providers), stagger (canary, wave deploys), add degraded modes (cache fallback, fail open), or accept and document the residual risk against objectives. Don't over-separate: per-AZ accounts make cross-AZ debugging and cost attribution painful.

Validation. Fault injection: kill the shared ancestor and watch whether both replicas go down. Access reviews for shared credentials. Chaos experiments on the deploy pipeline and quota paths.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-5

Compare synchronous and asynchronous replication for DR.

Answer

Assume a primary in one region and replicas in another, and that the RPO target is what actually decides this. Default: synchronous commit inside a region or metro, asynchronous across regions, with the async lag measured and alerted rather than assumed.

What each one actually waits for

PostgreSQL's synchronous_commit has four relevant settings. on waits for the standby to flush WAL to disk. remote_write waits only for the standby's kernel to accept the write: cheaper, but a standby power loss can lose it. remote_apply waits until the standby has replayed the commit, so a read there sees it. off doesn't even fsync locally.

Commit latency is roughly one RTT to the standby plus its fsync. Same-AZ RTT is ~0.5 ms, so p50 commit goes from ~1 ms to ~2–3 ms: invisible. us-east-1 to us-west-2 is ~65 ms RTT, so every commit pays ~65 ms; a transaction with 20 sequential commits goes from 20 ms to ~1.3 s. That arithmetic, not a principle, is why cross-region sync usually loses.

Quorum is the knob that decides whether you block

synchronous_standby_names = 'ANY 1 (a, b, c)' requires one ack from three standbys; losing one doesn't block. FIRST 1 (a, b) counts only a: lose a and every write blocks. Same latency, very different availability.

Failure modes

Sync standby unreachable: PostgreSQL does not fall back to async. Commits block indefinitely. Detection: pg_stat_activity rows with wait_event_type = 'IPC' and wait_event = 'SyncRep', and pg_stat_replication.sync_state dropping from sync to potential. Incident shape: primary healthy, CPU near zero, every application write timing out. Reads like a network partition, is actually a replication config.

MySQL semi-sync is worse in a specific way: rpl_semi_sync_source_timeout defaults to 10000 ms, and after 10 s without an ack the source silently reverts to async and keeps committing. Detection: Rpl_semi_sync_source_status flips to OFF and Rpl_semi_sync_source_no_tx increments. You believe you're synchronous and you are not.

Async: RPO is the lag at the instant of failure. Measure it: on the primary, pg_stat_replication.replay_lag and the gap between replay_lsn and pg_current_wal_lsn(). Steady-state cross-region streaming is tens of ms to low seconds; a bulk load or index build pushes it to minutes. MySQL's Seconds_Behind_Source reads 0 when the replica or source is idle, so it under-reports exactly when you're checking.

syncasync
acked-write RPO0lag at failure
commit cost+1 RTT~0
primary availabilityblocks on quorum lossunaffected
cross-region viablerarelyyes

Promotion and what neither covers

Before promoting an async replica, compare its last replayed LSN to the primary's last known LSN; everything after is gone. Aurora Global Database publishes RPO under 1 s and RTO under 1 min for managed cross-region failover: a vendor figure for a managed system, not a property of async replication.

Neither mode covers DROP TABLE, ransomware, or storage corruption: those replicate. Keep PITR backups and test restore, because that's the only thing that answers those.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-9

Explain split brain and how you prevent it during disaster recovery.

Answer

Split brain is two nodes or sites both acting as primary and accepting writes, so their histories diverge and you reconcile by hand. You prevent it two ways at once: make "who is primary" a decision a majority agrees on, and make the resource being written to reject anyone who isn't the current primary. Quorum alone isn't enough: the fence has to be enforced at the storage layer, not by the client's good behaviour.

Assumptions: two sites, one active primary, a standby that can be promoted, and a shared resource both can reach. If the resource is reachable from only one site, you have a partition problem, not a split-brain problem.

Why quorum works. A Raft or ZAB group of N voters needs ⌈(N+1)/2⌉ to elect a leader and commit. Three nodes tolerate one failure; five tolerate two. A partitioned minority can't elect anyone, so it can't accept writes: the minority is unavailable by construction. Odd sizes matter: four nodes need three for quorum, the same fault tolerance as three, one more machine to run. etcd defaults to --heartbeat-interval 100 ms and --election-timeout 1000 ms; a follower that misses heartbeats for the election timeout starts an election. Consul and ZooKeeper are the same shape.

Why leases need a clock bound. A leader lease says "I'm primary until T." For that to be safe, the lease must expire before any new leader can be elected, and its duration must exceed worst-case clock skew plus network delay. NTP drift of 300 ms with a 1 s lease is fine; a 2 s VM pause under GC is not. Leases are weaker than quorum: they trade safety for availability and rest on a clock you don't control.

Why fencing must be enforced by the resource. Epochs (fencing tokens) are the belt to quorum's braces. Every promotion increments a monotonic epoch. The storage layer (a database row, an S3 object with a conditional write, a distributed lock) rejects any write carrying an epoch lower than the highest it has seen. The old primary can still be running and still think it's primary; its writes get rejected. Kleppmann's point: a lock service that hands out tokens without the resource checking them gives you nothing.

Worked trace. Three etcd nodes, two in site A, one in site B. The inter-site link drops. Site A keeps quorum (2 of 3), the leader stays, writes continue. Site B's node can't reach quorum, steps down, refuses writes: no split brain, availability preserved on the majority side.

Now put Postgres primary in site A, standby in site B, Patroni managing failover through etcd, heartbeat every 1 s, promote after 5 s. Link drops. Site B's Patroni sees no leader and tries to take the etcd leader key: it can't, because etcd quorum is in site A, so it doesn't promote. If etcd itself splits and site A's two nodes die, site B's single node can't elect either: down, but consistent.

The case you're actually defending against is a standby that promotes without quorum: a manual pg_ctl promote, a broken health check, an operator in a hurry. Fencing saves you there: the promoted standby bumps the epoch, and the old primary's writes get rejected.

Failure modes and detection.

  • Clock skew breaks leases. Two nodes both believe they hold the lease. Detect by logging lease acquisition timestamps and alerting on overlapping windows.
  • Fencing token not checked by storage. Silent divergence. Detect by comparing write epochs at the storage layer, or a periodic checksum over the primary key range.
  • Quorum loss. Writes fail with "no leader." Intended trade-off, not a bug, but losing the majority site means losing writes, not just the standby.
  • STONITH fails. The fencing authority (IPMI, cloud API) is unreachable or the node ignores power-off. Verify the node is actually down before promoting, not just that you sent the command.
  • Healed partition with divergent writes. Duplicate sequence numbers, conflicting rows. Detect with a reconciliation job that runs on every failover, not on suspicion.

What would change the decision. If the workload tolerates dual writes (a CRDT, a last-writer-wins counter, an append-only log with idempotent replay) skip quorum and accept both sides, but name the merge rule and why it's correct for the data. Last-write-wins is fine for a "last seen" timestamp, wrong for a bank balance. If the resource is reachable from only one site, quorum is overkill; a lease with a generous TTL is enough. If you can't get a third site or a witness, you're choosing between availability and consistency on every partition: pick one and write it down.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-10

How do you design health checks for HA and failover?

Answer

First I'd ask what "healthy" means for this service and which traffic class we're protecting. Then I split signals into three layers, because conflating them is the classic HA bug: liveness (process is alive (restart me), readiness (I can serve this traffic right now) take me out of rotation), and end-to-end (users are actually succeeding. Page a human). Kubernetes gives you the first two as probes; the third is a metric, not a probe.

Assumptions: Kubernetes 1.29, a primary/replica datastore (Postgres managed by Patroni), HAProxy or a Service in front.

Layer 1: liveness. Cheap, local, no dependencies. exec: pg_isready or an HTTP /livez that returns 200 if the process loop is running. Defaults matter: periodSeconds: 10, timeoutSeconds: 1, failureThreshold: 3 → 30s before a restart. Don't put a database ping in liveness; a slow dependency turns into a restart storm.

Layer 2: readiness. This is where the failover decision lives. For a Postgres replica, readiness must answer "am I the role the router expects?" Patroni exposes /primary, /replica, /health; HAProxy checks /primary on the primary backend and /replica on the replica backend. A replica 40 MB behind in WAL replay is not ready for read-your-writes traffic: check pg_stat_replication lag or Patroni's /replica?lag=....

Layer 3: end-to-end. Synthetic probe or SLO burn rate: "can a client complete a write and read it back?" This catches the case where every probe is green and users are still failing.

Worked trace: failover. Primary dies at t=0. Patroni loop_wait: 10, retry_timeout: 10, ttl: 30. The leader key in etcd expires at t≈30s. Replicas race for the key; the winner promotes, runs pg_ctl promote, and starts returning 200 on /primary. HAProxy's health check (2s interval, 3 failures) removes the old primary at t≈6s and adds the new one at t≈32s. Total write outage ≈ 32s. If your readiness check is a plain TCP connect, HAProxy keeps routing to the dead primary for the full 30s TTL: that's the difference between a 6s and a 32s outage.

Trade-offs: dependency checks in readiness. Two credible designs:

  • Shallow readiness (process + role only): fast, no load on dependencies, but can route to a node whose datastore is unreachable.
  • Deep readiness (query the dependency): accurate, but N pods × every 10s = N/10 QPS against the dependency. At 200 pods that's 20 QPS of health traffic; if each check holds a connection for 50ms, that's ~1 concurrent connection: fine. If the check runs a SELECT count(*), it isn't.

Deciding criteria: check the dependency in readiness only if (a) the dependency is per-node and can fail independently, and (b) the check is O(1) and bounded. Otherwise use a separate, lower-frequency end-to-end probe.

Failure modes.

  1. Split-brain. Network partition; both nodes pass local liveness and readiness because neither checks the other. Both accept writes. Detection: two nodes returning 200 on /primary with different timeline values in pg_control. Cost: manual reconciliation, lost writes. Fix: quorum-based leader election (etcd/Patroni) plus fencing. STONITH via IPMI or a /dev/watchdog that reboots the node if it can't renew its lease.
  2. Restart storm. Liveness timeoutSeconds: 1 on a JVM with 2s GC pauses → kubelet kills it → cold start → more load. Detection: kube_pod_container_status_restarts_total climbing, p99 latency rising. Fix: startup probe, or raise failureThreshold to 5.
  3. Flapping. A node oscillates ready/not-ready every 10s. Detection: endpoint churn in kube_endpoint_address metrics. Fix: failureThreshold: 3 + successThreshold: 2 + minimum failure duration (Patroni retry_timeout) so a single blip doesn't move traffic.
LayerQuestionProbeTypical configOn failure
LivenessProcess alive?pg_isready / /livezperiod 10s, timeout 1s, threshold 3Restart container
ReadinessRight role, caught up?Patroni /primary, /replica?lag=period 2s, threshold 3Remove from endpoints
End-to-endUsers succeeding?Synthetic write+readperiod 30sPage on-call

The one-line rule: liveness is local and cheap, readiness encodes the failover contract (role + lag + quorum), and anything that touches a shared dependency belongs in a lower-frequency end-to-end check with an owner and a runbook.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-22

How do queues change HA and DR design?

Answer

The 90-second answer. A queue moves failure from "this request fails now" to "this work happens later." That is an availability win for the producer and a brand-new stateful system you now own. Three decisions set the HA/DR design: is the queue authoritative (the only copy of the work) or a buffer in front of a system of record; what is the acknowledgement and replication contract, because that is your RPO; and can the backlog be drained inside the business deadline after an outage, because that is your RTO. Get the third wrong and a 4-hour outage becomes a 16-hour one.

Replication is the availability/data-loss dial. In Kafka, acks=all with min.insync.replicas=2 and replication.factor=3 gives RPO 0 for acknowledged writes inside the cluster, at the cost of the producer blocking when the ISR drops below 2. Leaving unclean.leader.election.enable=false (the default) means you choose unavailability over silent data loss: that is the whole trade. RabbitMQ quorum queues make the same choice via Raft: a minority partition stops accepting publishes rather than diverge. SQS has no native cross-region replication, so a multi-region design means dual-write or EventBridge fan-out you build and test yourself.

TopologyRPO for acked workBehaviour on regional loss
Kafka RF=3, acks=all, min.insync.replicas=20 in-clusterProducer blocks if ISR < 2
Kafka + MirrorMaker 2, async= replication lag (sub-second to seconds)Consumers fail over after offset translation
RabbitMQ quorum queue, 3 nodes0 for confirmed publishesMinority partition refuses publishes
SQS standard0 in-regionNo cross-region replication; app-level fan-out

Drain arithmetic decides RTO. Producers at 12,000 msg/s, a 4-hour outage, 1 KB messages:

backlog      = 12,000 * 14,400 s        = 172.8M messages
storage      = 172.8M * 1 KB * RF 3     = 518 GB
net drain    = 15,000 - 12,000          = 3,000/s  -> 57,600 s = 16 h  (misses RTO)
scaled       = 40,000 - 12,000          = 28,000/s -> 6,171 s  = 103 min

That last line only works if the topic has at least 40 partitions: consumer parallelism is capped by partition count, so partition sizing is a DR decision, not a throughput afterthought. Kafka's default log.retention.hours=168 (7 days) covers this backlog; a 3-day retention would delete messages before they were ever consumed.

Failure modes and how you see them.

  • Poison message with no DLQ. SQS redelivers forever without maxReceiveCount; the consumer burns CPU on one bad payload. Detect: ApproximateReceiveCount climbing on the same MessageId, and alert on DLQ ApproximateNumberOfMessagesVisible > 0.
  • Lag growth. kafka-consumer-groups.sh --describe LAG column; alert when lag exceeds 15 minutes of production rate: at 12,000 msg/s that is 10.8M messages behind, roughly 11 GB.
  • Rebalance storm. A consumer exceeding max.poll.interval.ms (default 300,000 ms) is evicted, partitions reassign, and the group makes no progress. Detect: rebalance rate and repeated "member has left the group" lines.
  • Unclean leader election. If someone flips it on for availability, RPO becomes unbounded: committed messages can vanish. Detect: the controller's unclean-election log line; alert on it as a data-loss event, not a warning.
  • Retention shorter than the outage. Backlog age approaching log.retention.hours means data is deleted unconsumed. Detect: max message age per partition versus retention.

DR topology choice. If the queue is authoritative, fail it over and accept the replication-lag RPO. If it is a buffer, replay from the system of record instead: cheaper, but only valid when the producer can regenerate the work. Write down which one you picked, because the runbook differs completely: failover means promoting a replica and re-pointing consumers; replay means draining and re-producing, which doubles the load on the downstream service you were protecting.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-3

Design a multi-zone highly available web service.

Answer

Clarify first, then answer. I'd ask: how many AZs, what's peak RPS, what's the availability SLO, and is there session or durable state? Assume 3 AZs in one region, 60k RPS peak, p99 300 ms, 99.95% monthly, sessions in Redis, durable data in Postgres, deploys daily. Then the answer is: N+1 capacity per zone, health checks that test real dependencies, state in zone-resilient stores with stated RPO/RTO, bounded retries with jitter, and progressive rollout.

Capacity is arithmetic, not a slogan. Size each zone so that after losing one, the survivors still carry peak with headroom. 3 zones × 36k RPS = 108k; lose one → 72k = 1.2× peak. Sizing each zone at exactly peak/2 (30k) leaves 60k = 100% with zero headroom, and the first retry burst tips it over. So each zone runs at ~60% of its own capacity at peak.

Routing. ALB with cross-zone load balancing on, health check on /healthz that pings the DB pool and Redis, not just process liveness. Liveness restarts a process; readiness removes it from rotation. Deregistration delay 30 s so in-flight requests drain. Readiness failing on a dependency is what stops a zone with a dead DB from taking traffic.

State.

statestoreconsistencyRPO / RTO
sessionElastiCache Redis, multi-AZ, AOF everysecasync replica≤1 s of sessions lost, failover ~30–60 s
durableAurora PostgreSQL, 3 AZ, 4/6 quorum writesync commitRPO 0 for committed writes, RTO ~30 s
cacheper-zone Redis, no cross-zoneeventualcold start, no data loss

The trade-off: synchronous cross-AZ commit adds ~1–2 ms per write versus async replication's seconds of RPO. For durable data I take the latency; for sessions I take the async replica and accept losing the last second.

Failure mode 1: retry storm. 10k clients, 1 s backoff, no jitter: all 10k retries land at t=1 s, the downstream sees a spike equal to the original load, and it fails again. Full jitter spreads retries uniformly over [0, 1 s], so the instantaneous retry rate is flat instead of a spike. Detection: retries_total counter and 5xx rate climbing together. Cap retries at 3 with a 2 s budget.

Failure mode 2: AZ loss. The Aurora writer is in the lost AZ; failover takes ~30 s, connections drop, and the pool must reconnect. Detection: ALB target health plus AZ-scoped 5xx. Cost: ~30 s of elevated errors, so retries must be idempotent (idempotency keys on writes) or you double-charge.

Rollout. 10% → 50% → 100% across zones, 10 min bake each, auto-rollback if p99 > 400 ms or 5xx > 1%. Game days kill one AZ and verify the 72k RPS headroom, the 30 s failover, and that no committed write is lost.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-7

How would you choose among backup/restore, pilot light, warm standby, and active-active?

Answer

Core answer

The tier is an output, not an input. I get two numbers per service, RTO and RPO, plus the budget, then pick the cheapest tier that meets both. The mapping is tight enough that the numbers usually decide it before cost enters:

TierRPORTOWhat runs in the DR region
Backup/restorehours (age of last backup)4–24 hnothing
Pilot lightseconds–minutes (replication lag)30–120 mindata replication + IaC/AMIs
Warm standbyseconds5–30 minfull stack, scaled to ~30–50%
Active-active~0~0full stack, both regions serving

Those ranges are typical, not guarantees. The point is that a 15-minute RTO rules out backup/restore before you look at the bill.

Why each tier behaves the way it does

Backup/restore is slow for a mechanical reason: an EBS snapshot restore lazy-loads blocks from S3 on first touch, so reading a 2 TB volume sequentially at ~200 MB/s is ~10,000 s ≈ 2.8 h before WAL replay and instance provisioning. (Illustrative arithmetic.) That is why "restore in 15 minutes" is fiction at that size, and why RDS PITR creates a new instance with a new endpoint: app config has to change too.

Pilot light is cheap because only data moves. Async replication gives RPO = replication lag: single-digit seconds at steady state, minutes under a write burst. Nothing else is warm, so RTO is dominated by booting compute from AMIs/IaC.

Warm standby pays roughly 30–50% of prod cost to keep the stack running, so failover is a scale-up plus a traffic shift rather than a cold start.

Active-active is the only tier with RPO ≈ 0, and it buys that with conflict resolution. DynamoDB global tables resolve concurrent writes last-writer-wins, so a lost update is silent: you need application-level versioning or CRDTs if that matters.

Failure modes and how I'd catch them

  • Backup/restore: the backup job fails quietly. Alarm on last-successful-snapshot age and restore into a scratch account monthly. Note that RDS automated-backup retention of 0 disables PITR entirely.
  • Pilot light: replication lag spikes under load and RPO degrades silently. Alert on AuroraReplicaLag above 60 s. Second failure: the AMI/IaC has drifted and the pilot light won't boot. Only a drill finds that.
  • Warm standby: DNS failover is not the RTO. Clients cache the answer (JVMs honour networkaddress.cache.ttl, frequently set to cache indefinitely) so traffic keeps hitting the dead region. Measure client-side cutover, not Route 53 health-check state.
  • Active-active: split brain during a partition, with both sides accepting writes. Detect with write-conflict counters and per-region write rates; reconcile with version vectors.

Two things that kill a plan regardless of tier

KMS keys are regional. An encrypted snapshot cannot be restored into the DR region without re-encrypting under a key that exists there, so that key has to be provisioned before the incident, not during it. And if IAM, DNS or your control plane lives only in the primary region, you cannot fail over at all: the tier you picked never gets a chance to run.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-6

Design a backup strategy that can survive logical corruption or ransomware.

Answer

Core answer (first 90 seconds)

Assume tier-1 RPO of 15 minutes and RTO of 4 hours, and that the threat is an attacker or a bug holding valid production credentials. Three properties have to hold at once:

  1. Recovery points are immutable for longer than the attacker's dwell time.
  2. The backup plane is a separate trust domain: different account, different credentials, no path back into production.
  3. Restores are proven, not assumed.

Concretely: production writes to a bucket in account A; a backup job in account B (no trust relationship back to A) copies versioned objects into a bucket with S3 Object Lock in compliance mode, default retention 35 days. Compliance mode means no principal, including the root user of account B, can delete or overwrite a locked version before its retention date. An SCP on account A denies s3:DeleteObject, s3:PutBucketPolicy and backup:DeleteRecoveryPoint, so a compromised production role cannot reach the vault at all.

Why it works

Ransomware has to destroy the recovery points to force payment. Immutability removes that capability: the attacker's credentials live in account A, the objects are locked in account B, and compliance mode has no bypass. Versioning alone does not achieve this: a role with s3:DeleteObjectVersion deletes every version. Object Lock requires versioning enabled at bucket creation, so this is a design-time decision, not a toggle you add after an incident.

Retention must exceed dwell time. If attackers sit for 20 days before encrypting and you keep 7, every surviving recovery point is already inside the compromise. 35 days gives margin; the cost is that you cannot delete that data for 35 days.

Failure modes

  • Backup credentials compromised. The attacker authenticates to account B directly. Detect with CloudTrail in the vault account alerting on DeleteObject, DeleteBackupVault and PutBucketPolicy; require MFA for delete and keep the vault account's root credentials offline.
  • Retention shorter than dwell time. Silent until restore day. Detect by comparing retention against observed dwell time and by a monthly restore of the oldest retained point.
  • Restore passes integrity but fails application validation. Checksums match, but the backup omitted the schema migration, the KMS key or the external secret store, so the app will not start. Detect with an automated restore into an isolated account plus an application smoke test, not a checksum alone.
  • Silent logical corruption. Bad writes are faithfully backed up for weeks. Detect by restoring to a point before the suspected corruption and diffing row counts and checksums.
  • Cost. Immutable storage plus cross-region replication roughly doubles storage; 100 TB retained 90 days is a real line item, so tier retention by dataset instead of applying 90 days everywhere.

Trade-offs and what changes the decision

Compliance mode versus governance mode: compliance cannot be bypassed by anyone, which is what you want against ransomware, but it blocks GDPR erasure and legal-hold release. If you have deletion obligations, use governance mode with s3:BypassGovernanceRetention restricted to a break-glass role, or set retention short enough to satisfy them. Legal holds have no expiry and override retention deletion, so a hold can keep data past your retention policy. Cross-region replication buys region-loss recovery at the cost of double storage and replication lag.

Arithmetic for RTO: 10 TB at 1 GB/s is about 2.8 hours of transfer, so a 4-hour RTO leaves little headroom once restore validation is added. That number, not the backup schedule, usually decides the design.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-25

How do you verify that backups and replicas are actually restorable and complete, rather than merely reporting success?

Answer

Backup success is a claim about the job, not about the data. I verify in three layers (metadata, byte-level integrity, and application-level semantics) and I do it on a schedule that matches the RPO, not once a year.

First, metadata. The backup catalog must show a complete chain: full plus every incremental, with no gaps, and the newest restore point must be within RPO. For replicas, I check replication slot lag and that the replica has applied every table and schema change. A replica that reports "streaming" but is missing a table because of a replication filter is not a replica.

Second, byte-level. Restore into an isolated account and VPC, then verify checksums. For Postgres, pg_verifybackup on the base backup plus WAL replay to the target LSN; for MySQL, mysqlcheck and CHECKSUM TABLE; for object stores, compare ETag or checksum on a sample of objects. For EBS snapshots, mount and run fsck or compare block checksums. This catches truncated files, zero-byte backups, and bit rot.

Third, application-level. Run domain invariants: row counts per table, foreign key checks, and a few business queries. A backup can be byte-perfect and still be useless if it is crash-consistent but the application needs a consistent point across two databases. So I verify cross-store consistency: orders and payments restored to the same logical timestamp.

Worked trace. A nightly RDS snapshot reports success. Restore into a scratch account takes 42 minutes. pg_verifybackup passes. Row count on orders is 12,847,203 versus source 12,847,203. But payments is 12,847,190: 13 rows behind. The snapshot was taken at 02:00; payments replication lag was 13 seconds at that moment. RPO is 5 minutes, so this passes RPO, but the invariant "every order has a payment" fails for 13 orders. That is a partial restore, not a complete one. Fix: use a coordinated snapshot or restore both stores to the same LSN.

For replicas, I promote one in a game day and run the same validation. I also compare checksums against the primary using pt-table-checksum or pg_checksums. Even if the replica is only for read scaling, I verify it can be promoted, because that is the DR claim.

Failure modes I have seen: KMS key deleted or key policy changed so restore fails at decrypt time; backup vault policy denies the restore role; cross-region copy silently stopped after a permission change; incremental chain broken by a missed backup window; object lock retention expired and ransomware deleted the backup. Each is detected by a restore test, not by a job status.

Metrics: restore success rate, restore duration p99 versus RTO, checksum mismatch count, backup age p99 versus RPO, replica lag p99. Alert on backup age, not on job exit code.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-21

How do you keep a passive recovery environment from drifting?

Answer

Assume passive recovery means a pilot-light or warm standby that does not take production traffic. Drift is the default because DR is not on the hot path: nothing breaks when it diverges, so it diverges. The core answer: make DR a build artifact of the same pipeline, with a small, versioned set of site-specific values, and gate every production change on a DR apply. Then verify by exercising the DR path, not by reading config.

Why it drifts: manual hotfixes to primary that never get backported; site-specific values (CIDRs, endpoints, capacity, licenses) edited by hand; data and dependency rot (schema, secrets, certs, IAM, quotas, AMIs, package versions); untested restores; time-based decay (cert expiry, token rotation). Each has a control that catches it.

Drift classWhy it happensControlDetection signalCost if missed
Code/configHotfix on primarySame IaC modules + image digests; site values in per-site parameter fileHourly terraform plan against DR must be emptyDeploy blocked or DR runs old code
Secrets/certsRotated in primary onlyExpiry check at 30/14/7 days; rotate DR firstAlert on <14 daysFailover fails at 2am
Data/schemaMigration applied to primary onlyNightly restore of prod snapshot into DR + smoke suiteRestore smoke failsRTO blown
Quota/accessDR region quota lowerCompare IAM policies and service quotasDelta alertCannot scale on failover
Traffic pathDR never exercisedSynthetic transaction every 15 min; quarterly 1% read shift for 30 minp99 > 2x primary or error rate > 0.1%Failover works in theory only

How same-release DR updates work: a production change is a PR that touches the shared module and the primary site file. CI runs plan against both sites; the release is blocked if the DR plan is non-empty or if the DR apply fails. That catches the hotfix case immediately. Cost: every deploy pays the DR apply. For example, if primary deploys 20x/day and DR apply adds 4 min, that is 80 min/day of pipeline time and a larger blast radius if the DR apply is flaky. Trade-off: if DR is cold/pilot-light with a 24h RTO, a nightly reconciliation may be enough; you accept up to 24h drift and pay with longer RTO. Warm standby costs more but drifts less because it runs the same stack. Accept-some-drift wins when rebuild-from-IaC is fast and the business can tolerate hours, not minutes.

Failure modes to name: (1) manual hotfix not backported -> hourly plan diff or synthetic transaction fails after deploy; cost: blocked deploy or broken DR. (2) secret expiry in DR only -> expiry check; cost: failover incident. (3) restore rot -> nightly restore smoke; cost: RTO miss. (4) quota drift -> quota check; cost: cannot scale. (5) same-release DR updates slow primary deploys -> pipeline time; trade-off.

Arithmetic: if RTO objective is 1h and nightly restore takes 4h, you have a finding, not a pass. If you run DR apply on every deploy at 4 min and 20 deploys/day, that is 80 min/day; if you move to nightly reconciliation, you save that but accept up to 24h drift. The decision is RTO/RPO vs cost.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-19

What is the cloud provider versus customer responsibility for reliability?

Answer

The split is by layer, not by service.

What a strong candidate says in the first two minutes: the provider owns the physical plant, the hypervisor and network fabric, and the documented redundancy of the managed service as you configured it. You own the configuration, the architecture above the service boundary, and the business continuity target. The provider's SLA is a refund contract: it pays service credits, it does not keep you up. AWS frames this as security of the cloud versus in the cloud; Azure publishes the same split; Google Cloud calls its version shared fate, which is the same idea with a stronger promise to tell you when you're misconfigured.

What the commitments actually cover

LayerOwnerCommitment
Datacenter, hardware, network fabricProviderNot separately SLA'd; rolled into service SLAs
Managed service control planeProviderRDS Multi-AZ 99.95% monthly; EC2 in a region 99.99%, single-AZ 99.5%
Region/AZ placement, replica countCustomerSLA applies only to the documented configuration
Retries, timeouts, degradationCustomerNo SLA
RTO/RPO, restore, DR drillsCustomerNo SLA

S3 Standard is the clean illustration: 99.999999999% (11 nines) of durability is a provider property, but the availability SLA is 99.9% monthly and covers only the standard storage class in a supported region. Durability is not availability, and neither is your application's uptime. Azure makes the same distinction explicit: a VM SLA of 99.99% applies only when you deploy two or more VMs across availability zones; a single VM with Premium SSD is 99.9%.

The arithmetic that decides architecture

SLAs compose in series, so they multiply. A 99.9% service calling a 99.9% dependency gives 0.999 × 0.999 = 99.8%: about 86 minutes of allowed downtime a month instead of 43. Add a third and you're at 99.7%. This is why "we're multi-AZ" is not an answer: if your app runs on one zonal instance, you bought the 99.5% tier, not the 99.99% one, whatever the region offers.

Trade-offs

  • Managed multi-AZ versus self-managed replication: RDS Multi-AZ failover is documented at typically 60–120 seconds and you don't operate it. Self-managed replication can fail over faster, but you own split-brain handling and the drill.
  • Regional versus zonal managed control planes: a regional GKE cluster carries a 99.95% control-plane SLA, a zonal one 99.5%. The cost gap is small; the failure-domain gap is not.
  • Multi-region active-active versus pilot light: active-active roughly doubles steady-state compute and forces you to solve write conflict; pilot light is closer to 1.1x but has a real RTO you must measure. Pick active-active only when the RTO pilot light actually achieves is worse than the business can tolerate.

Failure modes and how you'd see them

  • Single-AZ deployment behind a multi-AZ SLA. Detection: read the SLA's scope clause, if it names a multi-AZ deployment, your single-AZ stack is outside it.
  • Control plane down, data plane up. AWS's November 2020 us-east-1 Kinesis event is the canonical case: existing streams kept serving while the control plane was impaired. Detection: a game day that denies control-plane API calls and checks whether the workload still serves.
  • Retry storm. Clients retrying without jitter turn a two-second blip into sustained overload. Detection: retry rate and queue depth as first-class metrics, not just error rate.
  • Untested restore. RPO is a claim until you've timed a restore. Detection: a scheduled restore drill with wall-clock measured against the stated RPO.

The provider's job ends at the service boundary it documents. Everything that makes your product survive is on your side of it.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-18

How do you size capacity for failure and recovery scenarios?

Answer

Core answer

First I pin down three things: the degraded-mode SLO (what fraction of peak we must serve while a domain is down), the largest failure domain we plan to lose (one AZ, one region, one primary), and whether recovery work runs concurrently with serving traffic. Then I size for peak + loss of that domain + recovery load, and I check the shared stateful tier last, because that is usually the binding constraint, not compute.

The arithmetic

Hypothetical but representative: 12,000 rps peak, each pod sustains 400 rps at p99 < 200 ms, so 30 pods. Spread across three AZs that is 10 each. Lose one AZ and 20 pods carry 8,000 rps. If the degraded SLO is 60% of peak (7,200 rps) we pass with 800 rps (10%) headroom.

That headroom disappears once recovery work starts. The lost AZ served a slice of the key space; surviving pods have cold caches for it. If hit ratio drops from 95% to 70%, DB reads go from 400 rps to 2,400 rps. On a database sized for 3,000 rps reads that is 80% utilization: survivable. On one sized for 2,000 rps it saturates and "degraded" becomes an outage.

Why autoscaling delay forces headroom

HPA's default sync period is 15 s and its scale-down stabilization window is 300 s, so it reacts to load quickly. The slow part is nodes. Cluster autoscaler notices pending pods in about 10 s, but a new node takes 45-90 s to join and another 20-60 s to pull a large image. A 3x surge therefore takes two to three minutes to absorb. If traffic can triple faster than that (a retry storm, a cache flush, a launch spike) you cannot rely on scale-on-failure; you need pre-provisioned headroom or a load-shedding policy.

Replication catch-up bounds recovery

If the primary fails with 2 s of replication lag at 5,000 writes/s, up to 10,000 writes are at risk: that is your RPO. RTO is failover time plus the time for the new primary to accept writes plus the time for the old primary to rejoin and catch up. If catch-up runs at 20 MB/s and the backlog is 4 GB, that is 200 s during which the replica is not a failover candidate, so you run with reduced redundancy for over three minutes.

Trade-offs

OptionCost vs steady stateSurvivesBounded by
N+1 across 3 AZs1.5xone AZ losscold-cache DB load
N+22xtwo simultaneous domain lossessame, plus quota
Hot standbyfull duplicateprimary lossreplication lag
Scale-on-failure~1x idlenothing until it finishesprovisioning + image pull + quota

I pick based on how fast the failure arrives versus how fast I can add capacity.

Failure modes I have seen

  • Quota exhaustion: scale-on-failure hits the vCPU quota; symptom is pods stuck Pending; detect via cluster-autoscaler "not enough quota" events.
  • Cold-cache stampede: DB connection pool wait climbs; detect via pool wait time and read latency.
  • Retry storm during recovery: a second outage while recovering; detect via client retry rate and 5xx.
  • Replication lag growth: detect via pg_stat_replication lag; if it grows during recovery, you are one failure from data loss.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-11

How do you determine and enforce service dependency ordering during full-region disaster recovery failover?

Answer

Determining dependency order requires building a directed acyclic graph (DAG) of recovery tiers, mapped downward to root infrastructure. Enforcing that order during a live failover requires asynchronous readiness barriers rather than fixed time sleeps, bringing systems up in tiered waves and blocking traffic admission until underlying dependencies emit semantic readiness signals.

Dependency Discovery and DAG Construction

I segment services into recovery tiers based on upstream impact. Circular runtime dependencies (e.g., Auth service logging to a Kafka broker that validates tokens via Auth) must be decoupled for boot: Auth must boot against local or cached state, or Kafka must permit bootstrap clients without cross-service authentication checks.

Tier 0 (Foundations)  -->  Tier 1 (State & Data)  -->  Tier 2 (Core Business)  -->  Tier 3 (Edge / Ingress)
- Regional VPC/DNS       - Database Replica Prom.    - User / Auth Engines        - API Gateways / CDNs
- KMS & Secret Stores    - Object Stores / Caches    - Order Orchestration        - Global DNS Traffic Shift
- Identity (IAM, OIDC)   - Messaging / Queues        - Inventory Processors       - Public Ingress Enabled

Enforcement Mechanism

Static runbooks fail because startup latencies are unpredictable under cloud control-plane throttling. Enforcement must be orchestrated programmatically using stateful execution engines (e.g., AWS Step Functions, Temporal, or Argo Workflows) implementing phased barriers:

  1. Prerequisite Gating: Orchestrator initiates Tier $N$ only when Tier $N-1$ asserts explicit readiness. For instance, Tier 2 compute nodes do not launch until database replication lag drops to zero and promotion to primary completes.
  2. Semantic Health Verification: Compute readiness is not an HTTP 200 ping on /healthz. The health probe must execute a synthetic canary transaction testing state persistence and local dependency connectivity.
  3. Throttling and Circuit Breaking: Downstream tiers boot with cold caches. To prevent an immediate thundering herd from crashing freshly promoted databases, ingress points un-shed traffic gradually using ramped traffic shifting (e.g., 5% -> 25% -> 100% over 10 minutes).
TierTypical ComponentsReadiness Gate ValidationFailure / Abort Criteria
0: FoundationIAM, KMS, Core VPC, Transit GatewaysKMS key rotation check, internal DNS resolution passesSecret decryption failure, control-plane API rate limits
1: StateAurora/RDS Postgres, DynamoDB, KafkaWrite-probe latency < 50ms, replication epoch promoted, zero dual-masterReplication gap exceeds target RPO, read-only replica stuck
2: App LogicWorker pools, ECS/EKS clusters, internal APIsSynthetic read/write RPC to Tier 1 passes; circuit breakers closedCrashLoopBackOff > 5% of fleet, connection pool exhaustion
3: IngressCloudFront, Route 53, Envoy Edge ProxiesTier 2 target group healthy count >= minimum capacity thresholdSynthetic edge checks fail, p99 latency > 2.5s

Worked Failure Mode: Control-Plane Contention

During a region-wide failover, thousands of VMs and DB instances are launched simultaneously. Cloud provider API rate limits (e.g., RequestLimitExceeded on EC2/KMS) trigger exponential backoff. The orchestrator must decouple horizontal scaling: deploy the minimum viable capacity (pilot light) to clear Tier 2 readiness, open Tier 3 ingress at reduced rate limits, and auto-scale worker pools asynchronously to satisfy the RTO.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-14

How would you design and test regional DNS failover?

Answer

Assumptions. Two regions, one authoritative DNS provider (Route 53 here; the mechanics hold for NS1 or Cloudflare), clients are a mix of browsers and long-lived service-to-service connections, and the target is "users recover in a few minutes." If you need sub-second RTO, DNS is the wrong layer: use anycast or a load balancer that ejects unhealthy backends.

Design. Primary/secondary failover records: api.example.com points at the primary region's load balancer, with a Route 53 health check on /healthz using the 10-second fast interval and the default 3-failure threshold. Record TTL is 60 s. Worst-case DNS-side convergence is therefore 30 s detection (10 × 3) + 60 s TTL ≈ 90 s before a TTL-respecting resolver re-queries and gets the secondary. That 90 s is the number I'd defend, and it's optimistic.

Why it's optimistic. DNS failover moves new lookups only. It does not move:

  • Established TCP connections. HTTP keep-alive holds a socket to the dead region's IP until the connection breaks, regardless of DNS.
  • The JVM's DNS cache, governed by networkaddress.cache.ttl, which can hold an address past TTL.
  • Clients that resolve once at startup and pin the address (some gRPC clients, connection pools).
  • Recursive resolvers that clamp or ignore TTL.

So real convergence is detection + TTL + client cache behaviour, and the last term is unbounded unless you own the client. Shrinking TTL doesn't fix it: it just multiplies query load. The fix is client resilience: retry against a second address, short connect timeouts, and connection draining on the primary.

Tradeoffs. Failover routing (primary/secondary) is cheap and simple but has the ~90 s+ convergence and a cold standby. Weighted routing runs active-active and shifts traffic gradually, failing over faster because both regions already serve: at the cost of cross-region data consistency. DNS failover is the wrong tool for a bad deployment (that's health-based ejection at the LB) or for sub-second RTO.

Failure modes and detection.

Failure modeMechanismDetection
Stale cache past TTLresolver or client ignores TTLsynthetic client resolves, then reports which region it lands on after failover
Failover never fires/healthz returns 200 while the app is broken (shallow check)deep check that exercises a dependency; alert on primary health flapping
False failoverWAF/security group blocks health-checker IPs, endpoint looks down everywherealert when health-check status disagrees with real traffic
Split trafficsome clients on old IP, some on newper-region request counts during the drill

Testing. Game day: kill the primary's health endpoint (not the whole region, that's the realistic failure) and measure time to first request served by the secondary, fraction of traffic still on the primary at +1/+5/+10 min, error rate in the window, and whether a long-lived connection survives (it shouldn't). Query from several resolvers (8.8.8.8, 1.1.1.1, an internal one) to watch TTL behaviour diverge. Keep a manual override (flip a weighted record to 0/100) and an out-of-band status page on a different provider, so recovery never depends on the thing that failed.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-8

Design a safe regional failover decision process.

Answer

Assumptions I'd state up front: active-passive, two regions, async streaming replication, RPO target 60 s, RTO target 15 min, DNS steering with a 60 s TTL. If it were active-active with synchronous commit there is no promotion at all: you drain and rebalance, and the whole calculus below changes.

The core answer: failover is a decision, not a script. I gate it on three questions in order: is the failure real and regional, can the standby actually carry the load, is the old writer fenced, and only then does traffic move. Fencing comes before traffic shift, because traffic shift is what creates the second writer.

1. Detection needs two independent vantage points. A monitoring stack inside the failing region reports nothing when the region dies. I use external synthetic checks from three regions (10 s interval, 3 consecutive failures → alert at 30 s) plus a control-plane probe issued from outside the region. Both must agree before anyone calls it regional.

2. Qualify: regional failure or bad deploy? From the edge they look identical. I check whether the control plane responds and whether other services in the region respond. If only my service is down, it's a deploy: roll back, don't fail over.

3. Pre-promotion gates.

gatethresholdwhy it exists
replication lag5-min p99 < 5 sbounds RPO; an instantaneous 0 means nothing
standby capacity≥ 60% headroom at current peakpromotion puts the whole load on one region
certs / DNSvalid ≥ 30 days, records pre-createda failover that breaks TLS is a second outage
cross-region depsall healthypromoting into a broken dependency moves the problem

Measuring lag, not assuming it. On the primary SELECT pg_current_wal_lsn() → 0/3A000000; on the standby SELECT pg_last_wal_replay_lsn() → 0/39F00000. pg_wal_lsn_diff gives 1 MiB. At 8 MiB/s of WAL generation that is 131 ms of lag. I take the 5-minute p99, because the instantaneous value is 0 whenever the primary is idle.

4. Fence before you promote. This is the step people skip. A primary that is partitioned rather than crashed keeps accepting writes, and two writers on the same data is unrecoverable. So revoke the old writer's credentials (IAM role, DB user) or stop the instance via the control plane, and confirm the fence took effect before promotion.

5. Shift progressively. Weighted DNS 10% → 50% → 100% over about 5 minutes, watching p99 latency, 5xx rate, and replication of the new primary. Abort if 5xx exceeds 2% or p99 exceeds 2× baseline for 2 minutes.

Failure modes and how I'd detect them:

  • Split brain. Two writers. Detect with a monotonic lease: the standby refuses to promote without acquiring a lease the old primary must renew every 10 s.
  • Stale promotion. Standby promoted with 40 s of lag loses 40 s of acknowledged writes. Detect by diffing the last-received LSN against the primary's last known LSN before promotion, and log the gap.
  • Thundering herd. Every client reconnects at once. Detect via connection count; mitigate with jittered client backoff.

When failover is the wrong call: if the failure is a shared dependency (DNS, a SaaS provider) promotion just relocates the outage. And if RPO cannot be met on financial data, losing 40 s of writes may be worse than 20 minutes of downtime. That is a business call, made in advance, not at 3 a.m.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-16

How do you prevent a bad deployment from defeating multi-zone redundancy?

Answer

Multi-zone redundancy buys you tolerance of a lost zone. It buys you nothing against a change that is identical in every zone: same image, same ConfigMap, same migration. A bad deploy is a correlated fault, so the unit you have to isolate is the change, not the zone.

Assumptions: a stateless service on Kubernetes (apps/v1 Deployment) across three AZs, one shared database, a flag system, and a load balancer that can split traffic by weight or header.

The answer in one line: never let one artifact, config, or schema change reach all zones in a single step, and make every step abortable on a signal that reflects user-visible behavior.

Mechanism. A Deployment's default RollingUpdate is maxUnavailable: 25%, maxSurge: 25%. It will take down a quarter of your pods across all three zones at once. If the new image is bad, every zone degrades simultaneously and the redundancy you paid for is gone. Progressive delivery inverts that: the first wave is one pod in one zone, and each later wave is gated on a bake period and an abort condition.

Illustrative wave plan (figures are examples; tune to your traffic):

wavescopetrafficbakeabort on
01 pod, 1 zoneinternal only10 minany panic, any 5xx
12 pods, 1 zone1% (header-routed)15 minp99 > 1.5x baseline, error rate > 0.5%
250% of pods, 2 zones25%30 minsynthetic checkout failure, saturation climb
3all zones100%--

Blast radius arithmetic: 3 zones x 20 pods = 60 pods. Wave 1 is 2 pods, so a bad build costs 3.3% of capacity while the other two zones serve full traffic. The default rolling update would have 15 pods down at once, in all three zones.

The failure that actually defeats redundancy is the schema change, because it is the one thing you cannot undo by redeploying. Expand/contract: release 1 adds a nullable column plus code that writes both old and new; release 2 backfills and switches reads; release 3 drops the old column. Ship migration and code in the same wave and a code rollback leaves the schema ahead of the binary, so the old code breaks on the NOT NULL.

Failure modes and how you catch them.

  • Readiness green, users unhappy. /healthz doesn't touch the database. Gate on a synthetic user journey and on business metrics, not pod readiness.
  • Canary traffic isn't what you think. HTTP keep-alive and connection pools pin a few clients to the canary, so "1% of requests" is 1% of requests from three clients. Compare distinct client count, not request count.
  • Autoscaling hides the regression. HPA adds pods to cover slow ones, so error rate stays flat while latency climbs. Abort on saturation per request, not just errors.
  • Config drift per zone. Hash the rendered ConfigMap/Secret per zone and diff before rollout. A deploy that is fine in two zones and wrong in the third is still a correlated change.
  • Client retries amplify. A 1% canary failure with 3 retries becomes a 3% load increase on the remaining zones.

Trade-offs. Canary is cheapest and gives the fastest signal, but needs enough traffic to be statistically meaningful; a service doing 5 rps cannot resolve a 0.5% error rate in 15 minutes. Blue-green gives instant rollback by flipping the router, at the cost of double capacity, and it does nothing for schema. Zonal waves need no traffic-splitting infrastructure and work with DNS or anycast, but a zone is a coarse unit: if one zone is 40% of capacity, your smallest step is 40%. Flags alone are enough when the change is behavior behind a flag with no new binary or migration; they are not enough for a new dependency or a schema change.

The cost is real. Four waves with 15- and 30-minute bakes adds about an hour to every deploy. If that is too slow, shrink the change, not the bake.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-17

How would you design graceful degradation for a dependency outage?

Answer

The 90-second version

Assume the dependency is a remote service (pricing, inventory, payments) that can be slow, erroring, or unreachable, and that "graceful" means every user-visible outcome is one you chose in advance, not a 500. I classify each call site on two axes before picking any mechanism: criticality (can the user finish their goal without this answer?) and consistency (does a stale answer cause a wrong decision, or a financial/security violation?). The classification decides the behavior; the mechanisms are just how you implement it.

classexamplewhen dependency is down
read, staleness-tolerantproduct catalog, recommendationsserve bounded-stale cache
read, must be freshaccount balance, seat availabilityfail fast, explicit "unavailable"
write, must not be lostorder placement, payment capturedurable queue + idempotency key, tell user "accepted, pending"
write, must be synchronousauth, fraud decisionfail closed

Why bounded-stale is safe. The bound is the contract, not a hope. Cache entries are immutable and carry the version they were written at; the serving layer refuses anything older than that class's staleness budget: say 60s for catalog, 0 for balance. A stale read is then a known older state, never a corrupted one. Where read-your-writes matters, the write path returns the new version and the read path pins to it, so the user who just saved sees their own write even while everyone else reads stale.

How the breaker decides. Resilience4j's defaults: count-based sliding window of 100 calls, minimum 100 calls before it can trip, failure-rate threshold 50%, 60s in open, then 10 permitted calls in half-open. Concretely, it takes 51 failures in the last 100 calls to open. The half-open probes are the part that matters: they are the only traffic the sick dependency sees, so a still-broken service gets 10 requests instead of 10,000.

Queue arithmetic, because a buffer is a liability with a deadline. Payments arrive at 200/s peak; the dependency drains at 500/s healthy. Down for 3 minutes: backlog 36,000. Draining at 500/s while 200/s still arrives is 300/s net, so 120s to clear. If the promise is "pending payments settle within 5 minutes," that works. A 30-minute outage gives 360,000 queued and 20 minutes of drain: past the promise, so you need shedding on the enqueue side, not just a bigger queue.

Failure modes and how you see them.

  • Half-open flapping. Ten probes succeed, the breaker closes, real traffic re-kills the dependency. Detect via breaker state transitions per minute; repeated open→closed→open inside a minute means raise the probe count or add a minimum dwell time in closed.
  • Queue saturation. Enqueue starts rejecting. Detect with depth/max-depth ratio and an enqueue-reject counter. Cost is concrete: a user is told "try again" for a payment that would have succeeded.
  • Retry storm. Three bounded retries at 200/s is 600/s into a service already failing. Detect by comparing outbound request rate to inbound; cap retries with a shared budget and jitter, not per-call.
  • Stale cache outliving its budget because the refresh path is down too. Detect with a histogram of served-entry age; alert when p99 age exceeds the class budget.

Timeouts come from the dependency's own p99 plus headroom, and concurrency limits from Little's law, throughput × latency, so a slow dependency can't consume the whole thread pool. Recovery drains the backlog at a rate the dependency can absorb, and the invariant tests cover the one thing degradation must never do: let a stale or queued path violate a security or money invariant.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-20

How would you protect the DR environment from the same security incident as primary?

Answer

Assume primary and DR are in AWS, DR in a different region and account under the same AWS Organizations. The core answer is to make DR a separate security domain: separate AWS account, separate IAM, separate KMS keys, separate backup vault with immutability, and no shared trust. If you can't afford a separate account, at minimum use separate KMS keys and AWS Backup Vault Lock in compliance mode.

Why does the account boundary hold? AWS accounts are the strongest isolation primitive. An SCP attached to the DR account can deny all actions except from a specific break-glass role, and deny any cross-account access from the primary account. Even if an attacker has admin in primary, they cannot assume a role in DR unless the DR account's trust policy allows it. So you must ensure no trust policy in DR references the primary account. Similarly, use separate KMS keys: a key in primary cannot decrypt data in DR because KMS keys are regional and account-scoped. If you use the same key, compromise of that key (or its policy) lets the attacker decrypt DR backups. Use AWS Backup Vault Lock in compliance mode to make backups immutable for a retention period you set from 1 day to 100 years; a common choice is 7 years for regulatory compliance. That prevents even an admin in DR from deleting them.

Trade-offs: The cost is operational: you need to manage two accounts, two sets of IAM, two KMS keys, and you need to test recovery without using daily credentials. That means break-glass credentials stored offline (e.g., in a safe) with MFA, and a quarterly recovery drill. The alternative is to use a single account with separate VPCs and IAM boundaries. That's cheaper and simpler, but a single IAM misconfiguration or a compromised role with cross-VPC permissions can bridge the gap. Another alternative is a separate cloud provider, which gives even stronger isolation but adds significant complexity and cost. The deciding criteria: regulatory requirements (e.g., PCI DSS requires separation of duties), the value of the data, and the cost of a breach. If you can't afford the operational overhead, at least use separate KMS keys and immutable backups.

Failure modes: Shared identity provider. If both primary and DR use the same Okta tenant, compromise of Okta gives the attacker access to both. Detection: monitor for unusual login patterns from new locations, and use separate IdP tenants if possible. Shared KMS key. If you use the same KMS key for primary and DR backups, an attacker with kms:Decrypt in primary can decrypt DR backups. Detection: CloudTrail logs for kms:Decrypt from unexpected principals. Automation with cross-account permissions. If your CI/CD pipeline has a role that can assume into DR to deploy, that role becomes a pivot. Detection: AWS IAM Access Analyzer for external access, and CloudTrail for AssumeRole events. Operational cost: maintaining separate accounts adds about 20-30% overhead in management, but reduces blast radius.

Worked example: table of controls and their effect.

ControlMechanismFailure mode if omittedDetection
Separate AWS account for DRSCP denies all cross-account access from primaryAttacker with primary admin can assume DR roleCloudTrail AssumeRole events, GuardDuty
Separate KMS key for DR backupsKey policy allows only DR account principalsAttacker decrypts DR backups with primary keyCloudTrail kms:Decrypt, Config rules
AWS Backup Vault Lock (compliance mode)Prevents deletion for retention periodAttacker deletes backupsCloudTrail DeleteBackupVault, SNS alerts
Break-glass credentials offlineNo daily use, MFA, stored in safeCredentials stolen from CI/CDCloudTrail console logins, GuardDuty

Trace: An attacker compromises a primary EC2 instance and steals its IAM role credentials. They call sts:AssumeRole to a DR role. If the DR account has no trust policy for the primary account, the call fails with AccessDenied. That's the boundary. If the trust policy exists, the attacker gets DR access. So you must audit trust policies regularly with IAM Access Analyzer.

What would change the decision: If the data is low sensitivity and cost is prohibitive, you might accept the risk and use same account with separate VPCs, but then you must at least use separate KMS keys and immutable backups. If you have regulatory requirements, separate accounts are mandatory.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-24

How do compliance and data residency constrain DR architecture?

Answer

The 90-second answer. Residency rules bind where data may be stored and processed, so DR, which is by definition a second copy somewhere, is a compliance decision before it is an engineering one. My default: keep the recovery site inside the same legal jurisdiction as the primary, and go cross-border only when the data is not restricted or when a transfer mechanism (SCCs plus a Transfer Impact Assessment) is in place and signed off. Assumptions I state up front: the workload holds personal or regulated data, the primary is in the EU, and the business wants a region-failure RTO under an hour.

Why the constraint bites. A DR copy is a transfer. Under GDPR Chapter V, moving personal data to a recovery region outside the EEA is a restricted transfer; since Schrems II (CJEU C-311/18, July 2020) invalidated Privacy Shield, a US recovery region needs SCCs and a documented TIA. Sector and national rules are stricter: India's RBI payment-data localization (2018) requires payment data stored only in India, Russia's 242-FZ requires a domestic copy, and China's PIPL Art. 38-40 gates outbound transfers. That means synchronous cross-region replication, which writes plaintext continuously into the second region, is often simply barred, not merely discouraged.

Options and what they cost.

OptionLegal basisRPO / RTOWhen
Multi-AZ, one regionnone needed~0 / minutesdefault; no region-failure cover
Two regions, same bloc (eu-west-1 + eu-central-1)intra-EEA, no transfer~0 sync / minuteslatency-tolerant; RTT ~20-30 ms
Cross-bloc, encrypted, keys stay homeSCCs + TIAseconds-minutes async / hoursdata not strictly localized
In-jurisdiction backup onlynone1h / 24hregulator won't allow a second live copy

Failure modes and detection.

  1. Silent border crossing. A new region gets added to the account and the DR runbook or a backup policy starts writing there. Detect with policy-as-code: an AWS SCP denying aws:RequestedRegion outside the approved list, or Azure Policy allowed-locations, plus an alert on any cross-region replication target change.
  2. Key custody breaks failover. The KMS key or HSM lives only in the primary region; the DR copy is ciphertext you cannot decrypt. This is the one that passes a checklist and fails a real exercise: the only detection is a DR test that actually restores and decrypts, not one that confirms replication is "green."
  3. Support and telemetry. A third-country support engineer accessing production during an incident is itself a transfer (GDPR Art. 28 processor terms). Detect via audit logs of support sessions and access reviews.
  4. Erasure vs. immutable backups. Art. 17 erasure must reach DR copies; a 35-day immutable backup window cannot honour it. Fix with per-tenant keys and crypto-shredding, or a documented retention exception.

Deciding criteria. First, is the data actually restricted: plenty is not, and that removes the constraint. Second, can the workload tolerate sync latency to a same-bloc region? Third, what will the regulator accept as a documented cross-border DR? If none of the compliant options meet the business RTO, the honest answer is a degraded RTO/RPO with named business sign-off, not a quiet cross-border copy.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-23

How would you recover from regional data corruption rather than infrastructure loss?

Answer

First 90 seconds

Assume the corruption is logical (bad writes, a buggy migration, a malicious actor) not a lost region. The infrastructure is fine; the data is wrong. So the recovery point is a time, not a place.

I fence all writers first: revoke the application's IAM credentials, set the database to read-only, or block port 5432 at the security group. Then I snapshot the corrupt primary's disk and capture its WAL/binlog before anything restarts. That evidence tells me the corruption start time.

Next I pick a recovery point before that start time, restore into an isolated account or VPC with no production network path, validate with domain invariants and external reconciliation, then cut over. Replication resumes only from the clean copy to the new primary: never the reverse.

Choosing the recovery point

The RPO is not the backup interval. It is the gap between the last known-good write and the corruption start, plus detection lag. Example: nightly full backup at 02:00, WAL archived every 5 minutes to S3. Corruption begins at 14:00, detected at 18:00 by a reconciliation job. You restore the 02:00 base and replay WAL to 13:59. RPO = 12 hours of writes lost, not 5 minutes. If you have a logical replication stream or an external event log (Kafka topic with 7-day retention), you can replay those events into the restored database and shrink the loss to the detection window.

SourceRetentionRPO if corruption at 14:00Restore time
Nightly full + 5-min WAL35 days12 h2–4 h for 1 TB
Continuous PITR (e.g., Aurora)35 days5 min15–30 min
Immutable snapshot (S3 Object Lock, compliance mode)90 days24 hhours to a day from Glacier

Validation and cutover

Restore into an isolated account. No production credentials, no VPC peering. Run invariants: SELECT account_id, SUM(amount) FROM ledger GROUP BY account_id must equal SELECT account_id, balance FROM accounts. Check foreign key orphans, row counts per partition, and max timestamp per table. Reconcile against the payment processor's settlement file or the upstream Kafka offsets.

Then decide: serve stale clean data or full outage. If the clean copy is 12 hours old, you can serve read-only and queue writes, but stale reads may show a paid invoice as unpaid. For financial or safety-critical data, mixing clean and corrupt rows is worse than an outage: you must restore the whole dataset or none.

Failure modes

  • Detection lag: corruption found 3 days later. Your "last known good" is now 3 days old. Detection signals: reconciliation job failures, invariant violations, customer reports, sudden row-count divergence between primary and replica.
  • Backup also corrupt: immutability (S3 Object Lock) prevents deletion but not a bad write that was backed up. You need a backup taken before the corruption start.
  • Restore exceeds RTO: a 10 TB restore from Glacier takes hours to a day. Measure this with a game day.
  • Recontamination: application caches, downstream systems, or the old replica rejoin and overwrite the clean copy. Rotate credentials, purge caches, and set replication direction explicitly.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-12

How do you test DR without creating unacceptable production risk?

Answer

First, the assumption I'd state out loud: we have a primary region serving real traffic, a recovery target of something like an hour, and we can't take a customer-visible outage to find out whether that's true. So the question isn't "how realistic can we make the test": it's "what's the smallest test that can falsify the claim we're making." Every rung of the ladder exists to kill one specific claim, and you only climb when the rung below has passed.

rungclaim it falsifiesblast radiuscost
tabletop"we know who decides, and in what order"none~2h, 6 people
single-component restore into an isolated account"the backup restores, and the keys and permissions exist"none1–4h
full stack in an isolated account"dependency order and config are complete"none~1 day
shadow traffic against the recovery stack"it holds at the real request mix and rate"none (reads only)days of setup
production game day with traffic shifted"the control plane and the humans work"partialhours, plus real risk

The order matters because each rung removes a class of doubt cheaply before you spend the expensive one. A tabletop costs six people two hours and finds the decision gaps, who declares, who talks to support, who owns the data-integrity call. Restoring one component into an isolated account finds the things only a real restore finds: the KMS key that isn't shared, the cross-account role that doesn't exist, the backup encrypted with a key that was rotated. Full-stack isolated recovery finds ordering and config. Shadow traffic, replaying production reads against the recovery stack, finds capacity and config drift without touching users. Only the last rung tests the control plane and the humans under real load, and it's the only one you can't fully de-risk.

Here's the arithmetic that makes the point. Say RTO is one hour and the primary database is 2 TB. A snapshot restore at, say, 150 MB/s takes about 3.9 hours: the restore alone blows the target by a factor of four. You want to learn that in an isolated account on a Tuesday, not at 3 a.m. during an incident. That's the whole argument for the ladder: the cheap rungs are where the arithmetic gets checked.

Failure modes I'd watch for, and how each is detected:

  • Restore reports success but the data is stale, because the snapshot schedule was silently disabled months ago. Detect by asserting on the max timestamp in the restored data, not on the restore job's exit code.
  • Cutover works in the test but not in production because clients cache DNS or connection strings past the TTL. Detect by measuring actual connection drain, not by reading the TTL.
  • The game day "passes" because the incident commander made an undocumented manual fix. Detect by requiring the runbook to be the only artefact used, then diffing what was actually done against it.
  • The runbook step references a console path or a person that no longer exists. Detect by having someone who didn't write the runbook execute it.

The trade-off is real and I'd say it plainly: the last rung buys the most assurance and carries the most risk, because the test itself can become the incident. So I'd stop short of production failover when I can't bound the blast radius: a shared control plane, a single global database with no replica, or a payment path where a duplicate charge is worse than an outage. In those cases I'd test recovery into a region we don't serve, accept that the cutover step stays untested, and write that gap down as a known risk with an owner and a date. The deciding criterion is whether a stop condition can actually halt the test before a real user notices; if it can't, the test doesn't run.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-13

Which measurements prove a DR exercise met its goals?

Answer

The measurements that prove a DR exercise met its goals are the achieved RTO and RPO for each critical business function, measured end-to-end from the failure injection to the first successful critical user journey, plus evidence that no data was lost or corrupted beyond the stated RPO. Component readiness, replication lag, and a green standby dashboard are leading indicators, not proof.

I assume the goals are defined per service: for example, a tier-1 payments service might have RTO 15 minutes and RPO 0; an analytics service might have RTO 4 hours and RPO 5 minutes. If the goals aren't defined, the exercise can't prove anything.

I prove RTO by taking the timestamp of the first successful critical journey and subtracting the failure injection timestamp. Not the decision to fail over, not the start of traffic shift. Detection and decision latency are part of recovery. I prove RPO by comparing the last durable transaction on the primary before failure with the first transaction on the recovered system: any gap is data loss; any duplicate is a consistency failure.

Here is a hypothetical trace for a payments service with target RTO 15 minutes, RPO 0:

EventTimestampWhat it proves
Failure injected10:00:00Start of RTO clock
Alert fires10:04:30Detection latency 4m30s
Incident declared10:06:00Decision latency 1m30s
Failover decision10:08:00
Standby infra ready10:12:00
Data recovery complete10:14:00Last primary txn 09:59:58; gap 4m2s
Traffic shift begins10:15:00
First successful payment10:18:30Achieved RTO = 18m30s
Full service10:25:00
Backlog drained10:40:00
Failback11:30:00

Achieved RTO = 10:18:30 - 10:00:00 = 18m30s. Target was 15m, so this exercise fails. Achieved RPO = 4m2s of lost transactions. Target was 0, so it fails. The green standby dashboard at 10:12:00 would have looked fine, but the application couldn't process a payment until 10:18:30.

Failure modes that make an exercise look successful when it isn't:

  • Measuring from the failover decision instead of the failure injection. This hides detection and decision latency. Detection: compare the alert timestamp to the injection timestamp; if the gap is more than a few minutes, your monitoring is too slow.
  • A green standby dashboard that shows replication lag zero but the application can't start because of a missing secret, an unapplied schema migration, or a dependency on a service that wasn't failed over. Detection: run a canary transaction against the standby before shifting traffic.
  • Manual steps not counted in RTO. If an operator manually runs a script to promote the database, that time is part of recovery. Detection: record every manual step with start and end timestamps.
  • Backlog drain not measured. If the queue backs up during the outage, full service isn't restored until the backlog drains. Detection: monitor queue depth until it returns to baseline.

Alternative measurement approaches: component-level checks (e.g., "database is up") are cheap and fast but don't prove the goal. End-to-end business transaction is the only proof but requires test data and may be slow. Deciding criteria: if the goal is contractual or regulatory, you need end-to-end evidence with timestamps and data integrity checks. If it's a tabletop, you can't prove RTO. Synthetic monitoring can be run on standby without affecting users, but may not cover all critical journeys. Real traffic is the ultimate proof but you can't fail over production for a test. Use a canary transaction that mimics the critical journey.

Operator load is a secondary metric: if the exercise required 10 engineers for 2 hours, that's a cost, but it doesn't prove the goal unless the goal includes staffing.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-15

How do you plan safe failback after a regional disaster?

Answer

The 90-second answer

Failback is a second stateful migration, not a return to normal. The recovery region stays authoritative until the original region is rebuilt, patched, capacity-tested, and its dependencies are healthy. The hard part is the delta: every write the recovery region accepted during the incident that the original never saw, plus the tail of writes the original accepted but never replicated before it died. I reverse replication, reconcile that delta deterministically, fence the old writer, then shift traffic progressively with explicit abort criteria.

Mechanism

Assume async replication A→B with an RPO target of 5 minutes. When A fails, B is promoted and becomes the only writer. Two divergent sets now exist:

  • A's unreplicated tail: writes committed on A in the last few seconds that never reached B. If A's storage survived, extract them from the WAL/binlog; if not, they are lost and must be declared.
  • B's incident writes: everything B accepted while authoritative.

To fail back, reverse the stream B→A. A is stale, so bring A to B's state first, then reconcile. Conflict detection needs a per-row version, not a wall clock: last-writer-wins by timestamp breaks under NTP skew (a 100 ms drift flips the winner). Use a monotonic sequence or application version column; where both sides touched the same key, route to a reconciliation queue rather than guessing.

Fencing is not optional. A fenced old primary cannot accept writes: Postgres default_transaction_read_only=on, MySQL SET GLOBAL read_only=ON, or revoke its security group. Without it you get split brain: two writers, divergent rows, and no merge that is safe.

Gate table

GateThresholdAbort if
Replication catch-upreplay lag < 5 s for 10 consecutive minlag grows for 15 min
Delta reconciliation0 unresolved conflictsany conflict unresolved after 2 passes
CapacityA handles 1.5× steady write ratep99 write > 2× baseline
Traffic shift1% → 10% → 50% → 100%, 30 min bake eacherror rate > 0.1% or p99 > 2× baseline

Failure modes

  • Split brain: both regions accept writes. Detect via replication errors or duplicate-key violations on the reverse stream. Cost: manual row-level merge, possible data loss.
  • Catch-up never converges: B's write rate exceeds A's replay rate, backlog grows unbounded. Detect via pg_stat_replication replay_lag. Abort and stay on B.
  • DNS caching: clients keep hitting B after cutover. With a 60 s TTL, up to 60 s of stale routing: keep B writable during that window or you drop writes.

Trade-offs

Progressive shift is right when you cannot validate integrity offline and the workload is stateful. Big-bang cutover is right when the workload is stateless, when B is running at reduced capacity and cost matters, or when the incident ran long enough that B's data is the only truth and A's tail is unrecoverable. Managed options change the calculus: Aurora Global Database advertises sub-second RPO and sub-minute RTO with a managed planned failover, so the reconciliation work shrinks to the application-level conflicts it cannot see. Decide by whether you can prove the delta is reconciled before you move traffic; if you can, big-bang is faster and cheaper.

Curated: · Written: · Reviewed:

Difficulty: Hard