dataiotech Labs
Home/MySQL/Engineering Deep Dive/mysql-online-schema-change-metadata-locks
[Mühendislik]MySQL MySQL 8.4 LTSExpert
18 min read

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

Author / Standard:Principal Database Architect
Executive Architecture Brief:

Empirical deep dive into MySQL 8.4 Online DDL execution algorithms (INSTANT, INPLACE, COPY), metadata lock acquisition lifecycle, lock queues, and safe migration strategies.

MySQL Online Schema Changes: INSTANT, INPLACE, COPY and Metadata Locks

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. 1`ALGORITHM`: Dictates the physical storage engine execution path (INSTANT, INPLACE, COPY).
  2. 2`LOCK`: Dictates the level of concurrent DML (read and write operations) allowed while the operation proceeds (NONE, SHARED, DEFAULT, EXCLUSIVE).
WARNING
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)

AlgorithmTable Rebuild RequiredDisk Space OverheadConcurrent DML (LOCK=NONE)Lock BoundariesPrimary 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/endAdding/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 rebuildingYes (Concurrent reads and writes permitted for supported operations)Brief EXCLUSIVE MDL during Prepare and Commit phasesSecondary 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 swapData 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):

sql
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 EXCLUSIVE metadata 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, the INSTANT DDL 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):

sql
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:

  1. 1Prepare Phase: The engine initializes the online DDL change buffer and briefly requests an EXCLUSIVE metadata lock.
  2. 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.
  3. 3Commit Phase: The server applies the accumulated online alter logs and swaps table definitions. This phase requires a second, brief EXCLUSIVE metadata 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:

  1. 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=INPLACE operation 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=INPLACE without table rebuild.
  1. 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.
  1. 1Decreasing Column Length:
  • •Shrinking VARCHAR length always requires ALGORITHM=COPY to validate that existing data is not truncated.
  1. 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) to VARCHAR(60) under utf8mb4 ($120 \to 240$ bytes) is INPLACE without rebuild.
  • •Extending VARCHAR(60) to VARCHAR(65) under utf8mb4 ($240 \to 260$ bytes) crosses the 255-byte threshold and strictly requires ALGORITHM=COPY.
  • •Extending VARCHAR(100) to VARCHAR(200) under utf8mb4 ($400 \to 800$ bytes) remains within the 2-byte tier and is INPLACE without 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:

  1. 1Conn-1 (The Blocker, Connection ID 31): An application thread opens a transaction, reads from the table, and leaves the connection idle without committing:
sql
START TRANSACTION; SELECT COUNT(*) FROM ecommerce_orders; -- Connection remains idle (Command: Sleep)

This session holds a SHARED_READ metadata lock on ecommerce_orders.

  1. 1Conn-2 (The Blocked DDL, Connection ID 32): A migration script triggers an INPLACE column addition:
sql
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.

  1. 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:

sql
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';
TIP
For production incident triage, use our dedicated diagnostic script: Find MySQL Metadata Lock Waits and Blocking Sessions (my-041), which joins 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:

text
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:

sql
ALTER TABLE ecommerce_orders MODIFY COLUMN order_code VARCHAR(16) NOT NULL, ALGORITHM=INSTANT;

Result:

text
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_code remained VARCHAR(32)). The defensive algorithm specification acted as an automated safeguard against an unexpected full-table lock. We then verified the matching fallback with ALGORITHM=COPY, LOCK=SHARED on the exact same column change, which succeeded in 1.2572 seconds after 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).

CAUTION
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:

sql
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:

text
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_col was not created.

7. Senior DBA Engineering Checklist

  1. 1Always declare explicit `ALGORITHM` and `LOCK`: Prevent unexpected copy-based table locks by requiring ALGORITHM=INSTANT or ALGORITHM=INPLACE, LOCK=NONE.
  2. 2Constrain session timeout: Always preface production DDL with SET SESSION lock_wait_timeout = 5; to ensure fail-fast behavior.
  3. 3Target metadata locks during triage: When an ALTER TABLE stalls, do not rely on sys.innodb_lock_waits; query performance_schema.metadata_locks joined with threads.
  4. 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.
3-SITE TRIAD SERIES

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.

Tümünü Gör