Skip to lesson

ShopLite's code can always be rebuilt from Git, but customers and orders live only in the database. One wrong DELETE or a lost server, and they are gone unless a backup exists.

Managed backups and point-in-time recovery

PITR (point-in-time recovery) restores a database as it was at a chosen second. It replays the binary log, the server's change log, on top of the latest snapshot, a daily copy of the database.

A managed MySQL service keeps a daily snapshot and the change log in between. The program below replays the changes on top of a snapshot, stopping one second before a bad DELETE.

Example 1 · Point-in-time recovery: snapshot plus replayed changes

PitrDemo.javaJava
import java.time.LocalTime;import java.util.List;import java.util.TreeMap;
record Change(LocalTime time, String sql, int ordersAfter) {}
public class PitrDemo {    public static void main(String[] args) {        int ordersInSnapshot = 1200;                  // nightly snapshot at 02:00        List<Change> binlog = List.of(                new Change(LocalTime.parse("09:15:02"), "INSERT order 1201", 1201),                new Change(LocalTime.parse("10:40:30"), "INSERT order 1202", 1202),                new Change(LocalTime.parse("10:59:00"), "DELETE FROM orders  (no WHERE!)", 0),                new Change(LocalTime.parse("11:05:12"), "INSERT order 1203", 1));
        TreeMap<LocalTime, Integer> state = new TreeMap<>();        state.put(LocalTime.parse("02:00"), ordersInSnapshot);        binlog.forEach(c -> state.put(c.time(), c.ordersAfter()));
        for (String target : List.of("10:58:59", "11:00:00", "11:10:00")) {            LocalTime t = LocalTime.parse(target);            System.out.println("Restore to " + target + " -> " + state.floorEntry(t).getValue() + " orders");        }        System.out.println("Best target: one second before the DELETE, then re-enter order 1203 by hand");    }}
Output
Restore to 10:58:59 -> 1202 orders
Restore to 11:00:00 -> 0 orders
Restore to 11:10:00 -> 1 orders
Best target: one second before the DELETE, then re-enter order 1203 by hand

What this code does

  • A simplified model of PITR: start from the 02:00 snapshot and replay every logged change up to the chosen time. floorEntry finds the last change at or before the target.
  • Restoring to 10:58:59 keeps every order placed that morning and skips the bad DELETE; anything after the target (order 1203) must be recovered separately.

Snapshots and logs are kept for a retention period, often 7 days by default and up to about a month. The restore usually creates a new database server, and you point the app at it.

Know what they do not cover. A mistake found after the retention period is gone for good. On some providers, deleting the instance also deletes its automatic backups. And they live with the same provider and account: a locked account or an attacker with your admin login can take the backups along with the data, so you also keep your own copy.

mysqldump from a container, restore into a fresh one

A logical backup is a SQL file with the CREATE TABLE and INSERT statements that rebuild a database. mysqldump writes one, and you restore it by feeding the file to a fresh MySQL server.

You do not need to install mysqldump: the mysql:8.4 image contains it. The commands below dump the managed database from a one-off container, then restore into a fresh one.

Example 2 · Dump from the managed database, restore into a fresh container

Runs in: a terminal on the VM with Docker; the VM's IP is allowed by the managed database

Terminal
# Backup: MYSQL_PWD holds the backup user's password (exported, never typed on the command line)docker run --rm -e MYSQL_PWD mysql:8.4 \  mysqldump --host="$DB_HOST" --user=shoplite_backup --ssl-mode=REQUIRED \  --single-transaction --no-tablespaces --set-gtid-purged=OFF --triggers \  shoplite | gzip > shoplite-20261016.sql.gzls -lh shoplite-20261016.sql.gz# Restore test: a throwaway MySQL with a random root passworddocker run -d --name restore-test -e MYSQL_RANDOM_ROOT_PASSWORD=yes -e MYSQL_DATABASE=shoplite \  -e MYSQL_USER=restore -e MYSQL_PASSWORD=restore-only mysql:8.4until docker exec restore-test mysqladmin ping -h127.0.0.1 -urestore -prestore-only --silent; do sleep 2; donegunzip -c shoplite-20261016.sql.gz | docker exec -i restore-test mysql -urestore -prestore-only shoplitedocker exec restore-test mysql -urestore -prestore-only shoplite -e \  "SELECT COUNT(*) AS orders FROM orders; SELECT MAX(version) AS flyway FROM flyway_schema_history;"docker rm -f restore-test
Sample output
-rw-r--r-- 1 deploy deploy 412K Oct 16 20:30 shoplite-20261016.sql.gz
3f1e1c8b0d6a...
mysqladmin: [Warning] Using a password on the command line interface can be insecure.
mysql: [Warning] Using a password on the command line interface can be insecure.
mysql: [Warning] Using a password on the command line interface can be insecure.
orders
1202
flyway
6
restore-test

