This is the documentation for Vitess v25.0, the development version. See the v24.0 documentation for the latest release.

Creating a Backup

Choosing the backup type #

As described in Backup types, you choose to run a full Backup (the default) or an incremental Backup.

Full backups will use the backup engine chosen in the tablet's configuration. Incremental backups will always copy MySQL's binary logs, irrespective of the configured backup engine.

Using xtrabackup #

The default backup implementation is builtin, however we strongly recommend using the xtrabackup engine as it is more robust and allows for non-blocking backups. Restores will always be done with whichever engine was used to create the backup.

Prerequisites #

A compatible version of xtrabackup and xbstream, if needed, must be present in your $PATH prior to running the Backup[Shard] command.

Supported Versions #

Configuration #

To use xtrabackup with Vtbackup, VTTablet or Vtctld, the following flags must be set.

Required flags:

  • --backup-engine-implementation=xtrabackup
  • --xtrabackup-user string
    • The user that xtrabackup will use to connect to the database server. This user must have the necessary privileges.
    • This user will need to be authorized to connect to mysql locally without a password using auth_socket.

Additionally required for MySQL 8.0:

  • --xtrabackup-stream-mode=xbstream

Common Errors and Resolutions #

No xtrabackup User passed to vttablet:

E0310 08:15:45.336083  197442 main.go:72] remote error: rpc error: code = Unknown desc = TabletManager.Backup on zone1-0000000102 error: xtrabackupUser must be specified.: xtrabackupUser must be specified

Fix: Set the vtctld and vttablet flag --xtrabackup-user

xtrabackup binary not found in $PATH:

E0310 08:22:22.260044  200147 main.go:72] remote error: rpc error: code = Unknown desc = TabletManager.Backup on zone1-0000000102 error: unable to start backup: exec: "xtrabackup": executable file not found in $PATH: unable to start backup: exec: "xtrabackup": executable file not found in $PATH

Fixes:

* Ensure the xtrabackup binary is in the $PATH for the $USER running vttablet
* Alternatively, set --xtrabackup-root-path on vttablet provide path to xtrabackup/xbstream binaries via vtctld and vttablet flags

Tar format no longer supported in 8.0:

I0310 12:34:47.900363  211809 backup.go:163] I0310 20:34:47.900004 xtrabackupengine.go:310] xtrabackup stderr: Invalid --stream argument: tar
Streaming in tar format is no longer supported in 8.0; use xbstream instead

Fix: Set the --xtrabackup-stream-mode flag to to xbstream on vttablets and vtctlds

Unsupported mysql server version:

I0310 12:49:32.279729  215835 backup.go:163] I0310 20:49:32.279435 xtrabackupengine.go:310] xtrabackup stderr: Error: Unsupported server version 8.0.23-0ubuntu0.20.04.1.
I0310 12:49:32.279773  215835 backup.go:163] I0310 20:49:32.279485 xtrabackupengine.go:310] xtrabackup stderr: Please upgrade PXB, if a new version is available. To continue with risk, use the option --no-server-version-check.

To continue with risk: Set --xtrabackup-backup-flags=--no-server-version-check. Note this occurs when your MySQL server version is technically unsupported by xtrabackup.

Using mysqlshell (EXPERIMENTAL) #

An alternative option to physical backups (xtrabackup and builtin) is to take logical backups. Vitess supports MySQL Shell to dump and compress databases in a easy to recover plain text format using tab-separated values. Physical backups have the potential to suffer from silent corruption if pages are not often accessed and a logical backup will read and dump all the data on a tablet, flushing out any issues that could spread on a physical backup.

Prerequisites #

The mysqlsh binary should be present as it is used to handle the dump/load process. It is included in the MySQL distribution and also included in vitess provided containers.

Supported Versions #

  • MySQL 8.0

    Note that MySQL >=8.0.21 is recommended, but not required. It allows you yo disable redo logs and the double write buffer to make restores faster.

How it works #

This engine differs from the other engines in vitess in the sense that they usually manage the entire backup workflow, including uploading the generated data to the respective backend.

Because MySQL Shell doesn't provide a single stream and has many optimisations for dumping data faster, it outputs data into a target directory in many files (often thousands). If you are using an object storage like S3, Google Cloud Storage, Ceph, etc, MySQL Shell will need additional configuration as it needs direct access to those bakend storages, while the other engines rely on Vitess to upload the backup output.

The backup location configured for Vitess will only be used to store the MANIFEST for the metadata, which will point to the actual location of the backup in your preferred destination. This will also be used during the restore process, as Vitess needs to pass the location of the backup to MySQL Shell to initiate the restore process.

