Home›Operate›Run it well 7: change huge tables
Run it well

Change a huge table without stopping the app

Adding a column or deleting old rows is one line of SQL. On a table with billions of rows, that one line can lock the app out, push replicas hours behind, or fill the disk. Here is how to tell which changes are safe and what to do with the ones that are not.

The problem

An 800 GB table and a one-line change

Your orders table holds 2 billion rows and 800 GB. Product wants one new column, gift_note. Finance wants rows older than seven years gone. Both sound like one line of SQL. On a table this size, either line can take the site down.

This chapter is about the two jobs every DBA with real data runs into: changing the shape of a huge table, and removing a lot of rows from it, while the app keeps writing.

The naive way

Just run the ALTER

Say the change needs a table rebuild. The database copies 800 GB into a new table with the new shape, rebuilds every index, then swaps the two. At 200 MB a second that copy alone takes over an hour, and index builds come on top (derived, not measured). On MySQL, the replica then replays the same ALTER as one event, so it falls behind by the whole duration. On PostgreSQL, a rewrite holds an exclusive lock for all of it. Nobody can read or write the table.

And here is the part people miss. Even a change that should take a millisecond can stop the app.

How can an instant change cause an outage?

Every ALTER needs a brief exclusive lock on the table, even an instant one. If a long transaction is already holding a lock on that table, the ALTER waits. Every new query on the table now queues behind the ALTER. In MySQL this shows up as "Waiting for table metadata lock". In PostgreSQL it is the ACCESS EXCLUSIVE request waiting in the lock queue. Your 1 ms change becomes a pile-up that lasts as long as that forgotten transaction. The fix is to cap the wait and retry: SET lock_timeout = '3s' in PostgreSQL, SET SESSION lock_wait_timeout = 3 in MySQL.

First question

Does this change need a rebuild at all?

Many common changes do not touch the rows. Knowing which ones is most of the skill.

ChangePostgreSQLMySQL 8 (InnoDB)
Add a nullable columnInstantInstant (ALGORITHM=INSTANT; any position since 8.0.29)
Add a column with a constant defaultInstant since PostgreSQL 11Instant
Add a column with a volatile default, like random()Full rewriteNot instant
Add an indexCREATE INDEX CONCURRENTLY: no write lock, slower, cannot run in a transactionOnline (INPLACE): writes continue, but replicas apply it as one long event
Add a foreign key or check constraintAdd it NOT VALID, then VALIDATE CONSTRAINT without blocking writesAdding a foreign key needs foreign_key_checks off to be in-place
Make a column NOT NULLScans the table under a lock, unless a valid CHECK (col IS NOT NULL) exists first (PostgreSQL 12+)Rebuild (in-place, online)
Change a column typeUsually a full rewrite (making a varchar longer is not)Usually a copy (making a varchar longer within the same length-byte size is in-place)

Always say what you expect. In MySQL, write the algorithm into the statement. If it cannot be done that way, MySQL refuses instead of silently copying 800 GB:

-- MySQL: fail fast instead of rebuilding by surprise
SET SESSION lock_wait_timeout = 3;
ALTER TABLE orders ADD COLUMN gift_note VARCHAR(200) NULL, ALGORITHM=INSTANT;

-- PostgreSQL: the same idea
SET lock_timeout = '3s';
ALTER TABLE orders ADD COLUMN gift_note text;          -- instant, no default needed
CREATE INDEX CONCURRENTLY orders_gift_idx ON orders (gift_note) WHERE gift_note IS NOT NULL;

-- PostgreSQL: a constraint without a long lock
ALTER TABLE orders ADD CONSTRAINT orders_amount_pos CHECK (amount > 0) NOT VALID;
ALTER TABLE orders VALIDATE CONSTRAINT orders_amount_pos;   -- scans, but lets writes continue

One warning about CREATE INDEX CONCURRENTLY: if it fails partway, it leaves an index marked invalid. It is not used for reads, but it is still updated on every write. Find it and drop it before you retry:

SELECT indexrelid::regclass FROM pg_index WHERE NOT indisvalid;
When it must rebuild

Copy it yourself, slowly, with a way back

Some changes really do need every row rewritten: a new primary key, a column type change, a charset change. For those, you do not let the database do it in one locked step. You build a shadow copy in the background and swap at the end.

