Redundancy, Failover, and Disaster Recovery: From Availability Numbers to Restore Drills
System Design series · Part 6 Reliability (1 of 5)
- Redundancy, Failover, and Disaster Recovery: From Availability Numbers to Restore Drills
- Timeouts, Retries, Backoff, and Jitter: How Retries Save a System, and How They Bring It Down
- Circuit Breakers and Bulkheads: Keep One Broken Downstream from Taking Down the Whole System
- Rate Limiting: Algorithms, Distributed Rate Limiting, and How It Differs from Load Shedding
- Observability: Metrics, Logs, Traces, and SLOs, from 'It Seems Slow' to Finding the Cause
System Design series Part 6-1 | Previous: Real-Time Updates | Next: Timeouts, Retries, Backoff, and Jitter | Series map
Read first: Part 2-2 Load Balancing in Depth, Part 4-7 Distributed Locks and Fencing Tokens, Part 5-4 Idempotency and Idempotency Keys.
Scenario and problem
Here is how the talk platform is deployed today: one data center (one availability zone, AZ) holds 4 application servers, 1 MySQL primary plus 1 replica, and 1 Redis server. Which of these four events would take the platform down?
- The disk in one application server fails
- The whole availability zone loses power
- An engineer runs
DELETE FROM registrationwithout aWHEREin production - An attacker takes over an admin account, encrypts the database, and deletes the backups
Event 1 is solved by the load balancer sending traffic to the other 3 servers (the Load Balancing post). Event 2 makes everything disappear at once. Events 3 and 4 are worse: the machines are all fine, but the data is wrong, and the replica faithfully copied the same mistake within a few milliseconds.
- One disk failsThe disk in one application server fails. The load balancer sends traffic to the other 3, and users barely notice.
- The whole AZ loses powerEvery machine is in the same availability zone. When the power goes out, the application servers, the primary, the replica, and Redis all disappear at once, and nothing is left to take over.
- A DELETE without WHEREAn engineer runs DELETE FROM registration without a WHERE in production. The machines are all fine, but the data is wrong, and the replica faithfully copies the same mistake within a few milliseconds.
- DB encrypted, backups deletedAn attacker takes over an admin account, encrypts the database, and deletes the backups too. None of the availability tools help here; only a backup the attacker cannot reach can save you.
The first two are availability problems, solved with redundancy and failover. The last two are data correctness problems, and only backups can save you. This post treats the two separately.
The simplest approach and its limits
- Back up the database once a night, to another disk on the same machine: you can lose up to 24 hours of sign-up data; when the machine or the data center fails, the backup goes with it; and nobody has ever tried to find out how long a restore takes
- Run more machines: if they all sit in the same availability zone, use the same configuration, and ship in the same deploy, they fail together for the same reason
Redundancy only works when failures are independent of each other.
Core mechanism
The numbers behind availability
| Availability | Downtime per year | Downtime per month |
|---|---|---|
| 99% | 3.65 days | 7.3 hours |
| 99.9% | 8.76 hours | 43.8 minutes |
| 99.95% | 4.38 hours | 21.9 minutes |
| 99.99% | 52.6 minutes | 4.38 minutes |
| 99.999% | 5.26 minutes | 26.3 seconds |
For components in series, multiply their availabilities. A sign-up request passes through the load balancer (99.99%), an application server (99.9%), MySQL (99.95%), and Redis (99.9%) in turn:
0.9999 × 0.999 × 0.9995 × 0.999 ≈ 99.74%, about 22.8 hours of downtime a year, worse than any single component. Every extra dependency that “must be up” makes the whole worse.
For components in parallel, multiply their chances of being unavailable. Two servers at 99% each back each other up, so the chance that both fail at once is 1% × 1% = 0.01%, an availability of 99.99%. But this calculation assumes the two fail independently. A power outage in the same availability zone, the same bad deploy, or the same expired certificate takes both down at once, and the benefit of running them in parallel is gone. So redundancy is not about “how many”, but about “whether they are spread across different failure domains”: different availability zones, different deploy batches, different times for config changes.
Stateless services: N+1 and static stability
Application servers are stateless (the Stateless Services post), so redundancy just means running a few more and spreading them across several availability zones. The key is capacity: the peak needs 6 servers, spread over 3 availability zones, 2 per zone. If one zone fails, the remaining 4 cannot handle the peak.
To survive the loss of one availability zone, each zone must be able to carry 1/(k−1) of the peak traffic, where k is the number of availability zones:
| Availability zones | Capacity per zone | Total capacity (relative to peak) |
|---|---|---|
| 2 | 100% | 2x |
| 3 | 50% | 1.5x |
| 4 | 33% | 1.33x |
“Scale out automatically when something breaks” sounds cheaper, but during a failure the scaling itself may sit inside the failure domain: the management console slows down, and everyone in the same region is fighting for machines. AWS calls this static stability: the system keeps running through a failure without having to change anything, because the capacity is ready in advance.
Stateful services: who takes over
Database redundancy is harder, because there can be only one “correct” version of the data:
| Form | How | Cost |
|---|---|---|
| Active-passive (primary-replica) | One primary accepts writes, and a replica is ready to take over at any time | Asynchronous replication can lose data during the switch (the Replication post) |
| Consensus cluster | A write counts only when a majority of nodes confirm it; when the leader dies, a new one is elected automatically (the Raft post) | One extra network round trip per write |
| Active-active (multi-primary) | Every location accepts writes | Conflicts have to be resolved, for example last writer wins, which can silently lose data (the CAP post) |
The “temperature” of the standby node decides how fast it can take over: a hot standby syncs continuously and can take over at any moment; a warm standby has the data but runs at a smaller scale, so it has to scale up before it takes over; a cold standby has only backups and has to be built from scratch.
The four steps of failover
flowchart LR
D[Detect<br/>3 missed heartbeats in a row] --> J[Decide<br/>switch only with a majority]
J --> P[Promote<br/>pick the most up-to-date replica]
P --> R[Redirect<br/>DNS, VIP, or proxy]
R --> C[Clients reconnect<br/>pool retires old connections]
Detect: how long without a response counts as a failure? Too sensitive, and a brief network blip triggers a switch, where the outage caused by the switch itself is bigger than the original problem; too slow, and the downtime grows. A common approach is to declare a failure only after several heartbeats in a row fail.
Decide: who has the authority to declare the primary dead? If there is only one monitoring process and the network between it and the primary breaks, it wrongly concludes the primary is dead and promotes the replica. Now both servers think they are the primary and each accepts writes. This is split brain. Ways to avoid it:
- Let a majority-vote cluster decide (etcd, Raft, MySQL Group Replication)
- Before promoting a new primary, fence off the old one first: set it to
super_read_only, take it off the network, or revoke its write permission. It is the same idea as fencing in the Distributed Locks post: you cannot simply trust that “the old one should have stopped by now”
Promote: pick the replica with the most recent data. With asynchronous replication, transactions on the primary that had not been sent out yet are lost.
Redirect: get clients connected to the new primary. DNS has to wait for the TTL to expire, and clients and the JVM cache DNS as well; a VIP or a database proxy switches faster, but adds another component. Finally, the old connections in the connection pool are still connected to the old primary and have to be retired.
The four steps added together are the downtime users experience. For managed MySQL (for example Amazon RDS Multi-AZ), the official documentation gives a typical failover time of 60 to 120 seconds, and that does not include the time the application side needs to retire its connections.
Failing back should not happen automatically. When the old primary recovers, its binlog may hold transactions the new primary does not have, and plugging it straight back in leaves the data inconsistent. Compare and resolve them first, then rebuild it as a replica.
Replication is not a backup
Back to event 3. DELETE FROM registration runs on the primary, and a few milliseconds later on every replica. Failover cannot help at all, because every copy is wrong.
- Delayed replication: make one replica deliberately apply changes an hour late. When you find the mistake, that replica still holds the data from an hour ago, so you can stop replication and pull the data out
- Point-in-time recovery (PITR): a full backup plus the binlog after it. Restore the latest full backup first, then replay the binlog up to the moment just before the mistake
- The 3-2-1 rule: at least 3 copies of the data, on 2 different kinds of storage media, with 1 kept off-site
A backup you have never restored is no backup at all. You only know how long a restore takes by actually doing one. A rough estimate: a 500 GB physical backup copied at 200 MB per second takes 2,500 seconds, about 42 minutes, just to move the data, not counting binlog replay. With a logical backup such as mysqldump, the restore has to rebuild every index, which takes much longer.
RPO and RTO
- RPO (Recovery Point Objective): how much data, measured in time, you can afford to lose at most. With asynchronous replication the RPO is the replication lag; with one backup a day it is 24 hours
- RTO (Recovery Time Objective): how long you can afford to be down at most
Both numbers are set by the business, and different data can have different targets:
| Data | RPO | RTO | Reason |
|---|---|---|---|
| Payment records | 0 (lost records can be recovered by reconciling with the payment provider) | 1 hour | Money cannot be wrong |
| Sign-up lists | 1 minute | 15 minutes | Must be searchable on the day of the talk |
| Recommendations, caches | Not needed | Not needed | Can be regenerated from the source data |
Synchronous replication across regions is usually impractical: a network round trip from Taipei to Tokyo takes a few tens of milliseconds, and every write has to wait that much longer. So cross-region redundancy is almost always asynchronous, with an RPO greater than 0.
Blast radius and common-mode failures
Redundancy protects you against “one machine breaks”, not against “every copy breaks for the same reason”:
- One bad config change pushed to every machine at once
- A code bug that triggers on a particular date or input, so every copy crashes at the same time
- An expired certificate, so every service loses its connections at once
The countermeasure is to limit the blast radius: roll out deploys and config changes in batches, pushing to one availability zone first and watching it for a while before moving on to the next; split the system into independent units (cells), so that a problem in one cell does not affect the others.
Drills
Failover code does not run in normal operation, so it almost certainly has bugs. Regularly, during off-peak hours, actually switch the primary once, shut down an availability zone, and restore from a backup, recording how long each step really takes. Only then do you know whether your RTO is really achievable.
Comparing options
The four strategies below are the ones the AWS disaster recovery whitepaper describes; RPO and RTO are rough orders of magnitude:
| Strategy | Normal state | RPO | RTO | Cost |
|---|---|---|---|---|
| Backup and restore | Only backups off-site | Hours | Hours to days | Low |
| Pilot light | A continuously replicated database off-site; application servers normally off | Minutes | Tens of minutes | Medium-low |
| Warm standby | A scaled-down full environment off-site | Seconds to minutes | Minutes | Medium-high |
| Multi-site active-active | Several sites serve at the same time | Near 0 | Near 0 | High, plus write conflicts to handle |
The talk platform’s choice: deploy across 3 availability zones in the primary region (application servers at 1.5x capacity, MySQL on managed Multi-AZ); in another region, keep a full daily backup plus a continuous stream of binlogs, in other words “backup and restore” plus data replication close to pilot light. A whole-region failure is very unlikely, so it trades an RTO of a few hours for low cost.
In Java
1. Make the application survive a database failover
spring:
datasource:
url: jdbc:mysql://lectures-db.internal.example.com:3306/lectures
hikari:
connection-timeout: 3000 # fail fast during failover; do not let requests queue for 30 seconds
max-lifetime: 240000 # shorter than the idle timeouts of MySQL and any proxy in betweenHow max-lifetime relates to wait_timeout is covered in detail in the HikariCP tuning post. What to add here is connection-timeout: during a failover, the default of 30 seconds means every request hangs for 30 seconds, tying up all threads and upstream connections. Shorten it so requests fail fast, which gives the upstream a chance to retry or degrade.
public static void main(String[] args) {
// When failover relies on DNS pointing to the new primary, the JVM's DNS cache must not outlive the DNS record's TTL
// Without a security manager the JDK caches for 30 seconds by default; set it explicitly instead of relying on the runtime's settings
Security.setProperty("networkaddress.cache.ttl", "30");
SpringApplication.run(LectureApplication.class, args);
}This setting must run before the first DNS lookup; you can also put it in the JDK’s java.security file.
2. Detect that the connection no longer reaches the primary
After a failover, old connections in the pool may still be connected to the old primary. Once the old primary is set to super_read_only, writes fail with MySQL error code 1290. When you detect this error, have the pool retire all its connections:
@RestControllerAdvice
public class DatabaseFailoverAdvice {
private static final int ER_OPTION_PREVENTS_STATEMENT = 1290; // e.g. super_read_only rejecting a write
private final HikariDataSource dataSource;
public DatabaseFailoverAdvice(HikariDataSource dataSource) {
this.dataSource = dataSource;
}
@ExceptionHandler(DataAccessException.class)
public ResponseEntity<ProblemDetail> handle(DataAccessException e) {
if (rejectedByReadOnly(e)) {
// Idle connections close at once, in-use ones close when returned; new connections re-resolve DNS and reach the new primary
dataSource.getHikariPoolMXBean().softEvictConnections();
return ResponseEntity.status(HttpStatus.SERVICE_UNAVAILABLE)
.header(HttpHeaders.RETRY_AFTER, "5")
.body(ProblemDetail.forStatus(HttpStatus.SERVICE_UNAVAILABLE));
}
// Other database errors: do not return SQL or table names to the client
return ResponseEntity.internalServerError()
.body(ProblemDetail.forStatus(HttpStatus.INTERNAL_SERVER_ERROR));
}
private static boolean rejectedByReadOnly(Throwable e) {
for (Throwable t = e; t != null; t = t.getCause()) {
if (t instanceof SQLException sql && sql.getErrorCode() == ER_OPTION_PREVENTS_STATEMENT) {
return true;
}
}
return false;
}
}- Return 503 with
Retry-Afterso the client knows the error is temporary. When the client retries, it must send the same Idempotency Key: the failed transaction may in fact have committed on the old primary already - With a service such as Amazon Aurora, you can also consider a JDBC driver that is aware of the cluster topology, which switches over faster; but the application’s principle of “fail fast, retire connections, retry safely” stays the same
3. Graceful shutdown
Spring Boot’s embedded server shuts down gracefully by default: it stops accepting new requests and waits for in-flight requests to finish. How long it waits is set by spring.lifecycle.timeout-per-shutdown-phase. Combine it with a readiness probe that first takes the instance out of the load balancer (the Load Balancing post), and rolling deploys and availability zone evacuations will not cut off sign-ups in progress.
4. Delayed replication and point-in-time recovery
Create a replica delayed by one hour:
STOP REPLICA;
CHANGE REPLICATION SOURCE TO SOURCE_DELAY = 3600;
START REPLICA;When rows are deleted by mistake, first stop replication on that replica to keep the data from an hour ago. If you need to restore to a more precise point in time, start from the latest full backup and replay the binlog up to the moment just before the deletion:
# Run this on a separate restore host, never directly against the production primary
mysqlbinlog --start-position=4 --stop-datetime="2026-11-22 14:02:59" \
binlog.000123 binlog.000124 | mysql -h restore-host -u restore_admin -pReplace --start-position with the binlog position the full backup recorded. Put the restored data on another host first, check that it is correct, then move only the rows you need back into production instead of overwriting the whole database: the valid sign-ups made after the deletion have to be kept too.
The configuration and code above are based on the official documentation for Spring Boot, HikariCP, MySQL 8.4, and the JDK, and have not been run.
Pitfalls and gotchas
- Backups that have never been restored: on the day you really need one, you find the backup is empty, a table is missing, the decryption key is gone, or the restore takes 12 hours
- Backups in the same failure domain as production: the same availability zone, the same cloud account, the same set of admin permissions
- Trusting the parallel availability math: two servers in the same rack, shipped in the same deploy, are not independent
- Treating autoscaling as redundancy: scaling can fail during an outage, or there may be no machines left to get. Provision critical capacity in advance
- Failover that is too sensitive: it switches on a brief network blip, the switch itself causes an outage of a minute or more, and it may flip back and forth. Detection needs a threshold, and a switch needs a cooldown afterward
- Only “assuming” the old primary has stopped: without fencing off the old primary, it comes back and keeps accepting writes, and the data splits into two versions
- Forgetting the DNS cache and the connection pool: DNS already points to the new primary, but the application is still connected to the old one
- Counting only the database in the RTO: the database finishes switching over in two minutes, but warming the application back up, rebuilding caches, and draining queued messages add another 20 minutes
- A DR plan that depends on the failed region: the off-site recovery steps need you to sign in to the primary region’s management console, pull images from the primary region’s image registry, and read secrets stored in the primary region
Security
- Ransomware goes after the backups first: once attackers have admin rights, they usually delete the backups before encrypting the data. Keep backups in a separate account, managed with a separate set of credentials, and use immutable storage (for example S3 Object Lock in compliance mode), so that within the retention period not even an admin can delete or overwrite them
- A backup is a complete copy of personal data: access control, encryption, and auditing for backups must be as strict as for production. A common real-world situation is a tightly guarded production database whose backups sit in a bucket anyone can read
- Encryption keys need disaster recovery too: if backups are encrypted with a KMS key and the key is deleted or disabled, the backups can never be decrypted again. Include key replication, deletion protection, and key access permissions in your restore drills
- Restoring to a test environment: restoring a production backup into a test or development environment to debug copies every user’s personal data into an environment with weaker protection. Mask or remove the personal data first
- Equal protection for the off-site environment: if the off-site environment’s WAF, access control, audit logs, and secret rotation are not kept in sync, failing over to it switches off part of your protection
- Emergency access accounts: when the single sign-on service itself fails, operators need another way to sign in (break-glass accounts). Keep their credentials offline, alert whenever they are used, and audit their use afterward
- DNS is the control point for failover: whoever can change DNS records can send traffic anywhere. Require multi-factor authentication on the DNS service account, and turn on the transfer lock for the domain at the registrar
When to use it, and when not to
- Always do: spread across multiple availability zones, take regular backups, and run regular restore drills. This is the cheapest part, with the highest payoff
- Depends on the business: cross-region warm standby or active-active. First use RPO and RTO to work out the cost of downtime and lost data, then compare it with the cost of the redundancy
- Don’t: invest in multi-region active-active before you have reliable backups and a restore process. Complexity rises sharply, and it solves none of the data correctness problems (accidental deletes, ransomware)
Further reading: handing this failure-handling experience to an LLM agent that helps with on-call, in the Agent series Part 6-2 Designing an On-Call Incident Assistant.
References
- AWS Whitepaper — Disaster Recovery of Workloads on AWS: Recovery in the Cloud: https://docs.aws.amazon.com/whitepapers/latest/disaster-recovery-workloads-on-aws/disaster-recovery-workloads-on-aws.html
- AWS Builders’ Library — Static stability using Availability Zones: https://aws.amazon.com/builders-library/static-stability-using-availability-zones/
- Amazon RDS User Guide — Multi-AZ DB instance deployments: https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/Concepts.MultiAZSingleStandby.html
- Google, Site Reliability Engineering, Chapter 3 “Embracing Risk” and Chapter 26 “Data Integrity”: https://sre.google/sre-book/table-of-contents/
- MySQL 8.4 Reference Manual — Delayed Replication: https://dev.mysql.com/doc/refman/8.4/en/replication-delayed.html
- MySQL 8.4 Reference Manual — Point-in-Time (Incremental) Recovery: https://dev.mysql.com/doc/refman/8.4/en/point-in-time-recovery.html
- Spring Boot Reference — Graceful Shutdown: https://docs.spring.io/spring-boot/reference/web/graceful-shutdown.html
- Java SE — Networking Properties (
networkaddress.cache.ttl): https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/net/doc-files/net-properties.html - Further interactive diagrams: Dilum Sanjaya, System Design — an interactive course: https://designed-to-scale.vercel.app/
Comments