Skip to content

MySQL point-in-time recovery — the binlog replay runbook

Recover a MySQL database to the moment just before a bad DELETE or UPDATE by replaying binary logs onto a spare server. The runbook covers the settings to put in place now, how to find the bad event with mysqlbinlog, and how to copy only the lost rows back.

If someone ran a DELETE without a WHERE clause at 2:40 this afternoon, last night’s backup alone would lose everything written since. Point-in-time recovery, often shortened to PITR, closes that gap. It needs two things: a consistent full backup, and an unbroken chain of binary logs (the binlogs, MySQL’s record of every change) starting at the log position recorded when that backup was taken. You restore the backup onto a spare instance, replay the binlogs with mysqlbinlog until one event before the bad statement, then copy only the affected rows into production. Whether this works on the night depends on settings made weeks earlier: log_bin on, binlog_format=ROW, a binlog retention longer than your backup interval, and a backup that records its position.

What you’ll accomplish

  • Turn on and verify the prerequisites — binary logging, ROW format, retention, and binlogs on storage separate from the data directory — before an incident forces the question.
  • Read a backup’s recorded log coordinates out of a mysqldump header or a Percona XtraBackup metadata file.
  • Find the exact position or GTID of the offending statement with mysqlbinlog, instead of guessing at a timestamp.
  • Restore and replay onto a spare instance, stopping cleanly before the damage.
  • Extract only the affected rows and put them back into production, without swinging the whole server.

Prerequisites

  • MySQL 8.0 or 8.4. Binary logging is on by default from 8.0, and binlog_format defaults to ROW. On 8.4, SHOW MASTER STATUS is gone — the statement is now SHOW BINARY LOG STATUS, and RESET MASTER is now RESET BINARY LOGS AND GTIDS. The mysqldump option --master-data was renamed --source-data in 8.0.26; the old spelling still works in 8.0 but was removed in 8.4.
  • MariaDB is close but not identical. MariaDB keeps --master-data and has no --source-data. Binary logging is off by default, so log_bin must be set explicitly. Retention is expire_logs_days rather than binlog_expire_logs_seconds. MariaDB’s GTID model is domain-based and its mysqlbinlog does not offer --exclude-gtids, so on MariaDB you plan around positions, not GTIDs.
  • Disk space for two full copies of the data, plus the binlogs covering the recovery window. A replay is a write-heavy workload; if the spare instance runs out of space halfway through you start over.
  • A spare host or a second mysqld on a different port or socket. Restoring in place onto the damaged primary destroys the one artifact you still have — the current state — and gives you nothing to compare against.
  • The binlogs actually preserved. If binlog_expire_logs_seconds (default 2592000, 30 days) has already rotated away the file your backup points at, the chain is broken and PITR is over before it starts.
  • Client access with RELOAD, BACKUP_ADMIN or SUPER on the source, and full privileges on the spare instance.

How it works

MySQL’s binary log is an ordered record of every change that modified data, written as events with byte positions inside numbered files. A full backup captures the database at one instant; the binary log captures everything that happened afterwards. Line them up and you can rebuild the database as it existed at any moment in between.

Timeline showing a full backup at T0 with its recorded log position, three binary log files running forward in time, a bad DELETE at T_bad inside the third file, and the replay window covering everything from the backup position up to but not including the bad event

Two coordinates matter. The first is where the backup ends — a file name and a position, such as binlog.000041 at 154. mysqldump --single-transaction --source-data=2 writes that as a comment near the top of the dump; Percona XtraBackup writes it to xtrabackup_binlog_info. The second is where the damage begins — the position of the first event of the transaction containing the bad statement. Replay everything between those two coordinates and you have the database as of the instant before the mistake.

The reason to stop at a position rather than a datetime is resolution. Binary log event timestamps have one-second granularity. If forty transactions committed in the same second as the bad DELETE, --stop-datetime cannot separate them: it either includes the DELETE or drops the thirty-nine innocent transactions with it. A position, or a GTID, identifies one transaction exactly.

Where you replay matters as much as what you replay.