Configuration #

mysqlshell's configuration requires understanding some of the features of MySQL Shell. It is recommended users are familiar with the dump/load options as well as the options related to their backend storage included in these links.

Required flags:

  • --backup-engine-implementation=mysqlshell
  • --mysql-shell-backup-location string
    • This stores the location where MySQL Shell will store the backups. As mentioned above, this is different than the Vitess backup location.
  • --mysql-shell-flags="-js"
    • -js is required to be in the mysql shell flags otherwise we can't run the necessary commands.
    • There you can also pass other seetings that you would add to connect to your database, including hostname, username and password.
    • if you require a different way to pass credentials, you can look into the MySQL Shell's --credential-store-helper flag as that allows you to plug your own facility to fetch credentials without passing them via the command line

Optional flags:

  • --mysql-shell-dump-flags="{\"threads\": 4}"
    • you can control how many threads and other options with this flag. See the MySQL docs for other options
  • --mysql-shell-load-flags="{\"updateGtidSet\": \"replace\", \"progressFile\": \"\", \"skipBinlog\": true}"
    • updateGtidSet must be set to "replace" so MySQL Shell updates the executed GTID at the end of the restore
    • progressFile must be empty indicate we are starting a new backup and not continuing an existing one
    • skipBinlog must be true so we are not logging the statements to binary logs during the restore
    • loadUsers defaults to false, but it is not required. This is ideal if you rely on Vitess managing credentials as we will delete users by default during the dump process. If you perform your own credential management you might want to disable this.
    • these are all defaults in Vitess, but if you define this flag it must include the values above. other options can be found in the MySQL docs
  • --mysql-shell-should-drain=false
    • This flag controls if the tablet should be drained during backup or not. If true, it will transition to BACKUP type and will return to the original type once done, otherwise it will continue to serve during the backup (similar to the xtrabackup engine)
  • --mysql-shell-speedup-restore=false
    • If you are using MySQL >=8.0.21, this allows you to disable redo logs and the double write buffer for the duration of the restore, increasing the restore speed.

Limitations and Caveats to be aware #

Since MySQL needs to be running for the entire backup/restore process, we can't just replace all the files like we do with the physical backups. To account for this, Vitess handles things differently:

Databases #

All databases will be backed up, with the exception of information_schema, mysql, ndbinfo, performance_schema and sys. This is a MySQL Shell limitation. During the restore process, Vitess will drop all databases in the host ahead of the restore before starting the mysqlsh load process.

Users #

Since user grants are stored in the mysql database, they are not backed up like the other databases. MySQL Shell works around that saving users separately and allow the user to pass the loadUsers: true option during the load process to restore users to the state they were during the backup.

Internal users (mysql.sys@localhost, mysql.session@localhost, mysql.infoschema@localhost) are not restored, as well as the current user logged in to MySQL. It is also possible to exclude some users from being imported by using adjusting your --mysql-shell-load-flags if necessary.

Because MySQL Shell will fail the restore if any user already exists, Vitess will drop all users in MySQL (except the ones noted above) before the restore if you specify loadUsers: true.

Create a full backup with vtctl #

Run the following vtctl command to create a backup:

vtctldclient --server=<vtctld_host>:<vtctld_port> Backup [--upgrade-safe=false] <tablet-alias>

If the engine is builtin, replication will be stopped prior to shutting down mysqld for the backup.

If the engine is xtrabackup, the tablet can continue to serve traffic while the backup is running.

Run the following vtctl command to backup a specific shard:

vtctldclient --server=<vtctld_host>:<vtctld_port> BackupShard [--allow-primary=false] [--upgrade-safe=false] [--tablet-types=<types>] <keyspace/shard>

By default, BackupShard takes the backup on the REPLICA, RDONLY, or SPARE tablet in the shard with the lowest replication lag, whatever its type. It skips tablets whose replication lag is unknown. If none of these tablets can take the backup and you pass --allow-primary, Vitess takes the backup on the primary.

Backups are resource-intensive. To keep them off the tablets that serve replica reads, pass --tablet-types with a comma-separated list of tablet types in order of preference. Vitess uses the first listed type that has a tablet able to take the backup. Within that type, it uses the tablet with the lowest replication lag:

# Prefer an RDONLY tablet, falling back to a REPLICA
vtctldclient --server=<vtctld_host>:<vtctld_port> BackupShard --tablet-types=rdonly,replica commerce/0