For MySQL, the two common tools are gh-ost and pt-online-schema-change. Both create a new table with the new shape, copy rows across in small chunks, keep it in sync with ongoing writes, then rename the tables in one short step. pt-online-schema-change keeps the copy in sync with triggers. gh-ost reads the binary log instead, which keeps the extra work off the write path. That is also why it can pause itself when replicas fall behind.

# gh-ost: copy in chunks, pause when any replica is more than 1.5 s behind
gh-ost --host=replica1 --database=shop --table=orders \
  --alter="MODIFY amount DECIMAL(14,2) NOT NULL" \
  --max-lag-millis=1500 --chunk-size=1000 \
  --postpone-cut-over-flag-file=/tmp/ghost.postpone \
  --execute
# delete the flag file when you are ready for the final swap

In PostgreSQL, the tool for rebuilding a table online is pg_repack. It is most often used to remove bloat, which is the next problem. It needs a primary key or a unique index, and it takes a short exclusive lock at the start and the end.

Plan the disk first. Every one of these tools builds a full second copy, so you need free space at least the size of the table and its indexes.

The other job

Removing a billion old rows

The naive version is one statement: DELETE FROM orders WHERE created_at < '2019-01-01'. On a table this size that is one giant transaction. In MySQL it fills the undo log and holds row locks for the whole run, and the replicas replay it as one huge transaction. In PostgreSQL it writes a WAL record for every row and leaves a billion dead tuples for vacuum. And if anything fails at minute 50, the whole thing rolls back, which can take as long again.

Delete in small batches instead, by primary key, and give the system room to breathe between them:

-- MySQL: one batch; repeat from a script until it removes 0 rows
DELETE FROM orders
WHERE created_at < '2019-01-01'
ORDER BY id
LIMIT 5000;
-- between batches: check replica lag, sleep a little, stop if lag passes your limit

-- PostgreSQL: PostgreSQL has no DELETE ... LIMIT, so pick the batch by key
DELETE FROM orders
WHERE id IN (SELECT id FROM orders WHERE created_at < '2019-01-01' ORDER BY id LIMIT 5000);

Percona Toolkit has pt-archiver, which does the same batching and can copy rows to an archive table before deleting them. In MongoDB, a large deleteMany has the same replication problem, so batch it too. For data that should always expire, use a TTL index and let the server delete in the background.

The rows are gone. Why is the table still 800 GB?

Deleting does not give space back to the operating system. In PostgreSQL the space becomes reusable for new rows after vacuum, but the files keep their size. Shrinking them takes VACUUM FULL, which locks the table for the whole rewrite, or pg_repack, which does it online. In MySQL, InnoDB keeps the pages for reuse too. A rebuild (OPTIMIZE TABLE, which is an online rebuild for InnoDB, or gh-ost with a no-op ALTER) returns the space. If you delete old data every month, there is a far better design: partitions. That is the next chapter.

What to watch

Before, during and after

  • Before: long transactions on the table. In PostgreSQL, check pg_stat_activity for old xact_start. In MySQL, check information_schema.innodb_trx. Any of them can turn a 1 ms ALTER into a pile-up.
  • Before: free disk at least the size of the table plus its indexes, for any rebuild.
  • During: replica lag, and lock waits. Stop the batch job or pause gh-ost when lag passes your limit.
  • During: in MongoDB, index builds and big deletes both show up as replication lag on secondaries.
  • After: statistics. Run ANALYZE after big deletes, or the planner keeps planning for rows that are gone.
  • Always: a lock timeout on every migration session, and a retry, instead of an unbounded wait.
-- PostgreSQL: transactions open longer than 5 minutes SELECT pid, now() - xact_start AS open_for, state, left(query, 60) AS query FROM pg_stat_activity WHERE xact_start < now() - interval '5 minutes' ORDER BY xact_start;
-- MySQL: transactions open longer than 5 minutes SELECT trx_mysql_thread_id, trx_started, trx_rows_locked, LEFT(trx_query, 60) AS query FROM information_schema.innodb_trx WHERE trx_started < NOW() - INTERVAL 5 MINUTE;
Next · chapter 8PartitioningSplit a table by time, drop old parts in milliseconds← Chapter 6: Find the slow queries
Part 4 of 4 · Operate · 21 pagesAll pages

How do I run it in production? What to check when it is slow or broken, where it runs and what it costs, how big it must be, pooling, backups, security, upgrades and other changes made safely.