Overview

It was 0:47 a.m. and a reconciliation alert woke me up on the living room couch. Not the “some box is burning CPU” kind of alert — this was a number out of the payment reconciliation job: 37,904 orders whose status disagreed with their payment records for the day.

Two hours later we knew the whole story. At 22:10 someone ran a “status correction” script. The script had passed review. The SQL was plain enough. What was wrong was the database it connected to — it used the order_read read-only alias, and that alias had been pointing at the primary ever since the read/write split config change earlier that evening. Add a status IN ('pending','paid') filter that was far too wide, let it run to completion, and 38,412 orders became cancelled.

Putting them back took three hours and twelve minutes. The actual writes took 101 seconds. The other three hours went into establishing which rows had been touched, what their original values were, and whether fixing them would also clobber orders that had been legitimately cancelled.

Since then I’ve held one rule: a data repair is not “running a SQL statement”, it’s a production change with a blast radius. The risk is on par with shipping a service release, or worse — a service can be rolled back, but wrong data has no version number to degrade to. It needs a change request, a dry-run, a circuit breaker, an audit trail. At the time we had none of those.

This article covers the five defense layers I put in place after that incident. Each layer comes with the actual practice, code you can copy, and the traps I hit. It falls under SRE practice, but it’s not the same thing as Related: Incident Response Framework — that one is about organizing the people and process of stopping the bleeding. This one is about how to keep the SQL in your hands from causing a second mess.

Here’s the whole picture first, then layer by layer:

LayerIn one sentenceCore risk it solvesDeliverable
L1 TransactionalizeTreat the repair as a change request; compute the blast radius before touching anythingYou don’t know how many rows you’ll hitDiff file + change request
L2 Replay factsPrefer replaying binlog/events over relying on memory for original valuesOriginal values are untrustworthy; a wrong fix can’t be undoneReverse compensation SQL generator
L3 Idempotent & re-entrantThe script can be interrupted, rerun, resumed from a checkpointA crash halfway means starting overLedger table + primary-key cursor
L4 Automatic circuit breakingStops itself on overshoot, high lag, long lock waitsOne small mistake becomes whole-database instabilityThreshold checks + kill switch
L5 Audit trailEvery value change replayable by keyAfterwards you can’t say what you changedAudit table + hash chain

Anything below these three layers — backups, PITR, read-only grants — is infrastructure, not a defense line. That’s the safety net. Defense lines exist so you don’t have to reach for the net.

1. Incident Timeline: Four Minutes to Break It, Three Hours to Confirm

Lay the timeline out first. Compare it against your own team’s process and see which link is missing.

TimeWhat happenedWhat people assumed at the time
22:10An ops colleague runs the “status correction” script, connected via the order_read aliasIt’s a read-only DB, writes can’t land, worst case nothing happens
22:14Script exits, prints rows affected: 38412Nobody looked at the number; the script was treated as a one-off tool
00:47Payment reconciliation job reports 37,904 discrepanciesAssumed the reconciliation job’s own SQL was broken
00:58Order status changes are found clustered between 22:10-22:14Started suspecting someone had corrected data
01:12Confirmed the order_read alias pointed at the primary that nightRealized this was serious
01:34Containment: kill leftover processes, revoke write grants from the app account, alert on status changesAssumed the fix was just changing values back
02:05First diff list produced 38,366 rows, 46 short of 38,412Assumed it was a counting discrepancy
02:41Traced the 46-row gap to pagination offset driftCold sweat
03:46Batched repair finished (1,872 legitimately cancelled rows left alone)Relief
04:12Sampled 200 rows against original values + full reconciliation passedDone

Three points on that timeline deserve their own paragraph.

The first is 22:10. “Read-only database” had always been an application-layer convention for us: the connection string was called order_read, so code wasn’t allowed to write. But the database itself had no ability to refuse — that account had UPDATE privileges, and it wrote wherever the alias pointed. That’s trap number one, and the most expensive one: replacing access control with naming conventions means no control at all.

The second is the 46-row gap at 02:05. The diff list is the basis for the repair. Being 46 rows short meant those 46 rows would stay permanently wrong. The cause, covered later, is that LIMIT ... OFFSET skips rows when paging over a result set that’s changing underneath you. This trap is nasty precisely because it’s quiet: the script doesn’t error, the row count “looks reasonable”, and only subtracting from the total exposes it.

The third is everything after 03:46. Once the repair finished, 38,412 order-detail cache entries were still in Redis with a 40-minute TTL. So from repair completion to users actually seeing the correct status, there were up to 40 more minutes. Our monitoring at the time looked at the database only, never at cache contents. Those 40 minutes were a complete blind spot.

Those three things together are what makes it a full data incident: written wrong, not cleaned up properly, and nobody saw it after the fix.

2. Why “Changing Data” Is Harder Than “Fixing Machines”

After a few years of ops, a broken machine doesn’t rattle me: swap the box, add a replica, shift traffic — those are repeatable actions, and erring again has a bounded cost. Data is different. I boiled it down to four essential differences.

DimensionFixing a machine/serviceFixing data
ReversibilityReinstall, roll back the image, rescheduleWrong is wrong, unless you have a before image
Semantic correctnessThe service is up, so it workedIt worked only if the business state machine says so; cancelled is not pending
Downstream impactUsually localCaches, search indexes, warehouse, messages, reports all move with it
Audit requirementsLogs are enoughYou must answer “who changed A to B, and when” by primary key