Recovery topology: the production primary is left untouched and keeps serving, the full backup and the binary log chain are restored and replayed onto a separate spare recovery instance, and only the recovered rows are exported from that instance back into production

Production stays up and untouched. The spare instance takes the backup and the replay. When it reaches the pre-incident state, you export the rows that were destroyed and import them into production. That keeps the blast radius equal to the rows you lost, rather than to every write that happened during the recovery.

Step-by-step

1. Stop the clock on binlog expiry, then copy the logs off. Before anything else, make sure nothing rotates away while you work.

mysql -e "SET GLOBAL binlog_expire_logs_seconds = 0; FLUSH BINARY LOGS; SHOW BINARY LOGS;"
+---------------+-----------+-----------+
| Log_name      | File_size | Encrypted |
+---------------+-----------+-----------+
| binlog.000041 | 104857931 | No        |
| binlog.000042 | 104858122 | No        |
| binlog.000043 |  98442117 | No        |
| binlog.000044 |       157 | No        |
+---------------+-----------+-----------+

A 0 value disables automatic purging entirely. FLUSH BINARY LOGS closes the active file so you are copying a file nobody is appending to. Now get the logs onto the recovery host:

rsync -a /var/lib/mysql-binlogs/binlog.0000[4]* recovery-host:/srv/pitr/binlogs/
sent 302,157,204 bytes  received 92 bytes  40,287,639.47 bytes/sec
total size is 302,158,327  speedup is 1.00

2. Read the backup’s log position. With mysqldump, it is a comment in the file:

grep -m1 -i 'CHANGE REPLICATION SOURCE TO' /srv/backups/shop-2026-07-23.sql
-- CHANGE REPLICATION SOURCE TO SOURCE_LOG_FILE='binlog.000041', SOURCE_LOG_POS=154;

If nothing comes back, the backup was taken without --source-data and you have no starting coordinate — see the troubleshooting section. The backup that produced this line was taken as:

mysqldump --single-transaction --source-data=2 --set-gtid-purged=ON \
  --databases shop > /srv/backups/shop-2026-07-23.sql

With Percona XtraBackup the coordinates live in a metadata file inside the backup directory:

cat /srv/backups/2026-07-23/xtrabackup_binlog_info
binlog.000041	154	3f8a1c02-5b31-11ef-9c4a-0242ac110002:1-884217

3. Confirm the chain is unbroken. The file your backup points at must still exist, and every file between it and the incident must be present.

ls -1 /srv/pitr/binlogs/
binlog.000041
binlog.000042
binlog.000043

A gap in the numbering means the chain is broken and you can only recover up to the gap.

4. Find the offending event. Decode a window around the incident. --base64-output=DECODE-ROWS --verbose turns ROW events into readable pseudo-SQL comments.

mysqlbinlog --no-defaults --base64-output=DECODE-ROWS --verbose \
  --start-datetime='2026-07-23 02:55:00' \
  --stop-datetime='2026-07-23 03:15:00' \
  /srv/pitr/binlogs/binlog.000043 > /srv/pitr/window.sql
(no output on success; window.sql is written)

Now find the statement and the position of the transaction it belongs to:

grep -n -B 8 'DELETE FROM .shop..orders' /srv/pitr/window.sql | head -14
3184-# at 92117
3185-#260723  3:04:11 server id 1  end_log_pos 92196 	Gtid	last_committed=4102
3186-SET @@SESSION.GTID_NEXT= '3f8a1c02-5b31-11ef-9c4a-0242ac110002:884219';
3188-# at 92196
3189-#260723  3:04:11 server id 1  end_log_pos 92275 	Query	thread_id=884	exec_time=0
3190-BEGIN
3196-# at 92381
3199:### DELETE FROM `shop`.`orders`

The number you want is 92117 — the position of the Gtid event that opens the transaction, not the position of the DELETE rows event. Stopping at 92196 would replay a partial transaction. If your server runs without GTIDs, the transaction opens with the BEGIN query event instead, and you take that position.

5. Restore the full backup onto the spare instance. Start a second mysqld on its own socket and data directory, then load the dump.

mysql --socket=/run/mysqld/recovery.sock < /srv/backups/shop-2026-07-23.sql
(no output on success)