What this code does

  • --single-transaction gives a consistent copy without locking the live tables; the dump goes straight through gzip, so no plain file sits on the disk.
  • The ping uses -h127.0.0.1 on purpose: while the MySQL image is still initialising it runs a temporary server without networking, so a TCP ping succeeds only once the real server is up. The restore goes into a throwaway container, never into production.
  • The final query compares the restored data with production: the order count is plausible and the Flyway version is the current one, 6.

--single-transaction takes a consistent copy of InnoDB tables without locking them, so the shop keeps taking orders during the backup. Add --ssl-mode=REQUIRED for the managed server; for managed services, --set-gtid-purged=OFF and --no-tablespaces avoid privilege errors when the backup user has only SELECT, SHOW VIEW and TRIGGER.

Order of execution

Restore a backup safely

Tap the steps in the order they happen.

A backup you have not restored is not a backup

A restore test brings a recent backup back into a throwaway container and checks it: the tables exist, the row counts are close to production and the Flyway version matches. Its duration is your real recovery time.

Backups fail quietly: an empty file, a dump of the wrong database, a passphrase nobody saved. The program below compares a restored copy with production.

Example 3 · Checking a restore test

RestoreCheckDemo.javaJava
import java.util.LinkedHashMap;import java.util.Map;
public class RestoreCheckDemo {    public static void main(String[] args) {        // Counts from production at backup time, and from the restored copy        Map<String, Integer> production = new LinkedHashMap<>();        production.put("customers", 418);        production.put("products", 96);        production.put("orders", 1202);        production.put("order_items", 2977);        Map<String, Integer> restored = Map.of("customers", 418, "products", 96,                "orders", 1202, "order_items", 0);        String prodFlyway = "6";        String restoredFlyway = "6";
        int problems = 0;        for (Map.Entry<String, Integer> e : production.entrySet()) {            int got = restored.getOrDefault(e.getKey(), -1);            boolean ok = got == e.getValue();            if (!ok) {                problems++;            }            System.out.printf("%-12s expected %5d, restored %5d  %s%n", e.getKey(), e.getValue(), got, ok ? "ok" : "MISMATCH");        }        System.out.println("Flyway version " + restoredFlyway + (restoredFlyway.equals(prodFlyway) ? " ok" : " MISMATCH"));        System.out.println(problems == 0 ? "RESTORE TEST PASSED" : "RESTORE TEST FAILED: fix the backup before you need it");    }}
Output
customers    expected   418, restored   418  ok
products     expected    96, restored    96  ok
orders       expected  1202, restored  1202  ok
order_items  expected  2977, restored     0  MISMATCH
Flyway version 6 ok
RESTORE TEST FAILED: fix the backup before you need it

What this code does

  • The test compares row counts table by table. Here order_items came back empty, for example because the backup user lacked SELECT on that table after a permission change.
  • Without the test, every order would have lost its items in a real restore. Found in a monthly test, it is a one-line GRANT fix.

Do a restore test once a month, put it in the calendar and write down how long it took. The common mistake is to check only that the backup file exists.

Predict the output

Is this restore good?

Read each result and pick the verdict.

Round 1 of 3

The restore test shows these counts.

production: customers=1200 orders=2977 order_items=8801
restored: customers=1200 orders=2977 order_items=0

Scheduling encrypted backups off the server

Cron is the Linux scheduler that runs a command at set times, written as five fields: minute, hour, day of month, month and weekday. Cron on the VM and GitHub Actions schedules both use UTC.

A cron line on the VM runs backup.sh every night, and a GitHub Actions schedule can start the same script. Both use UTC, so 02:00 IST is 30 20 * * *. The example below shows both.

Example 4 · Nightly schedule: cron on the VM or a GitHub Actions trigger

Runs in: a GitHub repository (.github/workflows/backup.yml) and the VM's crontab