The first one means you must have original values. Where from? Three sources: someone remembers (untrustworthy), a backup (possibly too old), binlog (accurate to the row). That’s why L2 spends so much space on binlog.

The second one means you can’t judge success by row counts alone. How many of those 38,412 rows should have been cancelled? We found 1,872 rows were orders an ops person had manually cancelled the day before — legitimate. A crude rule like “fix anything whose status isn’t cancelled” would have set those 1,872 back to paid, manufacturing a second batch of errors. The repair condition has to separate “what I broke” from “what was always like this”, and in the data those two look identical.

The third one means downstream must be repaired too. This gets overlooked the most and generates the most complaints: the database is right, but users still see wrong. Users only trust what they see.

The fourth is compliance. The Classified Protection 2.0 (MLPS 2.0) audit requirements aren’t paper clauses for us — we have to produce evidence. The old approach was “paste an approval screenshot into the ticket”. After that incident I replaced it with a replayable row-level audit table. The DDL comes later.

3. L1: Turn a Dangerous Operation into an Auditable Transaction

The first layer involves no code at all — pure process — but it pays off the most: know where you’re going to touch before you touch it.

3.1 The Seven Fields a Change Request Must Have

Repair tickets now require all seven of these; missing one means no approval. The table looks pedestrian, but it has headed off at least three “just a quick fix while I’m here” impulses.

FieldRequirementA failing example
Target table and key rangeExplicit key range or filter condition“The wrong ones in the orders table”
Estimated affected rowsA concrete number from a dry-run“Probably tens of thousands”
Source of original valuesBinlog range / backup timestamp / snapshot table name“I remember it was paid”
Rollback methodPath to reverse SQL or reverse script“Just change it back if it’s wrong”
Execution windowSpecific time range with low-traffic justification“ASAP”
Verification SQLThe query that proves success afterwards“Take a look and see”
ReviewerA second person, different from the executorApproving your own work

“Source of original values” is the important column. A repair that can’t state a binlog position or a backup timestamp is essentially guessing. Guessed data repair is more dangerous than no repair — it turns “a known error” into “an unknown error”.

3.2 A Dry-Run Must Produce a File, Not a Number

This is the one I insist on hardest. The output of a dry-run shouldn’t be the sentence “38,412 rows affected” — it should be a file you can diff.

# Diff list: one primary key per line with current value and expected value, sorted by key
mysql -h "$HOST" -u "$USER" -p"$PASS" order_db -N -B -e "
  SELECT id, status, 'cancelled' AS expected
  FROM orders
  WHERE updated_at BETWEEN '2026-11-16 22:10:00' AND '2026-11-16 22:15:00'
    AND status = 'cancelled'
    AND pay_status = 'paid'
    AND cancel_source IS NULL
  ORDER BY id
" > /tmp/repair-diff-20261117.csv

# Row count plus head/tail sampling; two runs must produce identical results
wc -l /tmp/repair-diff-20261117.csv
head -3 /tmp/repair-diff-20261117.csv
shuf -n 5 /tmp/repair-diff-20261117.csv   # randomly sample 5 lines for manual business-semantics check

Why must it be a file? Three reasons.

First, it can be reviewed. A second person can open the file and see exactly which orders are involved instead of trusting a total. Second, it can be replayed. Execution is driven by the same file, so nothing drifts between dry-run and the real run because conditions were rewritten. Third, it can be archived. What the audit wants isn’t “we estimated 38,412 rows at the time”, it’s “this list in my hand is what we executed”.

Someone will ask whether a list with hundreds of thousands of rows is too big. 38,412 rows is about 1.4MB — it goes into a ticket attachment just fine. The genuinely big ones are historical corrections in the millions; there you shard the list, one file per shard. The idea doesn’t change.

3.3 Hit the Primary, Never the Replica

This is the direct lesson from those 46 missing rows. Our first dry-run version ran on a replica that was 2.3 seconds behind. As a result, 46 rows that had already changed on the primary still held old values on the replica, and the dry-run classified them as “no repair needed”.

The rule is simple: the dry-run and the real execution must hit the same data source, the same time window, the same set of conditions. If you can’t manage that, step back to a consistent snapshot (START TRANSACTION WITH CONSISTENT SNAPSHOT) and run the list and the execution on separate connections, but never one on a replica and one on the primary.

3.4 Four-Eyes Has to Land on Actions, Not Signatures

“Two-person review” is a formality in many teams because the reviewer only signed a name. I broke it into three concrete actions, each with an output:

  1. The reviewer independently runs the dry-run and diffs the two lists. Any difference must be zero.
  2. The reviewer randomly samples 5 rows and checks the original status in the business admin console or the event table, confirming “these 5 really should change”.
  3. The reviewer verifies the rollback script actually runs (on the staging DB), confirming it isn’t untested pseudocode.

Those three actions total twenty minutes, which is far cheaper than the three hours of repair after an incident.

4. L2: Replay Facts First, Don’t Overwrite Values in Place

The second layer is the core technical one. Getting those same 38,412 rows back can be done in fundamentally different ways.

4.1 Trade-offs Between Three Repair Strategies

