MySQL
index creation
large-scale databases
table locking
database optimization

Create an index on a huge MySQL production table without table locking

System Design practice on Codemia

Work through 120+ system design problems with detailed solutions, from rate limiters to multi-region storage.

Practice system design

MySQL databases are a cornerstone for many production environments, especially for web applications dealing with massive amounts of data. A common challenge faced by database administrators (DBAs) is creating or updating indexes on large tables without locking them, which can cause downtime or slow performance for applications that rely on those tables. Thankfully, MySQL provides several techniques and strategies to address this challenge, ensuring your system remains responsive during these operations.

Understanding Table Locking in MySQL

By default, MySQL creates indexes using the `ALTER TABLE` command, which locks the table for the duration of the operation. During this time, the table is not writable, and in some MySQL configurations, it might not even be readable. This can be problematic for production environments, especially for tables that frequently experience read-write operations.

Effects of Table Locking

  1. Downtime: Applications may experience downtime if they cannot access the table.
  2. Loss of performance: Long query waits can lead to performance bottlenecks.
  3. User dissatisfaction: If users cannot access data when needed, their experience may be negatively impacted.

Creating Indexes without Table Locking

MySQL provides several tools and techniques to create indexes without locking tables:

1. Using `pt-online-schema-change`

`pt-online-schema-change` is a powerful tool from Percona Toolkit that allows you to safely alter tables without locking them. It works by creating a new copy of the table with the desired changes and then gradually copying data from the original to the new table.

Steps to Use `pt-online-schema-change`

  1. Installation: Ensure Percona Toolkit is installed on your system.
  2. Command Execution:
    • `--alter`: The alteration statement containing the index creation.
    • `D=database_name`: The database containing the table.
    • `t=table_name`: The target table for index creation.
  • Benefits: Lower CPU and IO usage compared to traditional locking.
  • Limitations: Some complex operations might not support `ALGORITHM=INPLACE`.
  • Highly Parallelizable: It can engage throttling for minimal performance impact.
  • Flexibility: Supports a wide range of changes beyond just indexing.

Course
Beginner
27 lessons
10 hours
System Design Fundamentals

Build a strong foundation in designing scalable, reliable distributed systems.

View the course
System Design practice on Codemia

Work through 120+ system design problems with detailed solutions, from rate limiters to multi-region storage.

Practice system design