One morning in October we deployed a new version of one of our plugins. A few minutes later the site stopped answering. Not slow: stopped. Every PHP worker was busy, every new request queued behind them, and the only way out was restarting PHP.
The cause was four lines of code that almost every WordPress plugin has in some form:
add_action( 'plugins_loaded', function () {
if ( get_option( 'my_plugin_db_version' ) !== '1.30.0' ) {
my_plugin_create_tables(); // dbDelta, ALTER TABLE
update_option( 'my_plugin_db_version', '1.30.0' );
}
} );
This post is about why that pattern is dangerous on a busy site, and the small runner we replaced it with. We run Transtoyou, an online health platform in 14 languages on one WordPress multisite, so a broken deploy means patients who cannot reach a doctor. But nothing here is specific to health. If your plugin checks its database version on plugins_loaded, this is about you.
What actually happened
The check above runs on every request. Right after a deploy, the stored version is old, so the first request starts the migration. So does the second one, a few milliseconds later, because the first one has not written the new version yet. On a site with traffic, "the first request after a deploy" is really "the first twenty requests after a deploy".
Two things then went wrong at once.
Two requests ran the same ALTER TABLE. One succeeded, the other failed with Duplicate column name. Annoying, but survivable.
An ALTER TABLE waited on a metadata lock. To change a table, MySQL needs an exclusive metadata lock on it. If any other connection is in the middle of a transaction that touched that table, the ALTER waits. And while it waits, every new query on that table queues behind it, because MySQL will not let new readers jump ahead of a waiting writer.
How long does it wait? That is set by lock_wait_timeout, and the default is 31,536,000 seconds. One year.
So one PHP worker sat waiting on the ALTER, and every following request that touched the table sat waiting behind it. Within a minute all workers were stuck. Nothing failed loudly. Everything just waited.
When we went looking, we found the same pattern in about forty installers across our own plugins.
The rules we wrote down
Before writing any code, we agreed on what a migration is allowed to do:
- A visitor's request never changes the schema. Not a page view, not an AJAX call. Migrations run from WP-CLI, from cron, or from someone opening wp-admin.
- One at a time. If a migration is running, everyone else skips it and moves on.
-
Waiting is bounded. If the
ALTERcannot get its lock within a few seconds, it gives up and logs it, instead of holding a worker for a year. - The version is recorded only when the schema is really there. Not when the installer finished, but when a check confirms the new columns exist.
One runner for every migration
All forty installers now go through one function:
tty_schema_migrate( $key, $version, $install, $args );
$key is the option that stores the version, $version is the version this code needs, $install is the callable that runs dbDelta() or ALTER TABLE. Here is what it does, in order.
1. Is there anything to do?
$needed = (string) get_site_option( $key ) !== $version;
if ( ! $needed ) {
return 'current';
}
This is the only part that runs on every request, and it is a single cached option read.
2. May this request migrate?
function tty_schema_migration_request() {
if ( defined( 'WP_CLI' ) && WP_CLI ) {
return true;
}
if ( wp_doing_cron() ) {
return true;
}
return is_admin() && ! wp_doing_ajax();
}
The wp_doing_ajax() exclusion is the subtle one. admin-ajax.php counts as is_admin(), but on most sites it also serves front-end requests: dashboards, carts, anonymous pings. Treat it as a visitor.
If the request may not migrate, the runner returns 'skipped' and the page carries on with the old schema. That means the code that uses a new column has to cope with that column not being there yet, which is a good habit anyway: during a deploy, old and new code briefly run side by side.
3. Take the lock
$lock = 'tty_schema_lock_' . substr( md5( $key ), 0, 20 );
if ( get_site_transient( $lock ) ) {
return 'locked';
}
set_site_transient( $lock, 1, 120 );
The lock is set before the installer runs and removed only after success. If the installer fails, the lock simply expires after two minutes and the next eligible request tries again. A failed migration is retried, but never in parallel.
A fair objection: a transient read followed by a write is not atomic. Two requests can, in theory, both see "no lock" in the same instant. In practice this is much less likely than before, because the window is now only the eligible requests (cron, admin, CLI) instead of every page view. If you need a strict guarantee, MySQL's GET_LOCK() is atomic and disappears with the connection. We use it elsewhere for exactly that reason.
4. Bound the wait
$previous = $wpdb->get_var( 'SELECT @@SESSION.lock_wait_timeout' );
$wpdb->query( 'SET SESSION lock_wait_timeout = 5' );
try {
$result = call_user_func( $install );
} finally {
$wpdb->query( 'SET SESSION lock_wait_timeout = ' . intval( $previous ) );
}
This is the line that would have saved our morning. With a five-second limit, an ALTER that cannot get its metadata lock fails with an error after five seconds. One log line, one worker freed, and the migration tries again two minutes later, when the long transaction that held the table is probably gone.
The finally matters: the setting is per session, and the same connection serves the rest of the request.
5. Check before you record
$ready = $result !== false
&& ( ! is_callable( $args['ready'] ) || call_user_func( $args['ready'] ) );
if ( $ready ) {
update_site_option( $key, $version );
delete_site_transient( $lock );
return 'done';
}
error_log( "[Schema] {$key}: version {$version} not in place yet, retrying later." );
return 'failed';
dbDelta() fails silently more often than you would like. We had a table that never existed on production for weeks, because one column was called lines, a reserved word in MySQL, while the plugin had happily recorded its version. The ready callback asks the database whether the table and the newest column are actually there:
'ready' => function () use ( $wpdb ) {
return (bool) $wpdb->get_var(
"SHOW COLUMNS FROM {$wpdb->prefix}my_table LIKE 'cycle_set_by'"
);
},
No column, no version, and the next run tries again.
Running it after a deploy
Because a visitor never migrates, something else has to. We added one WP-CLI command to our deploy routine:
wp tty-schema run --all-sites
It starts a fresh process per site of the network. Each process boots WordPress normally, so every plugin calls the runner exactly as it would in wp-admin, and the command prints what each migration did: current, done, locked or failed. It exits with a non-zero code when anything failed, so the deploy notices.
If nobody runs it, the schema still arrives the first time an administrator opens wp-admin or cron runs. It just never arrives in the middle of a patient's checkout.
The one exception
Some code needs a table right now. For example: "store this event, and create the log table first if it does not exist". Waiting for cron is not an option there. For those paths the runner takes 'gate' => false: it skips the "may this request migrate" check, but still uses the lock, the five-second wait and the ready check. Lazy, but safe.
What changed
Since every migration goes through the runner, a deploy that changes a table is boring. The migration runs once, from the command line, with a bounded wait, and we see the outcome. A visitor never waits on an ALTER TABLE again.
If you maintain a plugin, three things are worth checking today:
- Does your version check run its installer on
plugins_loadedorinitfor every request? - Do you record the new version without checking that the schema is really there?
- What is
lock_wait_timeouton your production database?
The third one surprised us most.
We build Transtoyou, an online doctor and pharmacy service for patients across Europe and the UK. Patients answer a questionnaire or book a video call, an independent doctor reviews it, and a licensed partner pharmacy delivers (how it works). Questions about the runner are welcome in the comments.
Top comments (0)