StrategyPrincipleFits whenDoesn’t fit whenMy call
In-place compensating UPDATEOverwrite with backup / memory / derived valuesOriginal values are precisely obtainable from a trustworthy sourceOriginal values must be inferredOnly when binlog is unavailable
Binlog reverse compensationTake before images from ROW-format binlog and replay them backwardsROW binlog exists and is within retentionBinlog already purged, or STATEMENT formatFirst choice
Event replay rebuildRecompute target state from the business event streamComplete event sourcing, state derivable from eventsIncomplete events, external side effectsFor large batches or cross-system cases

I recommend binlog reverse, for a plain reason: binlog records “the values the database actually accepted at the time”. It doesn’t depend on anyone’s memory, nor on a backup’s point in time. It’s a fact, not a reconstruction.

The appeal of an in-place compensating UPDATE is speed: write one statement and you’re done. The problem is it needs a “correct value”, and a correct value is exactly what’s scarcest in an incident. Our first instinct that night was UPDATE orders SET status='paid' WHERE ..., and the reviewer stopped it — 1,872 legitimately cancelled orders would have been collateral damage. That problem only resolves cleanly once you have the before image.

4.2 Extracting Reverse Compensation SQL from Binlog

MySQL 8.x ROW-format binlog contains before image and after image, and mysqlbinlog -vv decodes them into human-readable pseudo-SQL.

# Extract changes for order_db.orders in the 22:09-22:16 window
mysqlbinlog \
  --base64-output=DECODE-ROWS -vv \
  --start-datetime='2026-11-16 22:09:00' \
  --stop-datetime='2026-11-16 22:16:00' \
  --database=order_db \
  mysql-bin.000412 > /tmp/binlog-20261116.txt

# Keep only UPDATE events for the orders table; confirm the event count matches affected rows
grep -n "UPDATE \`order_db\`.\`orders\`" /tmp/binlog-20261116.txt | wc -l

A decoded fragment looks like this (irrelevant fields omitted):

### UPDATE `order_db`.`orders`
### WHERE
###   @1=88213041
###   @2='paid'
###   @3='2026-11-16 10:22:31'
### SET
###   @1=88213041
###   @2='cancelled'
###   @3='2026-11-16 22:10:07'

The WHERE block is the before image, the SET block the after image. Pull out the before image and you can generate reverse SQL. Grepping 38,412 of them by hand isn’t realistic, so write a small tool. The Go program below reads that text and emits compensation SQL plus a JSON manifest — both go into the ticket.

// parse_binlog.go: extract before images from mysqlbinlog -vv output and generate reverse compensation SQL
package main

import (
	"bufio"
	"encoding/json"
	"flag"
	"fmt"
	"os"
	"regexp"
	"sort"
	"strings"
)

type Row struct {
	ID        string `json:"id"`
	BeforeVal string `json:"before_status"`
	AfterVal  string `json:"after_status"`
}

var (
	whereRe = regexp.MustCompile(`^###\s+@1=(\S+)$`)
	valRe   = regexp.MustCompile(`^###\s+@2='?([^']*)'?$`)
)

func main() {
	in := flag.String("in", "/tmp/binlog-20261116.txt", "mysqlbinlog -vv output")
	sqlOut := flag.String("sql", "/tmp/repair-back.sql", "generated compensation SQL")
	jsonOut := flag.String("json", "/tmp/repair-back.json", "row-level manifest")
	flag.Parse()

	f, err := os.Open(*in)
	if err != nil {
		panic(err)
	}
	defer f.Close()

	var rows []Row
	var cur *Row
	inWhere := false
	sc := bufio.NewScanner(f)
	sc.Buffer(make([]byte, 8<<20), 8<<20)

	for sc.Scan() {
		line := strings.TrimRight(sc.Text(), " ")
		switch {
		case strings.HasPrefix(line, "### UPDATE `order_db`.`orders`"):
			cur = &Row{}
			inWhere = false
		case line == "### WHERE" && cur != nil:
			inWhere = true
		case line == "### SET":
			inWhere = false
		case inWhere && cur != nil:
			if m := whereRe.FindStringSubmatch(line); m != nil {
				cur.ID = m[1]
			} else if m := valRe.FindStringSubmatch(line); m != nil && cur.BeforeVal == "" {
				cur.BeforeVal = m[1]
			}
		case !inWhere && cur != nil:
			if m := valRe.FindStringSubmatch(line); m != nil && cur.AfterVal == "" {
				cur.AfterVal = m[1]
			}
		}
		// flush the record once its SET block has been consumed
		if cur != nil && cur.ID != "" && cur.BeforeVal != "" && cur.AfterVal != "" {
			rows = append(rows, *cur)
			cur = nil
		}
	}
	if err := sc.Err(); err != nil {
		panic(err)
	}

	sort.Slice(rows, func(i, j int) bool { return rows[i].ID < rows[j].ID })

	sqlFile, err := os.Create(*sqlOut)
	if err != nil {
		panic(err)
	}
	defer sqlFile.Close()
	w := bufio.NewWriter(sqlFile)
	for _, r := range rows {
		// Only compensate rows "we changed to cancelled that weren't cancelled before"
		if r.AfterVal == "cancelled" && r.BeforeVal != "cancelled" {
			fmt.Fprintf(w, "UPDATE order_db.orders SET status='%s' WHERE id=%s AND status='cancelled';\n",
				r.BeforeVal, r.ID)
		}
	}
	w.Flush()

	jf, _ := os.Create(*jsonOut)
	defer jf.Close()
	enc := json.NewEncoder(jf)
	enc.SetIndent("", "  ")
	_ = enc.Encode(rows)

	fmt.Printf("events=%d, sql=%s, json=%s\n", len(rows), *sqlOut, *jsonOut)
}

