You need to add an index and a column to a 500-million-row table that's written to constantly. How do you avoid locking it?
AdvancedScenarioData and databases
Answer
Situation read → Some DDL takes locks that block writes for the whole operation. On a big hot table that's an outage. Use the online variants.
What I'd do →
- PostgreSQL index: build it concurrently (no write lock; can't run inside a transaction).
CREATE INDEX CONCURRENTLY idx_orders_customer ON orders (customer_id);
If it fails it leaves an INVALID index; drop it and retry.
2. PostgreSQL column: adding a nullable column, or one with a constant default, is metadata-only in PG 11+. Set lock_timeout so the brief lock never queues behind a long query and blocks everyone.
SET lock_timeout = '3s';
ALTER TABLE orders ADD COLUMN channel text;
- MySQL: use
ALGORITHM=INSTANTwhere supported, otherwise gh-ost or pt-online-schema-change, which copy into a shadow table and swap. - Run it off-peak, watch replication lag, and throttle if replicas fall behind.
Why → lock_timeout matters because a waiting ALTER blocks every query behind it, even if the ALTER itself is fast.
Interview tip → Explain the lock queue problem; it's the reason "instant" DDL still causes outages.
More on Data and databases
A release needs to rename a column that the running app reads and writes. How do you do it with zero downtime?IntermediateHow do you prove your database backups actually work?IntermediateDesign backups for an RDS PostgreSQL database with RPO of 5 minutes and RTO of 1 hour, including a region failure.AdvancedYour migrations run in an init container and two pods ran them at the same time during a deploy, leaving the schema half-applied. How do you fix the approach?IntermediateUpgrade RDS PostgreSQL from 13 to 17 with minimal downtime. How?AdvancedUsers see stale data right after saving because reads go to a replica with lag. How do you handle it?Intermediate