YAML
# Option 1, on the VM (crontab -e as the deploy user; the VM runs in UTC):#   30 20 * * * /opt/shoplite/backup.sh >> /opt/shoplite/backup.log 2>&1# Option 2, .github/workflows/backup.yml: GitHub triggers, the VM does the workname: Nightly backupon:  schedule:    - cron: "30 20 * * *"        # 02:00 IST every day (schedules use UTC)  workflow_dispatch:              # also a manual "Run workflow" buttonjobs:  backup:    runs-on: ubuntu-latest    environment: production    steps:      - name: Run backup.sh on the VM        env:          SSH_KEY: ${{ secrets.DEPLOY_SSH_KEY }}          KNOWN_HOSTS: ${{ secrets.DEPLOY_KNOWN_HOSTS }}          DEPLOY_HOST: ${{ vars.DEPLOY_HOST }}        run: |          install -m 700 -d ~/.ssh          printf '%s\n' "$SSH_KEY" > ~/.ssh/id_ed25519          chmod 600 ~/.ssh/id_ed25519          printf '%s\n' "$KNOWN_HOSTS" > ~/.ssh/known_hosts          ssh "deploy@$DEPLOY_HOST" /opt/shoplite/backup.sh
Sample output
Nightly backup #23  (schedule, 20:31 UTC)
  ✓ backup   Run backup.sh on the VM
    Dumped shoplite (412K), encrypted with AES256
    upload: backups/shoplite-20261016-203004.sql.gz.gpg to s3://shoplite-backups/shoplite/shoplite-20261016-203004.sql.gz.gpg
    Deleted 1 local backup older than 7 days
    Backup done: shoplite-20261016-203004.sql.gz.gpg (412K)

What this code does

  • Both options run the same backup.sh on the VM, which is the machine the database allows. The Actions version adds a visible history and a red run (and an email) when a backup fails.
  • GitHub runs schedules from the default branch, in UTC, and may start them some minutes late at busy times, which is fine for a nightly job.

Runners' IP addresses change, so the workflow SSHes to the VM, which is already allowed to reach the database, and runs the same script there. A backup on the same server is lost with the server, so the script encrypts the dump with a passphrase (gpg --symmetric), because it holds customers' names, phone numbers and addresses, copies it off the server to a bucket at another provider, and deletes local copies older than a week.

Fix the error

Fix the schedule time

Pick the line that runs the backup at 02:00 IST.

Round 1 of 2

The VM runs on UTC, but the backup must run at 02:00 IST.

# run at 02:00 IST every night
0 2 * * * /opt/shoplite/backup.sh

Error

Backup started at 07:30 IST (02:00 UTC), not at 02:00 IST

Backups before risky migrations, and the 3-2-1 rule

The 3-2-1 rule says keep 3 copies of your data, on 2 different kinds of storage or services, with 1 copy off-site. For ShopLite: the live database, the provider's backups and an encrypted dump in another provider's bucket.

Take an extra backup right before a release with a risky migration, such as a column change or a big UPDATE. The program below tests two backup plans against 3-2-1.

The 3-2-1 rule for ShopLite. Three copies: the live managed MySQL database, the provider daily backups and an encrypted nightly dump. Two kinds of storage: database service and bucket. One copy off-site: the dump sits in a bucket at a different provider than the database.

Example 5 · Does the plan pass the 3-2-1 rule?

ThreeTwoOneDemo.javaJava
import java.util.List;
record Copy(String what, String storage, boolean offSite) {}
public class ThreeTwoOneDemo {    static void check(String plan, List<Copy> copies) {        long kinds = copies.stream().map(Copy::storage).distinct().count();        long offSite = copies.stream().filter(Copy::offSite).count();        boolean ok = copies.size() >= 3 && kinds >= 2 && offSite >= 1;        System.out.printf("%s: %d copies, %d kinds of storage, %d off-site -> %s%n",                plan, copies.size(), kinds, offSite, ok ? "passes 3-2-1" : "FAILS 3-2-1");    }
    public static void main(String[] args) {        Copy live = new Copy("live database", "managed MySQL", false);        Copy auto = new Copy("automated backups", "provider snapshots", false);        Copy vmDump = new Copy("dump on the VM disk", "VM disk", false);        Copy bucket = new Copy("encrypted dump", "bucket at another provider", true);
        check("Only provider backups", List.of(live, auto));        check("Plus a dump on the VM", List.of(live, auto, vmDump));        check("ShopLite plan", List.of(live, auto, bucket));    }}
Output
Only provider backups: 2 copies, 2 kinds of storage, 0 off-site -> FAILS 3-2-1
Plus a dump on the VM: 3 copies, 3 kinds of storage, 0 off-site -> FAILS 3-2-1
ShopLite plan: 3 copies, 3 kinds of storage, 1 off-site -> passes 3-2-1

What this code does

  • Each copy says where it lives and whether it is away from the main provider; the check counts copies, distinct kinds of storage and off-site copies.
  • A dump on the VM adds a copy but not safety from losing the account or the VM; only the encrypted copy at another provider makes the plan pass.

If the migration goes wrong, you restore to the moment just before it, not to last night. The off-site copy is the one that survives a locked account.

Next step

Check your understanding

12 quick questions