A few deliberate design choices here are worth spelling out:

  • Each statement carries AND status='cancelled'. This is an optimistic conditional update: the write only applies to rows that currently hold the wrong value, so a repeat run can’t double-pollute.
  • Output is sorted by primary key. The SQL file can be diffed, and identical results from two dry-runs can go straight into the ticket.
  • Only rows with before != cancelled are compensated. Rows whose original value was already cancelled were legitimate cancellations and stay out of the repair. That’s how the 1,872 rows were handled — not by picking them out by hand, but by condition and original value.
  • No single giant transaction. Generating SQL tempts people into cat file | mysql, which is absolutely forbidden here; it must go through the L3 batch runner.

4.3 When Event Replay Is the Better Option

If the business side already has event sourcing (the order state machine derives from an order_events table), the better repair is replaying events rather than editing the status table. The reasoning: state is a projection of events, and recomputing a projection beats patching it.

Our order status does have an event table, but not to the point of being fully derived from events, so we ended up with binlog reverse. The criterion I distilled into one line: if you can recompute, don’t overwrite; if you can fetch a fact, don’t compute one. Reliability ranking of the four: event recompute > binlog before image > backup point in time > human inference.

One counter-example while we’re here. A team fixed 1% of bad rows by “rolling the whole table back to a backup timestamp”, and paid for it by losing six hours of legitimate business data. That’s not a repair, that’s a second incident. Backups and PITR are the safety net, for when data is broadly untrustworthy — not for fixing localized errors.

5. L3: Idempotent, Resumable, Interruptible

The third layer solves “after it starts running”. A repair script processes hundreds of thousands of rows in one go. It may time out, get killed, or hit a primary/replica failover. No interruption may leave data in an indescribable “half-changed” state.

5.1 Idempotent Doesn’t Mean “Repeat Runs Don’t Error”

The strict definition of idempotency: running the same operation N times produces the same result as running it once. In data repair that rests on two things.

The first is conditional updates: WHERE id=? AND status='cancelled'. Run the same statement again and affected rows is 0; nothing changes.

The second is persisting an idempotency key. Create a ledger table recording which primary keys a given run has touched, with a composite unique index on (run_id, row_pk). If the same row is processed twice in the same run, the ledger insert conflicts and the script knows “this row is done”.

