Video in progress
How do you add an index to a table with 200 million rows without stopping writes, and how do you write that in Flyway?
CREATE INDEX CONCURRENTLY doesn't lock writes to the table, but it can't run inside a transaction. In Flyway such a migration must be in its own file and run without a transaction. If it fails, an INVALID index is left behind, and you have to drop and recreate it.
📖 Answer
A regular CREATE INDEX takes a SHARE lock: reads work, but INSERT/UPDATE/DELETE wait until the index is built. On a big table that is minutes.
CONCURRENTLY scans the table twice and picks up the changes made in between. It's slower, but writes don't stop.
-- V31__orders_created_idx.sql
CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_orders_created_at
ON orders (created_at);
Key points for Flyway:
- with PostgreSQL, Flyway detects this itself and runs that migration without a transaction; in some versions, mixing transactional and non-transactional statements in one file raises an error. So I always put one
CONCURRENTLYper file; - if needed, you can set it explicitly in a config file next to the script (
executeInTransaction=falseinV5__index.sql.conf).
The failure case: on a deadlock or a unique violation, the index is left in an INVALID state. Queries don't use it, but it is updated on every write:
SELECT indexrelid::regclass FROM pg_index WHERE NOT indisvalid;
DROP INDEX CONCURRENTLY idx_orders_created_at;
IF NOT EXISTS doesn't help in that case, because the index name exists. So you need to check before retrying.
While the index is being built, long open transactions make CONCURRENTLY wait, which can also make the deploy hang. You can watch progress through pg_stat_progress_create_index.
Sign up to mark studied questions and save your progress.