Most teams find out how their database failover behaves during the first real incident. The cluster promotes a replica in 20 seconds, but the application keeps writing to a cached IP for two minutes, connection pools fill with dead sockets, and nobody can say whether committed writes were lost. A database failover test turns those unknowns into measured numbers. This guide covers what to measure (detection, promotion, client reconnect, and data loss), the pre-checks, a game-day runbook, the commands that trigger a controlled failover on Amazon RDS, Aurora, Patroni, MySQL, SQL Server, and MongoDB, the application settings that decide most of the real downtime, and a write-up template.
- Measure four clocks separately: detection, promotion, client reconnect, and data loss. The database usually reports only the second one.
- Run a write probe during every drill. Count the writes the client saw acknowledged, then check that every one of them exists on the new primary.
- A planned switchover (
patronictl switchover,rs.stepDown(),ALTER AVAILABILITY GROUP ... FAILOVER) does not test failure detection. Schedule an unplanned test on staging too. - On AWS, use
aws rds reboot-db-instance --force-failoverfor a Multi-AZ DB instance andaws rds failover-db-clusterfor Aurora and Multi-AZ DB clusters.
Scope and review date: November 2026. This guide covers Amazon RDS Multi-AZ and Aurora, Patroni 4.x on PostgreSQL, MySQL 8.4 InnoDB Cluster and Orchestrator, SQL Server Always On availability groups, and MongoDB replica sets. Commands, defaults, and timings were checked against vendor documentation on 25 November 2026. They were not run in a lab, so rehearse every step on staging before you run it against production.
What should a database failover test measure?
"Failover took 30 seconds" hides which part was slow. Split the outage into four measurements, each with a timestamp source you trust.
- Detection time: from the moment the primary stops serving writes to the moment the HA manager decides to fail over. In Patroni this is bounded by the leader lock
ttl; in MongoDB byelectionTimeoutMillis. - Promotion time: from the decision to the moment the new primary accepts writes.
- Client reconnect time: from promotion to the first successful application write. DNS caching, pools, and retries live here.
- Data loss: acknowledged writes missing on the new primary, counted from probe rows and, where possible, an LSN or GTID difference.
The four clocks of a failover
Time each stage separately; the application sees the sum of the first three
After step 3: compare acknowledged probe writes with the rows on the new primary. That count is your data loss, and it is the number a promotion-time metric never shows.
A write probe gives you all four: a loop that inserts a timestamped row through your application's connection path and logs each result.
-- Run once on the primary before the drill (PostgreSQL syntax shown)
CREATE TABLE failover_probe (
id bigserial PRIMARY KEY,
sent_at timestamptz NOT NULL,
note text
);#!/usr/bin/env bash
# Write probe: one insert every 200 ms through the application's endpoint.
# Logs "ok" or "fail" with a client-side timestamp for every attempt.
DSN="host=pg-writer.internal dbname=app user=probe connect_timeout=2 target_session_attrs=read-write"
while true; do
ts=$(date -u +%Y-%m-%dT%H:%M:%S.%3NZ)
if psql "$DSN" -qAtc "INSERT INTO failover_probe (sent_at, note) VALUES ('$ts', 'drill') RETURNING id" >> probe-acked.log 2>/dev/null; then
echo "$ts ok" >> probe.log
else
echo "$ts fail" >> probe.log
fi
sleep 0.2
doneInterpretation: the first fail line marks when writes stopped, the last fail before a run of ok lines marks reconnect, and probe-acked.log holds every id the database acknowledged. After the drill, every id in that file must exist on the new primary. It opens a new connection per insert, so also run a probe inside your real application pool. date +%3N needs GNU date.
What should you check before a failover drill?
A drill against a lagging replica measures the lag, not the failover. Abort if any of these fails.
- Every replica that could be promoted is healthy and caught up.
- Backups completed recently and a restore has been tested, so a failed drill has a fallback.
- The HA manager is not paused (Patroni maintenance mode, Orchestrator downtime, RDS pending maintenance).
- The on-call team knows a drill is running, and one named person can abort it.
-- PostgreSQL: on the primary, replay lag in bytes per standby
SELECT application_name, state, sync_state,
pg_wal_lsn_diff(pg_current_wal_lsn(), replay_lsn) AS replay_lag_bytes
FROM pg_stat_replication;Interpretation: state should be streaming and replay_lag_bytes close to zero under normal load. pg_current_wal_lsn() and pg_wal_lsn_diff() are documented in the PostgreSQL system administration functions.
-- SQL Server: run on the primary; every database on the target replica must be ready
SELECT ar.replica_server_name, drcs.database_name, drcs.is_failover_ready
FROM sys.dm_hadr_database_replica_cluster_states AS drcs
JOIN sys.availability_replicas AS ar ON ar.replica_id = drcs.replica_id;Interpretation: Microsoft's planned failover guide names is_failover_ready in sys.dm_hadr_database_replica_cluster_states as the readiness check. A value of 1 for every database on the target replica means a planned failover can proceed without data loss.
How do you run a failover drill step by step?
Use the same sequence for every engine so drills are comparable. Only step 4 changes per platform.
Failover game-day runbook
Eight steps; steps 4 to 6 are the write outage window
-
Announce and assign roles
Name a driver, an observer who records timestamps, and the person who can abort. Post the start time in the incident channel.
-
Run the pre-checks
Replication healthy, lag near zero, backups current, HA manager active. Abort if any check fails.
-
Start the probes and record positions
Start the write and read probes. Record the primary's LSN or GTID set as the baseline.
psql -Atc "SELECT pg_current_wal_lsn()" -
Trigger the failover
Outage startsUse the platform command for a planned test, or stop the primary host on staging for an unplanned one.
aws rds reboot-db-instance \ --db-instance-identifier app-db \ --force-failover -
Watch the HA manager and events
OutageRecord when it detected the failure and when it promoted. Do not intervene unless the abort criteria are met.
-
Confirm writes resume
Outage endsThe first ok line in the probe log after the failures is the reconnect time. Check the application's own error rate too.
-
Compare data
Every acknowledged probe id must exist on the new primary. Compare LSN or GTID sets where the old primary is reachable.
-
Restore topology and write up
Rejoin the old primary as a replica, fail back if your design needs it, and record the four numbers the same day.
Abort point: decide before step 4 what ends the drill early, such as writes failing for longer than your recovery time objective. Once step 4 runs you cannot undo the promotion, only fail back.
How do you test failover on RDS Multi-AZ and Aurora?
AWS has two commands, and which one you use depends on the deployment type. A Multi-AZ DB instance (one primary and one standby you cannot read from) fails over through a reboot. An Aurora DB cluster, or an RDS Multi-AZ DB cluster with two readable standbys, uses failover-db-cluster.
# RDS Multi-AZ DB instance: reboot through a Multi-AZ failover
aws rds reboot-db-instance \
--db-instance-identifier app-db \
--force-failover
# Aurora DB cluster or Multi-AZ DB cluster: promote a chosen reader
aws rds failover-db-cluster \
--db-cluster-identifier app-cluster \
--target-db-instance-identifier app-cluster-instance-2Interpretation: the reboot-db-instance reference states that you cannot enable --force-failover on an instance that is not configured for Multi-AZ. The failover-db-cluster reference notes that --target-db-instance-identifier is not supported for RDS for MySQL Multi-AZ DB clusters, so omit it there.
Do not use the Availability Zone shown in the console to decide the failover has finished. AWS says the zone can take several minutes to update, and that the Multi-AZ instance failover completed event is the authoritative signal (Failing over a Multi-AZ DB instance). Read it with aws rds describe-events --source-identifier app-db --source-type db-instance and compare the gap between the started and completed events with the gap in your probe log.
Failover on three AWS deployment types
Switch types to see the test command and AWS's documented timing
RDS Multi-AZ instance
| Item | RDS Multi-AZ DB instance |
|---|---|
| Test command | reboot-db-instance --force-failover |
| Can you choose the target? | No, there is one standby |
| Documented failover time | Typically 60 to 120 seconds |
| How clients follow | DNS record of the instance endpoint changes to the standby |
Aurora cluster
| Item | Aurora DB cluster |
|---|---|
| Test command | failover-db-cluster |
| Can you choose the target? | Yes, with --target-db-instance-identifier; otherwise promotion tiers 0 to 15 decide |
| Documented failover time | Typically under 60 seconds, often under 30, with a replica; under 10 minutes without one |
| How clients follow | The cluster endpoint points to the new writer |
Multi-AZ DB cluster
| Item | RDS Multi-AZ DB cluster |
|---|---|
| Test command | failover-db-cluster |
| Can you choose the target? | Yes, except on RDS for MySQL Multi-AZ DB clusters |
| Documented failover time | Typically less than 35 seconds |
| How clients follow | Reconnect to the cluster endpoint; each instance endpoint keeps its own address |
Timing source: the times are AWS's own figures from the Multi-AZ, Aurora high availability, and failover-db-cluster pages. Your measured reconnect time will be longer, and that difference is what the drill is for.
AWS states that RDS Proxy bypasses DNS caches and reduces failover times by up to 66% for Aurora Multi-AZ databases. Run the probe through the proxy endpoint.
How do you test Patroni switchover and failover?
Patroni has two commands, and the patronictl documentation is clear about the difference. switchover is for a healthy cluster: it demotes the current leader cleanly and promotes a candidate, and it can be scheduled. failover is meant for an unhealthy cluster with no leader, and the docs warn that it can lose data depending on how current the candidate is. The latest Patroni release is 4.1.5 (12 August 2026); in Patroni 4 the leader option is --leader or --primary.
# Planned test: clean switchover to a named candidate
patronictl -c /etc/patroni/patroni.yml switchover pg-cluster \
--leader pg-01 --candidate pg-02 --force
# Watch roles, timelines, and lag every 2 seconds during the drill
patronictl -c /etc/patroni/patroni.yml list pg-cluster -WInterpretation: pg-02 becomes Leader, the timeline increases by one, and pg-01 rejoins as a replica. A switchover does not test detection, because Patroni is told the leader is leaving.
patronictl list after a switchover
Illustrative output: columns follow the patronictl documentation (Host column omitted for width); members and LSNs are examples
Check the timeline: every member should show the same TL after the switchover. A member stuck on the old timeline has not rejoined and needs attention before the next drill.
For an unplanned test on staging, power off the leader VM or block its network; stopping Patroni cleanly releases the leader key and skips detection. Detection is then governed by the dynamic configuration: Patroni's defaults are ttl 30 seconds, loop_wait 10 seconds, and retry_timeout 10 seconds, and the dynamic configuration docs require loop_wait + 2 * retry_timeout <= ttl.
# patronictl edit-config: values that bound detection time and data loss
ttl: 30 # default
loop_wait: 10 # default
retry_timeout: 10 # default
maximum_lag_on_failover: 1048576 # bytes; set your own limitInterpretation: with the defaults, expect detection to take up to roughly the 30-second ttl before promotion starts. maximum_lag_on_failover is the most a follower may lag, in bytes, and still take part in the leader election. Patroni's replication modes page says that in asynchronous mode the worst-case loss is that many bytes of WAL plus what was written in the last ttl seconds, so record it in the drill write-up.
How do you test MySQL InnoDB Cluster and Orchestrator failover?
In a single-primary InnoDB Cluster, Group Replication elects a new primary on its own when the primary leaves. For a planned test, MySQL Shell's Cluster.setPrimaryInstance() overrides the election and moves the primary to a named member. The MySQL Shell 8.4 documentation describes a runningTransactionsTimeout option of 0 to 3600 seconds; once set, new incoming transactions are rejected while running ones finish.
// MySQL Shell (JavaScript mode), connected to any cluster member
var cluster = dba.getCluster()
cluster.status()
cluster.setPrimaryInstance('clusteradmin@db-02:3306', {runningTransactionsTimeout: 30})
cluster.status()Interpretation: the primary field should change and every member should report ONLINE. For an unplanned test on staging, stop mysqld on the primary and time how long MySQL Router takes to route writes again.
For asynchronous or semi-synchronous replication managed by Orchestrator, note the project status first: the original openark/orchestrator repository was archived on 18 February 2025 and points users to the Percona fork. The topology recovery docs list the commands for both drill types.
# Planned: graceful takeover to a named replica, restart replication on the old master
orchestrator-client -c graceful-master-takeover-auto -alias mycluster \
-d db-02.internal:3306
# Unplanned drill on staging: force a master failover for the cluster
orchestrator-client -c force-master-failover --alias myclusterInterpretation: in a graceful takeover, Orchestrator sets the old master read-only, waits for the designated replica to catch up, promotes it, and repositions the old master under it. The docs warn that applications see the master as read-only for a few seconds, so expect ERROR 1290 (--read-only) in the application log, not connection errors.
-- Data-loss check: run on the new primary. Paste in the old primary's final
-- gtid_executed, read after the drill (a pre-drill baseline misses drill writes)
SELECT GTID_SUBTRACT('<old_primary_gtid_executed>', @@GLOBAL.gtid_executed) AS missing_on_new_primary;Interpretation: an empty result means every transaction the old primary executed exists on the new one. Anything listed is either lost or errant and needs investigation before the old primary rejoins. GTID_SUBTRACT() is documented in the MySQL 8.4 GTID functions reference.
How do you fail over a SQL Server availability group for a test?
A planned manual failover is supported only when the primary and the target secondary are both in synchronous-commit mode and the target is synchronized. You run it on the target secondary, not on the primary (Microsoft: perform a planned manual failover).
-- Connected to the instance hosting the target secondary replica
ALTER AVAILABILITY GROUP [AppAG] FAILOVER;
-- Afterwards, confirm roles and synchronization
SELECT ar.replica_server_name, ars.role_desc, ars.synchronization_health_desc
FROM sys.dm_hadr_availability_replica_states AS ars
JOIN sys.availability_replicas AS ar ON ar.replica_id = ars.replica_id;Interpretation: the command returns as soon as the target accepts it, while database recovery continues asynchronously. Stop the clock when probe writes succeed through the listener.
ALTER AVAILABILITY GROUP ... FORCE_FAILOVER_ALLOW_DATA_LOSS is the disaster path for an unavailable primary. Microsoft's procedure afterwards removes the original primary from the group, so rehearse it only on a staging availability group you can rebuild.
How do you test MongoDB replica set failover?
rs.stepDown() is the planned test. The rs.stepDown() reference gives the defaults: the primary stays ineligible for 60 seconds, and it waits up to 10 seconds for an electable secondary to catch up. It steps down only if a secondary is caught up, to prevent rollbacks, and otherwise returns an error.
// mongosh, connected to the primary
rs.stepDown(120, 15) // ineligible for 120 s, wait up to 15 s for catch-up
// From any member: who is primary now, and which election term?
rs.status().members.filter(m => m.stateStr === "PRIMARY").map(m => m.name)
rs.status().termInterpretation: stepDownSecs must be greater than secondaryCatchUpPeriodSecs. MongoDB documents the worst-case write outage as the catch-up period plus electionTimeoutMillis (10 seconds by default). In-progress transactions fail with TransientTransactionError and can be retried as a whole.
On the client side, check that retryable writes are on. MongoDB states that drivers compatible with 4.2 and later enable them by default, and that a write is retried once, which covers a single election but not a longer outage (Retryable Writes). A connection string with retryWrites=false turns every election into application errors, so grep your configuration for it before the drill.
What should the application do during a failover?
Most of the outage users feel is the reconnect clock, and application configuration sets it. Review these before the drill.
DNS caching
RDS failover changes the DNS record of the endpoint, so a client that caches the old address keeps connecting to the demoted host. AWS recommends a JVM DNS TTL of no more than 60 seconds and warns that some Java configurations never refresh DNS until restart.
# $JAVA_HOME/conf/security/java.security (or set it in code before the first connection)
networkaddress.cache.ttl=60Interpretation: AWS's page shows the older $JAVA_HOME/jre/lib/security/java.security path; on Java 9 and later the file is under conf/security. Check the effective value with java.security.Security.getProperty("networkaddress.cache.ttl").
Multi-host connection strings
Without a DNS-based endpoint, as with many Patroni setups, libpq can list several hosts and pick the writable one. The libpq connection docs list read-write and primary among the target_session_attrs modes; the default is any.
postgresql://pg-01:5432,pg-02:5432,pg-03:5432/app?target_session_attrs=read-write&connect_timeout=2Interpretation: with any, a client can connect to the demoted primary after a switchover and fail with cannot execute INSERT in a read-only transaction. read-write makes it skip to the next host.
Connection pool behavior
Pools keep connections to the old primary; some die at once, some stay open to a node that is now read-only. In HikariCP, connectionTimeout defaults to 30,000 ms, so a request can wait 30 seconds before it fails (HikariCP configuration). Evict connections that return read-only errors.
Retries and reconnect storms
Retry idempotent operations with exponential backoff and jitter, capped below your request timeout. Without jitter, every instance reconnects at once and the new primary takes a connection spike right after promotion; watch its connection count during the drill.
How should you write up a failover test, and how often?
Write up each drill on the day, in the same one-page format, so drills can be compared over time.
| Field | What to record |
|---|---|
| Scope | Cluster, engine and version, HA manager version, drill type (planned switchover or unplanned failure), environment |
| Trigger | Exact command or action, who ran it, start time in UTC |
| Detection time | From the first failed probe write to the HA manager's decision log line (unplanned drills only) |
| Promotion time | From the decision to the new primary accepting writes, from HA manager or cloud events |
| Client reconnect time | From promotion to the first successful write, per probe and for the real application |
| Data loss | Acknowledged probe ids missing on the new primary; LSN or GTID difference |
| Against targets | Measured total compared with the recovery time and recovery point objectives |
| Surprises | Alerts that did or did not fire, errors seen by the application, manual steps needed |
| Fixes | Each fix with an owner and a date; the next drill checks them |
Cadence. Schedule a planned switchover for each production cluster on a regular calendar, for example quarterly, and an unplanned-failure drill on staging at the same interval. Add a drill after any change to the failover path: replica or zone layout, engine or HA manager upgrade, a new proxy, or a driver or pool change. If your design includes failback, test it too.
Frequently asked questions
How do you test database failover without affecting production?
Run unplanned-failure drills on a staging cluster that copies production's topology, HA manager, and connection path. In production, use planned switchovers such as patronictl switchover, rs.stepDown(), or an RDS reboot with failover in a low-traffic window. They cause a short write outage, so announce them and run a write probe to measure it.
What is the difference between a switchover and a failover?
A switchover is planned: the current primary is healthy, steps down cleanly, and hands over to a caught-up replica, so committed data is not lost. A failover happens when the primary is unavailable, and the HA manager promotes the best replica it can reach. A failover can lose writes that had not replicated, which is why drills should test both.
How do I force a failover on Amazon RDS?
For a Multi-AZ DB instance, run aws rds reboot-db-instance with --force-failover; it fails if the instance is not Multi-AZ. For Aurora or an RDS Multi-AZ DB cluster, run aws rds failover-db-cluster, optionally with --target-db-instance-identifier. Confirm completion with the "Multi-AZ instance failover completed" event, not the Availability Zone shown in the console.
How do you measure data loss after a failover?
Run a write probe that logs every acknowledged write, then check that each one exists on the new primary. For PostgreSQL, compare the old primary's last LSN with the new primary's position. For MySQL with GTIDs, run GTID_SUBTRACT of the old primary's gtid_executed against the new primary's; an empty result means nothing is missing.
Key takeaways
- Measure detection, promotion, client reconnect, and data loss as four separate numbers; the total is what users feel.
- A write probe that logs acknowledged ids is the most reliable data-loss check on any engine.
- Planned switchovers test promotion and reconnect; only an unplanned-failure drill tests detection.
- DNS caching, multi-host connection settings, pool timeouts, and retries usually decide the reconnect time.
- Write up every drill in the same format, track the fixes, and repeat after every change to the failover path.
Plan and run failover drills with JusDB
JusDB's database high availability team can help you plan a failover test for RDS, Aurora, Patroni, MySQL, SQL Server, or MongoDB clusters: write the drill runbook and probes, review driver and pool settings before the drill, and run the game day with your engineers.
Bring your topology, HA manager configuration, recovery time and recovery point objectives, and the application's connection settings. Your team approves every production change.