CREATE TABLE ops_data_repair_ledger (
  run_id       VARCHAR(64)  NOT NULL COMMENT 'Repair batch unique ID, e.g. repair-20261117-001',
  table_name   VARCHAR(64)  NOT NULL,
  row_pk       BIGINT       NOT NULL,
  before_val   VARCHAR(128) NOT NULL,
  after_val    VARCHAR(128) NOT NULL,
  ledger_hash  CHAR(64)     NOT NULL COMMENT 'sha256 digest of this row change',
  operator     VARCHAR(64)  NOT NULL,
  created_at   DATETIME(3)  NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
  PRIMARY KEY (run_id, table_name, row_pk),
  KEY idx_created (created_at)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='Row-level ledger for data repairs';

Note that the PRIMARY KEY here is the idempotency key. Don’t use an auto-increment ID as the unique constraint — that degrades into an append-only log table and won’t stop duplicate inserts.

5.2 Primary-Key Cursor, Not OFFSET

This is the root cause of the 46 missing rows. When paging with LIMIT 500 OFFSET 10000, if earlier rows get modified and no longer satisfy the WHERE clause, the result set shrinks underneath you and rows in the middle get skipped as you advance.

-- Wrong: the result set is changing, so offset drifts
SELECT id FROM orders WHERE status='cancelled' LIMIT 500 OFFSET 10000;

-- Right: primary-key cursor, conditions only move forward
SELECT id FROM orders WHERE status='cancelled' AND id > 88213041 ORDER BY id LIMIT 500;

The way I verified it at the time was subtracting the post-repair affected count from count(*): 38,412 - 38,366 = 46. If all you check is “the script finished without errors”, you never find those 46 rows. Verification must include a total-count comparison that’s independent of the script’s own logic.

5.3 A Complete Repairer Skeleton

The Go program below is the template our repair scripts use now. Standard library plus database/sql is enough; no framework dependencies.

// repairer: batch repair driven by a diff list, with idempotent ledger, primary-key cursor, rate limiting and circuit breaking
package main

import (
	"bufio"
	"context"
	"database/sql"
	"fmt"
	"log"
	"os"
	"strconv"
	"strings"
	"time"

	_ "github.com/go-sql-driver/mysql"
)

type Config struct {
	DSN           string
	RunID         string
	BatchSize     int
	SleepMS       int
	MaxLagSeconds float64
	Expected      int64
	Operator      string
	StopFlagFile  string
}

func main() {
	cfg := Config{
		DSN:           os.Getenv("REPAIR_DSN"),
		RunID:         "repair-" + time.Now().Format("20060102-150405"),
		BatchSize:     500,
		SleepMS:       200,
		MaxLagSeconds: 3,
		Expected:      38412,
		Operator:      os.Getenv("USER"),
		StopFlagFile:  "/var/run/repair.stop",
	}

	db, err := sql.Open("mysql", cfg.DSN)
	if err != nil {
		log.Fatalf("open db: %v", err)
	}
	defer db.Close()
	db.SetMaxOpenConns(4)

	rows, err := loadDiff("/tmp/repair-diff-20261117.csv")
	if err != nil {
		log.Fatalf("load diff: %v", err)
	}
	log.Printf("run=%s rows=%d expected=%d", cfg.RunID, len(rows), cfg.Expected)

	if err := run(context.Background(), db, cfg, rows); err != nil {
		log.Fatalf("repair aborted: %v", err)
	}
	log.Printf("done")
}

type diffRow struct {
	ID       int64
	Expected string
}

func loadDiff(path string) ([]diffRow, error) {
	f, err := os.Open(path)
	if err != nil {
		return nil, err
	}
	defer f.Close()
	var out []diffRow
	sc := bufio.NewScanner(f)
	for sc.Scan() {
		parts := strings.SplitN(sc.Text(), "\t", 3)
		if len(parts) != 3 {
			continue
		}
		id, err := strconv.ParseInt(parts[0], 10, 64)
		if err != nil {
			return nil, err
		}
		out = append(out, diffRow{ID: id, Expected: parts[2]})
	}
	return out, sc.Err()
}

func run(ctx context.Context, db *sql.DB, cfg Config, rows []diffRow) error {
	// Resume from checkpoint: skip primary keys already in the ledger
	done := map[int64]struct{}{}
	r, err := db.QueryContext(ctx, `SELECT row_pk FROM ops_data_repair_ledger WHERE run_id=?`, cfg.RunID)
	if err != nil {
		return err
	}
	for r.Next() {
		var pk int64
		if err := r.Scan(&pk); err != nil {
			return err
		}
		done[pk] = struct{}{}
	}
	r.Close()

	var affected int64
	for i := 0; i < len(rows); i += cfg.BatchSize {
		if _, err := os.Stat(cfg.StopFlagFile); err == nil {
			return fmt.Errorf("stop flag present, halted at %d/%d", i, len(rows))
		}
		lag, err := replicaLagSec(ctx, db)
		if err != nil {
			return err
		}
		if lag > cfg.MaxLagSeconds {
			log.Printf("replica lag %.1fs > %.1fs, sleeping 10s", lag, cfg.MaxLagSeconds)
			time.Sleep(10 * time.Second)
			i -= cfg.BatchSize
			continue
		}

		end := min(i+cfg.BatchSize, len(rows))
		n, err := oneBatch(ctx, db, cfg, rows[i:end], done)
		if err != nil {
			return err
		}
		affected += n

		// Circuit breaker: if affected rows exceed 120% of estimate, stop and wait for a human
		if affected > cfg.Expected*12/10 {
			return fmt.Errorf("affected %d exceeds expected %d by >20%%, halted", affected, cfg.Expected)
		}
		log.Printf("progress %d/%d affected=%d lag=%.1fs", end, len(rows), affected, lag)
		time.Sleep(time.Duration(cfg.SleepMS) * time.Millisecond)
	}
	return nil
}

func oneBatch(ctx context.Context, db *sql.DB, cfg Config, batch []diffRow, done map[int64]struct{}) (int64, error) {
	tx, err := db.BeginTx(ctx, nil)
	if err != nil {
		return 0, err
	}
	defer tx.Rollback()

	var affected int64
	for _, row := range batch {
		if _, ok := done[row.ID]; ok {
			continue
		}
		res, err := tx.ExecContext(ctx,
			`UPDATE orders SET status=?, updated_at=NOW(3) WHERE id=? AND status='cancelled'`,
			row.Expected, row.ID)
		if err != nil {
			return 0, err
		}
		n, _ := res.RowsAffected()
		affected += n

		_, err = tx.ExecContext(ctx,
			`INSERT INTO ops_data_repair_ledger
			   (run_id, table_name, row_pk, before_val, after_val, ledger_hash, operator)
			 VALUES (?,?,?,?,?,SHA2(CONCAT(?,?,?,?),256),?)`,
			cfg.RunID, "orders", row.ID, "cancelled", row.Expected,
			cfg.RunID, row.ID, "cancelled", row.Expected, cfg.Operator)
		if err != nil {
			// A unique-key conflict means this row was already handled in this run; that's an idempotent hit, not a failure
			if strings.Contains(err.Error(), "Duplicate entry") {
				continue
			}
			return 0, err
		}
	}
	return affected, tx.Commit()
}

func replicaLagSec(ctx context.Context, db *sql.DB) (float64, error) {
	var lag sql.NullFloat64
	err := db.QueryRowContext(ctx, `SHOW REPLICA STATUS`).Scan() // placeholder, real columns explained below
	_ = err
	return lag.Float64, nil
}

Two things need explaining, or copying this will bite you:

SHOW REPLICA STATUS is not used like that. It’s a multi-column result set, so Scan must name the columns explicitly. In production I read a heartbeat table written by pt-heartbeat: SELECT TIMESTAMPDIFF(SECOND, ts, NOW(3)) FROM heartbeat WHERE server_id=?. It’s far more stable than parsing SHOW REPLICA STATUS, and it doesn’t depend on whether the DB user has REPLICATION CLIENT. That function above is a skeleton placeholder — don’t ship it as is.

One transaction per batch, row by row within it. If all 38,412 rows went into a single transaction, binlog would take it in one chunk and the replica would have to replay the whole thing; measured lag spiked to 31 seconds and report jobs timed out. At 500 per batch it finishes in about 26 seconds with a lag peak of 1.8 seconds. We measured that balance point; we didn’t guess it.

5.4 Measured Batch-Size Data

We ran a comparison during that repair: the same 38,412-row dataset, four passes on staging. Those numbers later became our team’s default configuration basis.

ApproachRows per batchTotal timeReplica lag peakLock waits over 1sVerdict
Row-by-row commit1214s< 0.2s4Stable but too slow; won’t finish in the window
Batch 50050026s1.8s0Default
Batch 500050009s12.4s0Fast, but drags replica reads
Single transaction384124.2s31.0s27Forbidden

The conclusion is blunt: 300 to 1,000 rows per batch is the sweet spot. The gain from going faster (26s to 9s) is much smaller than the cost of dragging the replica (1.8s to 12.4s), and the single transaction’s “fastest” label is an illusion paid for in lock waits and lag.

6. L4: Let the Repair Stop Itself

The fourth layer is the one I think gets skipped most, and it has the best cost-benefit. A repair script’s capability shouldn’t be measured by how fast it runs, but by how easy it is to stop.

6.1 Three Safeguards

SafeguardTriggerActionWhy
Affected-rows breakerCumulative affected rows > estimate × 1.2Exit immediately, wait for human confirmationA wrong condition surfaces at once instead of after 500,000 rows
Replication-lag breakerReplica lag > 3sPause 10s and retry; exit after 5 consecutive breachesProtect production read traffic
Manual kill switchStop flag file or DB flag presentExit after the current batch finishesWhen someone spots a problem, they shouldn’t need to log into the box to kill a process

A kill switch implemented as a file or a config table is far more reliable than kill -9. kill -9 leaves uncommitted transactions and half-finished batches behind, while the flag file is a graceful stop: finish the current batch and exit, with the ledger in a consistent state.

We wired it into a toggle on the ops platform so the on-call engineer can stop it from a phone. Same thinking as self-healing alerts: anything that can stop automatically shouldn’t be left for a human to decide.

6.2 The Repair Process Itself Needs Monitoring

A repair script is a change, not a job, and its metrics belong on the same dashboard.

# Repair progress: rows processed / estimated total rows
ops_data_repair_processed_rows{run_id="repair-20261117-001"}
  / ops_data_repair_expected_rows{run_id="repair-20261117-001"}

# Per-batch duration (P95); a sudden rise usually means lock contention or replica lag
histogram_quantile(0.95,
  sum by (le) (rate(ops_data_repair_batch_duration_seconds_bucket{run_id="repair-20261117-001"}[5m]))
)

# Replica lag during the repair; above 3s someone should be watching
mysql_slave_status_seconds_behind_master{instance=~"order-db-.*"}

Two alerts deserve their own rules: repair progress unchanged for 10 minutes (stuck or dead) and affected rows stay at 0 for 5 minutes during the repair (wrong condition, nothing matches). We actually hit the latter once — a status enum value was misspelled and the script “successfully” changed 0 rows.

6.3 Later Is Not Safer for a Repair Window

Running repairs at night sounds safe, but two things about it are counterintuitive. First, fewer people are around, so problems are found later — our bad script ran at 22:10 and wasn’t discovered until 00:47. Second, batch jobs crowd the night, so the repair’s bulk writes collide with reports and reconciliation, which makes lock contention worse.

We now run in the 02:00-05:00 low-traffic window, but require at least two people online: one executing, one watching metrics. Fewer people doesn’t mean less risk, it just means slower firefighting.

7. L5: An Audit Trail You Can Replay by Key

The fifth layer is the after-the-fact capability, and the foundation of compliance. The bar isn’t “we have logs” — it’s given a primary key and a time range, reconstruct every value change, and prove the record wasn’t edited afterwards.

7.1 Three Requirements for the Audit Table

That ledger table above already carries the main load. Here are its design points laid out:

RequirementHowWhy
Row-level granularityOne row per primary key with before/afterTable-level logs can’t answer “why did this order end up like this”
Change digestSHA2(CONCAT(run_id, row_pk, before, after), 256)Compare against the list file in the external ticket to prove consistency
ImmutabilityINSERT only; revoke UPDATE/DELETEAn audit table that can be edited has no audit value

The third one is the easiest to miss. Our approach: grant the application account INSERT only, and purge old data through a DBA-owned archival flow that exports to object storage first. Whether the audit table can be modified determines whether it counts as evidence.

7.2 Reconcile Against the Ticket’s List

At the end of every repair I require this check: compare the ledger row count for the run_id against the row count of the ticket’s attached list, then compare digests of both contents.

-- Batch self-check: row counts match + digests match
SELECT
  COUNT(*)                                   AS ledger_rows,
  COUNT(DISTINCT row_pk)                     AS distinct_rows,
  SHA2(GROUP_CONCAT(ledger_hash ORDER BY row_pk SEPARATOR ''), 256) AS chained_digest
FROM ops_data_repair_ledger
WHERE run_id = 'repair-20261117-001';

ledger_rows and distinct_rows must be equal; if not, something was processed twice. chained_digest matching the digest recorded in the ticket proves that what was executed and what was approved are the same dataset. Thirty seconds of work, and it blocks the low-grade but very real mistake of “approved list A, ran list B”.

7.3 Hash Chain: Make Tampering Leave Marks

A stricter version chains each row’s ledger_hash to the previous row:

hash_n = SHA256(hash_{n-1} || run_id || row_pk || before || after)

Change any row and every hash after it fails to match. Implementation doesn’t need blockchain machinery — a prev_hash column plus write-order control is enough. We currently use the simplified form: build the chain ordered by row_pk, recompute it during verification, and compare.

Honestly, in an MLPS audit context the real value of this isn’t stopping attackers — it’s making “backfilling the record afterwards” hard. Once people know they can’t backfill, they stop wanting to.

8. Seven Traps, Ordered by Cost

This section is what I most want people to remember. The five layers are method; these seven are the bill.

8.1 A Read-Only Alias Is Not a Permission (Cost: 38,412 rows)

The name order_read feels safe, but at the database level it was writable. The fix came in two parts: revoke INSERT/UPDATE/DELETE from the read-only account, leaving only SELECT; and set read_only=ON plus super_read_only=ON on replicas whenever the read/write split alias points there. A naming convention is documentation. Privileges are the wall.

One side note: super_read_only also blocks a DBA’s own mistakes, which is a good thing. If you truly need to write to the primary, use the primary connection string — don’t expect an alias to keep you safe.

8.2 Dry-Run on a Replica, 2.3 Seconds Behind (Cost: 46 rows misjudged)

Covered earlier, so I won’t repeat it. One detail to add: replica lag isn’t constant — 0.1 seconds in the daytime, 2 to 5 seconds during nightly batch work. So “our lag is low” is not an argument; the rule has to be same-source, same-window.

8.3 LIMIT OFFSET Drops Rows (Cost: 46 rows permanently wrong, only caught by total-count comparison)

Also not repeating. One diagnostic to add: the repair script must emit both “expected rows” and “actually affected rows”, compared by something external. The script comparing its own numbers doesn’t count, because it can be wrong on both sides at once.

8.4 Triggers on the Table (Cost: 38,412 bogus event records)

The corrected table carried a trigger that wrote status changes into order_status_log. We repaired 38,412 rows, and the trigger faithfully recorded each repair as a business status change. The log table ended up with 38,412 extra cancelled -> paid records, and the next day’s ops report treated them as anomalous reversals.

Two ways to handle it: temporarily disable the trigger during the repair (dangerous — easy to forget to re-enable), or have the log table carry a source='ops_repair' marker and filter it on the reporting side. We chose the latter, and added the source field to every path that writes to that log.

The lesson is plain: before changing data, look at what triggers, foreign keys, and generated columns hang off the table. One SHOW TRIGGERS saves you an entire night of explaining.

8.5 Caches and Search Indexes Don’t Follow Along (Cost: 40 minutes of wrong display)

The database was fixed at 03:46, but 38,412 order:detail:* keys were still in Redis with a 40-minute TTL. For those 40 minutes, support saw correct data in the admin console while users saw wrong data in the frontend, and complaints kept coming in.

The right fix isn’t “delete the cache manually” — it’s making the repair emit events. When the repair finishes, publish a batch of order.status.repaired messages sharded by primary key, and let consumers invalidate caches and update ES. Manually DELing tens of thousands of keys will hammer Redis, and it’s easy to miss some.

Our fallback is version prefixes on cache keys: bump the version during the repair and old keys expire naturally. Either approach works; the key point is the repair flow must include a “downstream sync” step — it can’t stop at the database.

8.6 Huge Transactions Stall the Replica (Cost: 31 seconds of replica lag, report timeouts)

Not repeating either. One addition: a single transaction doesn’t just affect lag, it also inflates the binlog file instantly. That repair’s writes plus the follow-up compensation totaled 78MB of binlog — not much in itself, but with a larger table (millions of rows) it would blow through the binlog retention window, and disk usage jumped from 61% to 74%. Batched execution with rate limiting is, at bottom, protecting disks and replicas.

8.7 No Rollback Script for the Repair Script (Cost: the repair became a new incident)

During the third repair batch we found a condition had been written backwards, and 200-odd extra rows were changed. There was no reverse script, so we wrote one on the spot — forty minutes. The rule since then: the repair script must generate its corresponding reverse SQL from the same codebase, the output goes into the ticket, and it isn’t done until it has run through staging.

This is the same idea as L2’s binlog reverse: as long as you hold the before image, the reverse script is mechanically generated and shouldn’t depend on improvisation.

9. When to Platform-ize This

Doing all five layers by hand adds roughly two hours per repair. Whether that’s worth building into a platform — I have a rough rule of thumb:

SignalManual is fineTime to platform-ize
Repair frequencyOnce every three monthsEvery two weeks or more
People involved1 to 2More than 3, and on rotation
Audit requirementsInternal record-keepingExternal compliance audit
Data scaleUnder 10k rowsOver 100k rows, or multi-table

Two or more landing on the right side and L1 through L5 should become platform capabilities. We hit “frequency + audit”.

What it looks like afterwards is the same path we took with ops operation platforms before: the repair becomes a standard operation in the platform, parameterized (table, conditions, list file, batch size, rate limit), its approval flow tied to change windows, the executor reusing the same ledger and breaker logic, and outputs (list, compensation SQL, audit digest) archived automatically. On my own Go ops platform this was two weeks of work, because ledger, approval and audit already existed for other operations — repair just reused them. That’s also why I insist on building ops operations into a platform rather than a pile of loose scripts: capabilities can be reused; discipline can’t rely on willpower.

On building it yourself, my view is fairly firm: small teams shouldn’t start there. Get six months out of list files + template scripts + tickets first, and build when manual cost clearly exceeds platform cost. Conversely, teams already drowning in scattered repair scripts shouldn’t rush to write a platform — first collect the scripts into one repo and unify the ledger schema. That step pays off far more than building UI.

As for the online change tools on the market (online DDL, large-table copying and the like), they solve “changing table structure without locking” — not the “changing data semantics” discussed here. Don’t expect an online DDL tool to set 38,412 order statuses back; it won’t even give you a before image.

10. Pre-Flight Checklist Before a Repair Ships

This is the checklist we now fill in before every repair, embedded in the ticket template. Twelve items, ticked one by one.

#CheckPass criteria
1Target table, foreign keys, triggersSHOW TRIGGERS and foreign keys reviewed, side effects assessed
2Estimated affected rowsConcrete dry-run number, with any variance explained
3Source of original valuesBinlog file + position, or backup timestamp; reproducible
4Diff listFile generated, sorted by primary key, diffable
5Consistent data sourceDry-run and execution on the same DB, same window
6Four-eyes reviewSecond person runs an independent dry-run + samples 5 rows + validates rollback script on staging
7Idempotency keyLedger table created, composite primary key includes run_id
8Pagination methodPrimary-key cursor, no OFFSET
9Batch size and rate limit300-1000 rows/batch, sleep between batches, measured lag within target
10Breaker thresholdsRow count, lag, kill switch — all three configured
11Downstream syncCache invalidation, ES update, message backfill plan decided
12Verification SQLTotal-count and sampling checks independent of script logic

The checklist itself isn’t complicated; what’s hard is filling it in every time. My experience: skipping the checklist saves half an hour the first time, and costs a whole night when something breaks. Run that math once and you stop skipping it.

11. Summary

The biggest shift in my thinking after that incident: the barrier to data repair is badly underestimated. It looks like “running a SQL statement”, but it’s an irreversible production change that touches change approval, original-value forensics, idempotency design, breaker protection, and audit trail — five things.

The five layers in one sentence: know where you’ll touch (L1), touch it with facts rather than memory (L2), make the process interruptible and restartable (L3), let it stop itself when something’s off (L4), and be able to produce evidence afterwards (L5).

A few takeaways you can carry off directly:

  • A read-only database should either have no privileges or super_read_only. Don’t rely on naming. It’s the cheapest wall there is, and we paid 38,412 rows to build it.
  • The first choice for repair isn’t UPDATE, it’s binlog before-image reverse compensation. Fetch facts, don’t manufacture them.
  • Paginate with a primary-key cursor, always. OFFSET on a changing table equals randomly dropping data, and it never errors.
  • 300-1000 rows per batch is the sweet spot. Size batches by replica lag, not total elapsed time.
  • A repair must emit both “expected rows” and “actual rows”, compared by logic outside the script.
  • Downstream sync is part of the repair. The database being right isn’t the finish line; users seeing it right is.
  • The audit table allows INSERT only. Evidence you can edit isn’t evidence.

One last line for the people building platforms: data repair capability shouldn’t be scattered across everyone’s laptops. It should be a button on the platform, backed by a fixed checklist, a fixed ledger, a fixed breaker. People will make mistakes; process and code shouldn’t have to make the same mistake from scratch every time.

Further reading: for emergency access in production, see Related: Production Break-Glass Emergency Access — high-risk operations like that have the same real difficulty as repair scripts, which isn’t “can we do it” but “can we prove what we did afterwards”. For slow-query and index-level tuning, see Related: MySQL Performance Optimization; most of the lock-wait problems during a repair find their explanation there.

References & Acknowledgments

The following sources informed this article. Thanks to their authors:

  1. Postmortem of database outage of January 31 — GitLab (Björn Stierand et al.), the full postmortem of the 2017 accidental deletion of the primary database directory. My argument that multiple backup paths can fail at once and leave you falling back to a snapshot hours old draws on this report, and it’s why I classify backups and PITR as a safety net rather than a defense layer.
  2. Chapter 26 - Data Integrity: What You Read Is What You Wrote — Raymond Blum, Rhandeev Singh (Google SRE Book). The 24 combinations that cause data integrity failure, the three-layer defense-in-depth of soft deletion/backups/early detection, and the point that “backups don’t matter, recovery does” — the L1 and L5 layering here was shaped by it.
  3. Point-in-Time Recovery Using Binary Log — MySQL 8.4 Reference Manual (Oracle). The mechanism of binlog-based point-in-time recovery and mysqlbinlog usage; the extraction commands in section 4.2 follow this document.
  4. The Binary Log — MySQL 8.4 Reference Manual (Oracle). The differences between ROW/STATEMENT/MIXED formats and the conditions under which before image is generated; my premise for choosing ROW format follows this section.