Confirm the damaged table is at its pre-incident shape before you replay anything:

mysql --socket=/run/mysqld/recovery.sock -e "SELECT COUNT(*) FROM shop.orders"
+----------+
| COUNT(*) |
+----------+
|   847213 |
+----------+

6. Replay the binlog chain in one invocation. Pass every file, in order, to a single mysqlbinlog command piped into a single mysql session.

mysqlbinlog --no-defaults --disable-log-bin --skip-gtids \
  --start-position=154 \
  --stop-position=92117 \
  /srv/pitr/binlogs/binlog.000041 \
  /srv/pitr/binlogs/binlog.000042 \
  /srv/pitr/binlogs/binlog.000043 \
  | mysql --socket=/run/mysqld/recovery.sock
(no output on success)

Three flags are doing real work here. --start-position applies to the first file named on the command line and --stop-position to the last, which is why the whole chain goes in one command. --disable-log-bin emits SET @@SESSION.SQL_LOG_BIN=0 so the replay does not generate a second copy of every event on the recovery instance. --skip-gtids omits the SET @@SESSION.GTID_NEXT statements, which would otherwise collide with what the restore already registered in gtid_executed.

Running this as separate mysqlbinlog invocations is the classic way to corrupt a recovery. Temporary tables, user variables and session state created in one file are used by events in the next; a fresh mysql connection per file throws that context away and the replay fails or, worse, silently produces different data.

7. If you have GTIDs, consider excluding instead of stopping. When the mistake is one transaction and you want everything after it too, replay the whole chain and drop just that GTID:

mysqlbinlog --no-defaults --disable-log-bin --skip-gtids \
  --exclude-gtids='3f8a1c02-5b31-11ef-9c4a-0242ac110002:884219' \
  /srv/pitr/binlogs/binlog.000041 \
  /srv/pitr/binlogs/binlog.000042 \
  /srv/pitr/binlogs/binlog.000043 \
  | mysql --socket=/run/mysqld/recovery.sock
(no output on success)

This only works when later transactions did not read what the bad one wrote. If the application read the post-DELETE state and acted on it, excluding the transaction leaves you with a database that never existed.

8. Export only the recovered rows. Dump the affected range from the recovery instance, data only.

mysqldump --socket=/run/mysqld/recovery.sock \
  --no-create-info --skip-add-locks --skip-disable-keys --insert-ignore \
  --where='id BETWEEN 91733 AND 134002' \
  shop orders > /srv/pitr/orders-recovered.sql
(no output on success)

--insert-ignore matters if some rows in the range survived: it skips them rather than aborting the import on a duplicate key. Then load it into production:

mysql shop < /srv/pitr/orders-recovered.sql
(no output on success)

Validate it works

Compare the affected range on both servers. On the recovery instance:

mysql --socket=/run/mysqld/recovery.sock \
  -e "SELECT COUNT(*), MIN(id), MAX(id) FROM shop.orders WHERE id BETWEEN 91733 AND 134002"
+----------+-------+--------+
| COUNT(*) | MIN   | MAX    |
+----------+-------+--------+
|    42270 | 91733 | 134002 |
+----------+-------+--------+

Run the identical query against production. The counts and boundary values should match. Then checksum the whole table on both:

mysql -e "CHECKSUM TABLE shop.orders"
+--------------+------------+
| Table        | Checksum   |
+--------------+------------+
| shop.orders  | 3907441882 |
+--------------+------------+

Identical checksums on both hosts mean the table is byte-consistent. For a live production table where rows keep arriving, pt-table-checksum from Percona Toolkit compares in chunks without needing the table to be still.

Finally, prove the replay window really excluded the mistake:

mysqlbinlog --no-defaults --base64-output=DECODE-ROWS --verbose \
  --start-position=154 --stop-position=92117 \
  /srv/pitr/binlogs/binlog.000043 | grep -c 'DELETE FROM .shop..orders'
0

Zero occurrences in the replayed range is the signal you stopped in the right place. A non-zero count means your stop position is past the transaction and the recovery instance has the same damage as production.