# Use an RDONLY tablet only; fail if none can take the backup
vtctldclient --server=<vtctld_host>:<vtctld_port> BackupShard --tablet-types=rdonly commerce/0

# Prefer an RDONLY tablet, falling back to the primary
vtctldclient --server=<vtctld_host>:<vtctld_port> BackupShard --tablet-types=rdonly --allow-primary commerce/0

--tablet-types accepts replica, rdonly, and spare. Listing any other type, including primary, fails the command with an INVALID_ARGUMENT error. To fall back to the primary, pass --allow-primary instead: Vitess uses the primary only when no tablet of the listed types can take the backup. Without --allow-primary, the command fails with no tablet available for backup.

Upgrade vtctld before using --tablet-types. A vtctld older than v25 ignores the flag and uses the lowest-lag REPLICA, RDONLY, or SPARE tablet, so --tablet-types=rdonly can still back up from a REPLICA.

Include binary logs in a full backup #

A server restored from a full backup normally starts with an empty binary log history. It can't serve binlog streams, such as replication or VStreams, for transactions from before the backup. To keep that history, pass --include-binlogs to vtctldclient Backup, vtctldclient BackupShard, or vtbackup:

vtctldclient --server=<vtctld_host>:<vtctld_port> Backup --include-binlogs <tablet-alias>

The backup then also contains every binary log listed in the source's binary log index. Restores need no extra flag. When a backup includes binary logs, the restore writes them under the target tablet's own log-bin basename. It adds them to the binary log index before mysqld starts. Vitess doesn't reset or purge them afterward. Point-in-time recovery from such a backup works as usual.

Requirements #

  • Use the builtin backup engine. The builtin engine stops mysqld before copying files, so the binary logs end at exactly the position of the backed-up data. xtrabackup and mysqlshell back up a running server, so binary logs copied with their data could contain transactions the data lacks.
  • Take a full backup. Incremental backups can't use --include-binlogs.
  • Don't combine --include-binlogs with vtbackup --restore-with-clone, because MySQL CLONE doesn't copy binary logs.
  • Enable log_bin and log_replica_updates on the source, so its binary logs contain replicated transactions as well as local writes.
  • Set the tablet's log-bin (and log-bin-index, if used) to the location where mysqld keeps its binary logs, as the my.cnf that Vitess generates does. Vitess checks this before it stops mysqld.
  • Upgrade both vtctld and the tablets before using the flag with vtctldclient Backup or BackupShard. An older vtctld or vttablet ignores the flag and takes a backup without binary logs.

A request that uses another engine, an incremental backup, or --restore-with-clone fails with INVALID_ARGUMENT. A source that doesn't meet the log_bin, log_replica_updates, or log-bin requirements fails the backup with FAILED_PRECONDITION.

Trade-offs #

  • Backups grow by the size of the binary logs the source retains.
  • The restored files keep their original modification times, so binlog_expire_logs_seconds on the restored server can purge older binary logs soon after mysqld starts.
  • Encrypted binary logs (binlog_encryption) are backed up as they are. Only a server whose keyring holds the source's binary log master key, such as one sharing the source's keyring, can restore them. ALTER INSTANCE ROTATE BINLOG MASTER KEY removes the previous key, so a backup whose binary logs were encrypted before a rotation can no longer be restored.
  • A restore fails if the restored server can't read a restored binary log. A missing binary log master key in the keyring is one cause. If the newest binary log is unreadable, mysqld doesn't start. After a failed restore, the tablet doesn't start replicating, and restarting the tablet retries the restore.
  • The binary logs keep every transaction the source logged, including errant GTIDs. The restored server sends such a transaction to any replica that lacks it, and the replica applies it. VTOrc's errant GTID detection still applies.
  • Vitess versions without this feature restore only the data from such a backup and ignore the binary logs.

Create an incremental backup with vtctl #

An incremental backup requires additional information: the point from which to start the backup. An incremental backup is taken by supplying --incremental-from-pos to the Backup or BackupShard command. The argument may either indicate:

  • A valid position.
  • A name of a successful backup.
  • Or, the value auto.
vtctldclient Backup --incremental-from-pos="MySQL56/0d7aaca6-1666-11ee-aeaf-0a43f95f28a3:1-53" zone1-0000000102

vtctldclient Backup --incremental-from-pos="0d7aaca6-1666-11ee-aeaf-0a43f95f28a3:1-53" zone1-0000000102

vtctldclient Backup --incremental-from-pos="2024-01-10.062022.zone1-0000000101 commerce/0" zone1-0000000102

vtctldclient Backup --incremental-from-pos="auto" zone1-0000000102

