MySQL Online Schema Changes: INSTANT, INPLACE, COPY and Metadata Locks
MySQL 8.4 LTS DDL Algorithms Internals, MDL Queue Stampedes, and Evidence-Based Migration Choices
Empirical deep dive into MySQL 8.4 Online DDL execution algorithms (INSTANT, INPLACE, COPY), metadata lock acquisition lifecycle, lock queues, and safe migration strategies.

Executing an ALTER TABLE statement on a production MySQL database is one of the highest-risk operations a senior Database Administrator (DBA) can perform. Software development teams often assume that the phrase *"Online DDL"* in official documentation guarantees zero impact and zero locking. In practice, however, a single poorly planned ALTER TABLE can cause hundreds of application queries to back up in the server queue within seconds, exhausting the connection pool and triggering widespread 504 Gateway Timeout errors across client applications.
In this deep-dive engineering analysis, backed by isolated laboratory evidence executed on MySQL 8.4 LTS (8.4.13 Community Server) with the InnoDB engine, we investigate the concrete mechanics of ALGORITHM and LOCK clauses, when tables are physically rebuilt, how the SQL-layer Metadata Lock (MDL) operates, and why classic row-lock diagnostics are completely blind to MDL blockers.
1. Algorithm vs. Lock: Deconstructing the Dimensions
In MySQL's ALTER TABLE syntax, two orthogonal dimensions govern schema execution:
- 1`ALGORITHM`: Dictates the physical storage engine execution path (
INSTANT,INPLACE,COPY). - 2`LOCK`: Dictates the level of concurrent DML (read and write operations) allowed while the operation proceeds (
NONE,SHARED,DEFAULT,EXCLUSIVE).
ALGORITHM and LOCK are independent dimensions. Specifying ALGORITHM=INPLACE does not imply zero locking or zero table rebuild. In certain operations, INPLACE still requires an entire clustered index rebuild and exclusive metadata acquisition.▸Architectural Matrix (MySQL 8.4 LTS InnoDB)
| Algorithm | Table Rebuild Required | Disk Space Overhead | Concurrent DML (LOCK=NONE) | Lock Boundaries | Primary Production Use Cases |
|---|---|---|---|---|---|
| `INSTANT` | No (Data Dictionary & Row Header Versioning only) | Minimal (Data dictionary entry; no physical table rewrite) | Yes (Non-blocking by default) | Transient EXCLUSIVE MDL at start/end | Adding/dropping nullable columns, altering default values |
| `INPLACE` | Operation-dependent (No rebuild for secondary indexes or extending VARCHAR within the same length-byte tier (0–255 bytes or >=256 bytes); full table rebuild required for Primary Key modifications or changing nullability; crossing the 255-to-256 byte threshold or shrinking VARCHAR requires ALGORITHM=COPY) | Memory buffer for index creation; up to 1x table size if rebuilding | Yes (Concurrent reads and writes permitted for supported operations) | Brief EXCLUSIVE MDL during Prepare and Commit phases | Secondary index addition/drop, extending VARCHAR within the same length-byte tier, column renaming |
| `COPY` | Yes (Rows copied sequentially to a temporary table) | Full table duplicate on disk (temporary table + logs) | No (Requires at least LOCK=SHARED; all DML writes blocked) | Shared lock throughout the run; exclusive lock during swap | Data type conversion, primary key modification, adding stored generated columns, crossing VARCHAR length-byte tier |
2. INSTANT: Zero Rebuild, Not Zero Locking
Introduced in MySQL 8.0 and stabilized in MySQL 8.4 LTS, ALGORITHM=INSTANT avoids rewriting physical data pages. Instead, it adjusts the table dictionary and modifies row header metadata to track column version offsets.
In our isolated L1 Laboratory Run (Run ID: MYSQL-84-LAB-20261126-v21-L1), we added a nullable column to the primary-keyed ecommerce_orders table (25,000 rows):
ALTER TABLE ecommerce_orders
ADD COLUMN notes VARCHAR(255) NULL,
ALGORITHM=INSTANT;The execution finished with a client duration of 0.2854 seconds with 0 rows affected. However, treating this as "zero-cost" in production is dangerous:
- •The Zero-I/O Myth: While existing rows are not physically rewritten immediately, every subsequent read and write must evaluate row version headers to reconstruct columns. Newly written rows carry the column data and offset headers.
- •The Metadata Lock Requirement: The DDL engine must acquire an
EXCLUSIVEmetadata lock during the initial preparation phase to update the internal data dictionary. If an active or sleeping transaction holds an open read lock on that table, theINSTANTDDL will be forced to queue and wait.
3. INPLACE and LOCK=NONE: The Boundaries of Concurrency
Adding a secondary index is typically handled via ALGORITHM=INPLACE, LOCK=NONE (L2 Laboratory Run, Run ID: MYSQL-84-LAB-20261126-v21-L2):
ALTER TABLE ecommerce_orders
ADD INDEX idx_orders_status_created (status, created_at),
ALGORITHM=INPLACE,
LOCK=NONE;In our verified laboratory run (25,000 rows, client-observed DDL wall-clock execution window: 1.1861 seconds), a concurrent batch of 10 INSERT operations was dispatched during the DDL client execution window:
- •Concurrent DML Commit Status: 10/10 (100% commit success rate, 0 errors, 0 lock wait timeouts).
- •Client-Interval Overlap: Concurrently recorded timestamps show that all 10 concurrent INSERT operations (10/10) dispatched and committed within the 1.1861-second client DDL execution window. We explicitly classify this empirical result as client-interval overlap rather than an exhaustive proof of server-side internal build phase concurrency or zero lock contention under sustained high write pressure.
However, claiming "zero downtime across all workloads" is technically false:
- 1Prepare Phase: The engine initializes the online DDL change buffer and briefly requests an
EXCLUSIVEmetadata lock. - 2Execution Phase: The secondary B-Tree is constructed. Concurrent DML operations write their modifications into
innodb_online_alter_log_max_size. Concurrency is preserved during this phase. - 3Commit Phase: The server applies the accumulated online alter logs and swaps table definitions. This phase requires a second, brief
EXCLUSIVEmetadata lock.
If a long-running reporting query or an uncommitted background transaction is active when the DDL enters its commit phase, the DDL blocks. The moment the DDL blocks, all subsequent SELECT and INSERT queries queue behind it.
▸VARCHAR Length-Byte Classes and In-Place Expansion Rules
A critical nuance often overlooked in online migrations is that extending a VARCHAR column is not universally in-place. In the InnoDB storage engine, VARCHAR columns store a length prefix whose width is determined by the column's maximum byte length:
- •1-Byte Length Prefix (0 to 255 bytes): Columns requiring at most 255 bytes need only 1 byte per row to record string length.
- •2-Byte Length Prefix (256 to 65,535 bytes): Columns requiring 256 or more bytes require 2 bytes per row.
The Boundary Rules for In-Place Modification:
- 1Intra-Tier Extensions (No Table Rebuild):
- •Extending from length $L_1$ to $L_2$ within the 1-byte tier (both $\le 255$ bytes, e.g., extending from 100 to 200 bytes) requires no change to the row length-prefix width. This is an
ALGORITHM=INPLACEoperation requiring only data dictionary updates with no table rebuild. - •Extending from length $L_1$ to $L_2$ within the 2-byte tier (both $\ge 256$ bytes, e.g., extending from 300 to 500 bytes) similarly keeps the 2-byte prefix width unchanged and proceeds with
ALGORITHM=INPLACEwithout table rebuild.
- 1Tier-Crossing Extensions Mandate `ALGORITHM=COPY`:
- •When an extension crosses the 255-to-256 byte threshold (e.g., from 250 bytes to 260 bytes), every row on disk must have its length prefix physically widened from 1 byte to 2 bytes. InnoDB cannot execute this transformation in place; it strictly requires
ALGORITHM=COPY, forcing a table rebuild and blocking concurrent writes.
- 1Decreasing Column Length:
- •Shrinking
VARCHARlength always requiresALGORITHM=COPYto validate that existing data is not truncated.
- 1Multi-Byte Character Sets (`utf8mb4`) Multiplier:
- •In MySQL,
VARCHAR(N)denotes $N$ characters, while storage tier boundaries evaluate maximum bytes. - •Under
utf8mb4(up to 4 bytes per character): - •
VARCHAR(63)requires $63 \times 4 = 252$ bytes (1-byte length prefix tier: $\le 255$ bytes). - •
VARCHAR(64)requires $64 \times 4 = 256$ bytes (crosses into the 2-byte tier: $\ge 256$ bytes). - •Consequently:
- •Extending
VARCHAR(30)toVARCHAR(60)underutf8mb4($120 \to 240$ bytes) isINPLACEwithout rebuild. - •Extending
VARCHAR(60)toVARCHAR(65)underutf8mb4($240 \to 260$ bytes) crosses the 255-byte threshold and strictly requiresALGORITHM=COPY. - •Extending
VARCHAR(100)toVARCHAR(200)underutf8mb4($400 \to 800$ bytes) remains within the 2-byte tier and isINPLACEwithout rebuild.
Secondary Index vs. Primary Key (Clustered Index) Distinctions:
- •Secondary Indexes (`INPLACE, LOCK=NONE`): Creating or dropping a secondary index constructs a new secondary B-Tree via external merge sort while buffering concurrent DML changes in
innodb_online_alter_log_max_size. The clustered table data is not rebuilt. - •Primary Key (Clustered Index Rebuild): The primary key defines the physical organization of the clustered index and its leaf pages. Adding, modifying, or dropping a primary key reorganizes every record on disk and mandates a full clustered index rebuild, consuming significant I/O and temporary disk space.
4. Metadata Lock (MDL) Internals and Sleeping Blockers
Metadata Locking is an SQL-layer concurrency control mechanism designed to guarantee transactional consistency—preventing a table's schema from changing while concurrent queries are executing against it. It is distinct from and operates above InnoDB row locks.
▸The Cascading Queue Collapse (L3 Laboratory Evidence)
In our L3 Laboratory Run (Run ID: MYSQL-84-LAB-20261126-v21-L3), we reproduced the classic production failure chain:
- 1Conn-1 (The Blocker, Connection ID 31): An application thread opens a transaction, reads from the table, and leaves the connection idle without committing:
START TRANSACTION;
SELECT COUNT(*) FROM ecommerce_orders;
-- Connection remains idle (Command: Sleep)This session holds a SHARED_READ metadata lock on ecommerce_orders.
- 1Conn-2 (The Blocked DDL, Connection ID 32): A migration script triggers an
INPLACEcolumn addition:
ALTER TABLE ecommerce_orders ADD COLUMN loyalty_tier INT NULL, ALGORITHM=INPLACE, LOCK=NONE;Because ALTER TABLE requires an EXCLUSIVE lock, it cannot proceed until Conn-1 commits. Conn-2 enters the Waiting for table metadata lock state.
- 1The Queue Starvation Trap: MySQL prioritizes pending DDL locks over subsequent read requests. New incoming read operations are forced to queue behind Conn-2. Within seconds, hundreds of application threads pile up, exhausting
max_connections.
▸Why Row-Lock Scripts Fail to Detect the Blocker
Standard DBA scripts, such as sys.innodb_lock_waits or data/scriptsMysql.ts (my-022), inspect only InnoDB row locks. Because Conn-1 is merely holding a shared metadata lock at the SQL layer and no row locks, sys.innodb_lock_waits returns 0 rows (empirically confirmed in our L3 raw capture).
Similarly, scripts that filter for active queries (COMMAND != 'Sleep', like my-021) miss the blocker entirely because the blocking session is in Sleep state between queries within an open transaction.
▸The Diagnostic Telemetry: performance_schema.metadata_locks
To accurately identify the blocker, query the SQL metadata lock registry directly:
SELECT
m.OBJECT_TYPE,
m.OBJECT_SCHEMA,
m.OBJECT_NAME,
m.LOCK_TYPE,
m.LOCK_DURATION,
m.LOCK_STATUS,
t.PROCESSLIST_ID,
t.PROCESSLIST_COMMAND,
t.PROCESSLIST_STATE,
t.PROCESSLIST_INFO
FROM performance_schema.metadata_locks m
JOIN performance_schema.threads t ON m.OWNER_THREAD_ID = t.THREAD_ID
WHERE m.OBJECT_SCHEMA = 'lab_triad_mysql84_v21'
AND m.OBJECT_NAME = 'ecommerce_orders';metadata_locks with threads while filtering out system schemas.The following explanatory telemetry presentation correlates the metadata lock records with the thread processlist state captured during our L3 run:
OBJECT_TYPE: TABLE
OBJECT_SCHEMA: lab_triad_mysql84_v21
OBJECT_NAME: ecommerce_orders
LOCK_TYPE: SHARED_READ
LOCK_STATUS: GRANTED
PROCESSLIST_ID: 31
PROCESSLIST_COMMAND: Sleep
PROCESSLIST_STATE: NULL
---
OBJECT_TYPE: TABLE
OBJECT_SCHEMA: lab_triad_mysql84_v21
OBJECT_NAME: ecommerce_orders
LOCK_TYPE: EXCLUSIVE
LOCK_STATUS: PENDING
PROCESSLIST_ID: 32
PROCESSLIST_COMMAND: Query
PROCESSLIST_STATE: Waiting for table metadata lock
PROCESSLIST_INFO: ALTER TABLE ecommerce_orders ADD COLUMN loyalty_tier INT NULL...The telemetry provides direct laboratory verification: Processlist ID 31 is sleeping, yet holds GRANTED on SHARED_READ. Processlist ID 32 is pending on EXCLUSIVE. Once Conn-1 issued COMMIT;, Conn-2 unblocked and finished immediately. Beyond this two-connection blocking condition, production architectures face the cascading queue collapse documented in MySQL internals: once Conn-2 queues for an EXCLUSIVE metadata lock, subsequent SELECT queries queue behind Conn-2, rapidly exhausting available connections.
5. Explicit ALGORITHM: Eliminating the Silent Fallback Hazard
When an ALTER TABLE statement omits the ALGORITHM clause, MySQL silently falls back from INSTANT to INPLACE, and ultimately to COPY.
On a multi-gigabyte table, changing a column data type without an explicit algorithm specification causes MySQL to silently launch a full COPY rebuild, locking out writes for hours.
In our L4 Laboratory Run (Run ID: MYSQL-84-LAB-20261126-v21-L4), we enforced defensive syntax:
ALTER TABLE ecommerce_orders
MODIFY COLUMN order_code VARCHAR(16) NOT NULL,
ALGORITHM=INSTANT;Result:
ERROR 1846 (0A000): ALGORITHM=INSTANT is not supported. Reason: Need to rebuild the table to change column type. Try ALGORITHM=COPY/INPLACE.- •Error Code:
1846 - •SQLSTATE:
0A000 - •Schema Impact: None. The table schema remained completely untouched (
order_coderemainedVARCHAR(32)). The defensive algorithm specification acted as an automated safeguard against an unexpected full-table lock. We then verified the matching fallback withALGORITHM=COPY, LOCK=SHAREDon the exact same column change, which succeeded in1.2572 secondsafter verifying row data integrity.
6. Defensive DDL via Session lock_wait_timeout
In production environments, DDL operations must never be permitted to wait indefinitely under the server-wide default (lock_wait_timeout = 31536000 seconds / 1 year).
innodb_lock_wait_timeout (default 50 seconds) governs only InnoDB row locks. The parameter controlling Metadata Lock wait time is `lock_wait_timeout`.In our L5 Laboratory Run (Run ID: MYSQL-84-LAB-20261126-v21-L5), we validated the session-level circuit breaker:
SET SESSION lock_wait_timeout = 2;
ALTER TABLE ecommerce_orders
ADD COLUMN timeout_test_col INT NULL,
ALGORITHM=INPLACE;After exactly 2.6128 seconds of waiting behind an open transaction, the DDL aborted cleanly:
ERROR 1205 (HY000) at line 1: Lock wait timeout exceeded; try restarting transaction- •Blocker Session: Unaffected and able to complete its business logic.
- •Connection Queue: DDL departed the wait queue immediately, preventing application traffic starvation.
- •Schema State: Clean. No lingering table artifacts or corrupt states remained on the server. Column
timeout_test_colwas not created.
7. Senior DBA Engineering Checklist
- 1Always declare explicit `ALGORITHM` and `LOCK`: Prevent unexpected copy-based table locks by requiring
ALGORITHM=INSTANTorALGORITHM=INPLACE, LOCK=NONE. - 2Constrain session timeout: Always preface production DDL with
SET SESSION lock_wait_timeout = 5;to ensure fail-fast behavior. - 3Target metadata locks during triage: When an
ALTER TABLEstalls, do not rely onsys.innodb_lock_waits; queryperformance_schema.metadata_locksjoined withthreads. - 4Never use automated kill daemons on production: Rather than abruptly killing sleeping user connections, configure DDL statements to abort and retry during lower traffic windows.
Complementary Ecosystem Content: Safe MySQL Schema Changes
Complementary dataiotech publications covering this problem from different angles (diagnostics, tooling, escalation):
Other MySQL Guides
Verified operational assets for this database engine.
InnoDB Tuning Reference
Buffer pool sizing formula (70-80%), redo log and flush policies, I/O capacity, production my.cnf template, and SHOW ENGINE INNODB STATUS triage guide.
MySQL Backup & Recovery
Logical backups with mysqldump and MySQL Shell dumpInstance, physical backups with Percona XtraBackup, Point-in-Time Recovery via binary logs, and the CLONE plugin.
MySQL OCP 8.0 DBA Exam Topic Map
All 7 domains of Oracle 1Z0-908 MySQL 8.0 Database Administrator exam: Architecture, Install/Config, Security, Monitoring, Query Optimization, Backup/Recovery, HA, and pitfalls.