Troubleshooting

The binlog file the backup points at no longer exists. SHOW BINARY LOGS starts at a file numbered higher than the one in your dump header, or mysqlbinlog reports ERROR 1236 when reading remotely. The chain is broken and PITR to a point before the earliest surviving file is not possible; you can only restore the backup as-is. The fix is preventative: set binlog_expire_logs_seconds to comfortably more than your longest backup interval, put binlogs on a filesystem separate from datadir with log_bin_basename so a full data volume cannot stop logging, and ship each rotated file to object storage as it closes.

binlog_format=STATEMENT makes row recovery unreliable. --base64-output=DECODE-ROWS produces nothing useful because there are no row events to decode, and replay of statements containing NOW(), UUID(), RAND(), or an UPDATE ... LIMIT without a deterministic ORDER BY can produce different rows than the original execution. Check with SELECT @@GLOBAL.binlog_format and switch to ROW. Also check binlog_row_image: at MINIMAL the delete events carry only the primary key, so you can identify which rows were removed but cannot reconstruct their contents from the log. FULL is the default and the value you want for recoverability.

Replay dies on ERROR 1062 Duplicate entry. Almost always a coordinate error: the backup was taken after the position you started from, so the replay re-applies inserts already present. Re-read the dump header, and make sure --start-position matches the backup exactly rather than a rounded-down guess. The second common cause is replaying the same file twice because someone re-ran the command after a partial failure. Resist the temptation to pass --force to the mysql client to push past the errors — it turns a stalled recovery into a silently wrong one. Drop the recovery database and start the restore again.

GTID errors on the recovery instance. ERROR 1837 (HY000): When @@SESSION.GTID_NEXT is set to a GTID, you must explicitly set it to a different value or a complaint that GTID_NEXT cannot be ANONYMOUS while gtid_mode=ON both mean the replay stream and the instance disagree about GTID bookkeeping. The straightforward fix is --skip-gtids on mysqlbinlog, which strips the GTID assignments and lets the events apply as ordinary transactions. If you would rather keep GTIDs intact, clear the instance’s history first with RESET BINARY LOGS AND GTIDS on 8.4 (RESET MASTER on 8.0) before restoring the backup.

mysqlbinlog: unknown variable 'default-character-set=utf8mb4'. mysqlbinlog reads the [client] group from my.cnf but does not accept every option a client accepts. Add --no-defaults as the first argument, or move the offending setting from [client] into [mysql]. This is why every mysqlbinlog command above starts with --no-defaults: during an incident you want the tool reading nothing but the arguments you typed.

When this is the wrong approach

  • You already run a delayed replica. CHANGE REPLICATION SOURCE TO SOURCE_DELAY=3600 gives you an instance permanently an hour behind. If the mistake is younger than the delay, you stop the replica, use START REPLICA UNTIL to walk it to just before the event, and read the rows straight out. That is minutes of work instead of hours of restore.
  • The instance is on a managed platform with built-in PITR. RDS-style services keep the backup and log chain for you and restore to a new instance from a timestamp in the console. Doing it by hand there means fighting the platform for binlog access you may not have.
  • You have filesystem or volume snapshots. Restoring an LVM or block-storage snapshot and letting InnoDB crash-recover is faster than replaying hours of binlogs, if a snapshot exists close enough to the incident. Snapshots and binlogs are complementary: the snapshot gets you near, the binlogs get you exact.
  • The damage is a schema change, not rows. A dropped column or a botched ALTER is usually better handled by restoring that one table from backup than by rebuilding the whole instance. See mysqldump backup and restore for the single-table path.
  • Never replay against a live primary. mysqlbinlog output is plain SQL, and nothing in it knows which server it is being applied to. Piping it into production re-applies history on top of current data. The output belongs on the spare instance, always.

For the exact semantics of every flag used here, the reference pages are Point-in-Time Recovery Using Binary Log and mysqlbinlog. For reading events in anger — tracing who ran what, and when — see mysqlbinlog forensics.

If this is the kind of work you’d rather never own again, it’s the daily job of Managed Cloud Ops — book an infrastructure review.