vtctldclient BackupShard --incremental-from-pos=auto commerce/0

When --incremental-from-pos supplies a position, you may choose to use or to omit the MySQL56/ prefix (which you can find in the backup manifest's Position).

When --incremental-from-pos indicates a backup name, that must be a successfully completed, existing backup. It may be either a full or an incremental backup.

When --incremental-from-pos="auto", Vitess chooses the position of the last successful backup as the starting point for the incremental backup. This is a convenient way to ensure a sequence of contiguous incremental backups.

An incremental backup backs up one or more MySQL binary log files. These binary log files may begin with the requested position, or with an earlier position. They will necessarily include the requested position. When the incremental backup begins, Vitess rotates the MySQL binary logs on the tablet, so that it does not back up an active log file.

If Vitess finds that the database made no writes since the requested backup/position, then the incremental backup is deemed empty and produces no artifacts, essentially becoming a no-op. The Backup/BackupShard command exits with success code, but there is no MANIFEST file created and no backup name.

An incremental backup fails when it is unable to find binary log files that covers the requested position. This can happen if the binary logs are purged earlier than the incremental backup was taken. It essentially means there's a gap in the changelog events. Note that while on one tablet the binary logs may be missing, another tablet may still have binary logs that cover the requested position.

Running SQL Queries Before Backup #

You can execute SQL queries on the mysqld instance after catch-up replication completes but before initializing a backup. This is similar to MySQL's --init-file and --init-connect options.

When to Use Init SQL Queries #

Running SQL queries before a backup can be useful in various scenarios, for example:

  • Running OPTIMIZE TABLE on specific tables can reduce the backup size, speed up the backup process, and improve restore times. Because init queries run after catch-up replication, you can use OPTIMIZE TABLE to combat table fragmentation introduced during the catch-up replication process.
  • Execute maintenance tasks that prepare the database for backup
  • Temporarily modify settings for the backup operation

How It Works #

When taking a backup with vtbackup, the backup process follows these steps:

  1. Restore from the most recent backup
  2. Start mysqld and catch up on replication from the primary
  3. Execute any configured init SQL queries
  4. Take the backup

Init SQL queries are executed only on tablets that match the specified tablet types. If the backup tablet's type is not in the allowed list, the queries are skipped and the backup proceeds normally. The queries are executed with a configurable timeout. If they fail to complete within the timeout, you can choose to either fail the backup or continue anyway.

If MySQL was started with super_read_only enabled, Vitess temporarily disables it while executing the init SQL queries and restores it afterward.

Note that when using vtbackup there is no real tablet involved and the tablet-type used for this feature is always BACKUP.

Configuration Flags #

When taking backups with vtctldclient Backup, vtctldclient BackupShard, or vtbackup, you can use the following flags:

  • --init-backup-sql-queries: SQL queries to execute after catch-up replication, before initializing the backup. You can specify this flag multiple times or provide a single comma-separated value to run multiple queries in sequence.
  • --init-backup-tablet-types: Comma-separated list of tablet types where the init SQL queries will run (e.g., replica,rdonly). The backup will only execute the queries if the tablet taking the backup matches one of these types. You can also specify the flag multiple times to specify the set of tablet types.
  • --init-backup-sql-timeout: Maximum time to wait for the init SQL queries to complete. If the queries don't finish within this time, the behavior depends on the --init-backup-sql-fail-on-error flag.
  • --init-backup-sql-fail-on-error: Whether to fail the entire backup if the init SQL queries fail or timeout. Default is false, which means the backup continues even if the queries fail.

Requirements #

If you specify init SQL queries, you must also provide:

  • At least one tablet type via --init-backup-tablet-types
  • A non-zero timeout value via --init-backup-sql-timeout

These requirements prevent accidentally running queries without proper safeguards.

Examples #

Optimize a Single Table #

vtctldclient --server=<vtctld_host>:<vtctld_port> Backup \
  --init-backup-sql-queries="OPTIMIZE LOCAL TABLE mydb.large_table" \
  --init-backup-tablet-types=replica,rdonly \
  --init-backup-sql-timeout=1h \
  zone1-0000000102

Run Multiple Queries in Sequence #

You can specify multiple queries that will be executed in order:

vtctldclient --server=<vtctld_host>:<vtctld_port> Backup \
  --init-backup-sql-queries="SET sql_log_bin=0" \
  --init-backup-sql-queries="OPTIMIZE TABLE mydb.table1" \
  --init-backup-sql-queries="OPTIMIZE TABLE mydb.table2" \
  --init-backup-sql-queries="SET sql_log_bin=1" \
  --init-backup-tablet-types=replica,rdonly \
  --init-backup-sql-timeout=2h \
  zone1-0000000102

Fail Backup on Query Errors #

To ensure the backup only succeeds if the init queries complete successfully:

vtctldclient --server=<vtctld_host>:<vtctld_port> BackupShard \
  --init-backup-sql-queries="OPTIMIZE LOCAL TABLE mydb.critical_table" \
  --init-backup-tablet-types=replica,rdonly \
  --init-backup-sql-timeout=30m \
  --init-backup-sql-fail-on-error \
  commerce/0

Using with vtbackup #

The same flags work with vtbackup for scheduled or automated backups:

vtbackup \
  --init-backup-sql-queries="OPTIMIZE LOCAL TABLE mydb.large_table" \
  --init-backup-tablet-types=backup \
  --init-backup-sql-timeout=1h \
  --init-backup-sql-fail-on-error=false \
  # ... other vtbackup flags ...

Best Practices #

  • Test your init SQL queries on a non-production tablet to ensure they complete within your timeout and have the desired effect
  • Choose timeout values based on how long your queries typically take, with some buffer for variability
  • Run expensive operations like OPTIMIZE TABLE on replica or rdonly tablets rather than the primary
  • Check the backup logs to see whether init queries were executed, skipped, or failed
  • When optimizing tables, consider using OPTIMIZE LOCAL TABLE to avoid binlogging and potentially replicating the statement. With vtbackup --enable-errant-gtid-checks, a binlogged init SQL statement fails the run. For details, see Check vtbackup runs for errant GTIDs.

Check vtbackup runs for errant GTIDs #

A backup that holds errant GTIDs, which are GTIDs the shard primary doesn't have, can't be used. Every replica restored from it fails with Errant GTID detected. vtbackup restores the newest backup at the start of each run, so it carries the errant GTIDs into every later backup. vtbackup can pick up errant GTIDs in two ways:

  • It replicates from the primary without acknowledging semi-sync, so it can apply a transaction before any replica has it. If EmergencyReparentShard then promotes a replica that lacks the transaction, the new primary never has that GTID.
  • --init-backup-sql-queries runs with binary logging on. Statements such as ANALYZE TABLE, OPTIMIZE TABLE, or FLUSH TABLES write a GTID under vtbackup's own server UUID.

Pass --enable-errant-gtid-checks to vtbackup to fail the run, without completing a backup, when it finds errant GTIDs. The flag is off by default. GTIDs under the current primary's own server UUID aren't errant, which matches the rule tablets use. With the flag, vtbackup checks three times:

  1. The restored backup, or the data cloned with --restore-with-clone, before catch-up replication. If this check fails, the backup stays in storage.
  2. The data to back up, after init SQL queries run and before the backup starts.
  3. The new backup, just before its MANIFEST is written. If an emergency reparent during the upload loses transactions the backup holds, vtbackup aborts the backup.

The error names where the errant GTIDs came from and how to repair them. The source can be the restored backup, the clone donor, the init SQL queries, or catch-up replication.

Checks 2 and 3 can find transactions that vtbackup has applied but the primary hasn't committed yet. This happens while the primary waits for a semi-sync acknowledgement. If those transactions are under the primary's own UUID, vtbackup waits for the primary to commit them. The checks also wait for a missing or unreachable primary, an unreachable topology server, and the new primary after a reparent during the upload. These waits have no time limit of their own. Only a deadline on the job that runs vtbackup ends them. With the flag, the Phase metric includes a VerifyErrantGTIDs phase, which is active while checks 1 and 2 run. Check 3 runs within the TakeNewBackup phase.

vtbackup checks only MySQL GTID sets. As on tablets, MariaDB isn't checked.

Before you enable the checks #

  • If the shard's newest backup already has errant GTIDs, every run fails. Take a new backup of a healthy replica with vtctldclient Backup so the next run starts from it. Then remove the backups that hold the errant GTIDs with vtctldclient RemoveBackup. GTIDs under a former primary's UUID usually hold writes that a reparent lost. Copy any of that data the shard still needs before you remove the backups.
  • If your init SQL queries run binlogged statements, the run fails. Use the statements' NO_WRITE_TO_BINLOG or LOCAL forms, such as OPTIMIZE LOCAL TABLE, or start the queries with SET sql_log_bin = 0.

Backing up Topology Server #

The Topology Server stores metadata (and not tablet data). It is recommended to create a backup using the method described by the underlying plugin: