The interview problem
A service has 500 million account rows and 10,000 foreground updates per second. Replace a legacy notification boolean with a notification-mode field. Initially the modes are enabled and disabled; later the product will add digest. Design the migration while application versions roll gradually and writes remain available. Explain backfill races, validation, capacity, cutover and rollback.
Original system-design practice, not a reported company interview. Workload assumptions are hypothetical. PostgreSQL 18 documentation informs implementation caveats; interview date not applicable. Sources retrieved September 27, 2026.
1. Separate representation change from new behavior
Define f(true) = enabled and f(false) = disabled. Assume the legacy boolean is non-null. During compatibility, require mode = f(legacy) for migrated rows and all new writes. A null mode temporarily means the historical row still needs migration.
The third state, digest, cannot be represented losslessly by the boolean. Do not enable it while old writers, readers or rollback binaries still require the two-state model. Adding a column is a schema change; introducing an unrepresentable business state changes the compatibility contract.
Inventory every writer: API versions, scheduled jobs, imports, repair scripts and replication paths. An application deployment percentage is not proof that all writers follow the new rule. Define availability as bounded disruption under an explicit latency budget; online migration does not mean every database operation takes no locks.
2. Give each phase one write authority
migration controller: version, phase, ownership and evidence
↓
expand schema → install compatibility behavior
↓
range workers → short backfill transactions
↓
validate historical rows + enforce future writes
↓
change reads → retire incompatible writers
↓
change write authority → enable new semantics → contractFor this design, use a database compatibility trigger that derives mode from the legacy boolean on inserts and updates. The boolean remains authoritative during the first phase. New application versions can read mode with a legacy fallback while continuing to express writes through the boolean. The trigger must cover every relevant update, including backfill updates, and must not be bypassed by an overlooked write path.
This is a proposed design choice, not a claim that all replication or bulk-import configurations fire triggers identically. Verify coverage, privileges and failover behavior in the actual database setup. An alternative is transactional application dual-writing, but that requires upgrading every writer before relying on it. Two independent writes can fail halfway.
| Phase | Write authority | Reader behavior |
|---|---|---|
| Expansion and backfill | Legacy boolean; derive mode | Legacy or mode with fallback |
| Read cutover | Legacy boolean; derive mode | Validated mode |
| New writer cutover | Mode, after legacy writers are fenced out | Mode-aware readers |
| New semantics and contraction | Mode, including digest | Only compatible readers and recovery binaries |
A period with two competing authorities is not resolved by calling both writes “dual writes.” State which value wins, how conflicts are rejected and when that rule changes.
3. Expand with bounded operational impact
Add the new nullable field, inspect the exact DDL behavior for the database version, and avoid combining unrelated operations into one statement. Even a change that avoids rewriting every row can need a strong metadata lock. Set bounded lock waits and schedule retries; a long transaction can prevent an otherwise short schema change from acquiring its lock.
Install and verify compatibility behavior before scanning historical rows. Exercise old and new application versions, direct maintenance paths and inserts during backfill. Establish rollback for this phase before starting: old reads can continue while the old representation remains authoritative.
Keep the migration controller's phase, transformation version, completed ranges and error ledger durable. Permit only the current controller owner to advance phases. A stale worker must not announce completion for a newer migration version.
4. Prevent a stale backfill from undoing a live update
Consider an unsafe implementation without an effective backfill guard or enforcing trigger:
1. Worker reads legacy=false at revision 7. 2. Foreground request sets legacy=true at revision 8. 3. Compatibility write sets mode=enabled. 4. Worker blindly stores its old computed mode=disabled.
The last step destroys the invariant. Compute from the current locked row inside the update, or use a compare-and-set condition on the source revision and retry when it changes. A condition that the row is still unmigrated can also prevent overwriting a newer populated value. In this design, the compatibility trigger derives mode from the current legacy value on every update, providing another enforcement layer.
Test the actual statement and isolation behavior with concurrent writers. A safe database-side transformation does not make an arbitrary ORM read-modify-write safe. A worker that writes a stale full row can still overwrite the legacy boolean itself, and ordinary foreground lost-update prevention remains necessary.
Use small key-range transactions and persist completion after commit. A crash after commit but before checkpointing causes harmless replay when the operation is idempotent. If workers skip locked rows, track those rows or ranges as unfinished debt and revisit them. Advancing a maximum-ID checkpoint is not proof that every preceding row was processed.
Do not resurrect deleted rows. Inserts after the initial high-water mark must be covered by the write invariant. Gaps in identifiers are normal; completion is about required rows and values, not a contiguous sequence of IDs.
5. Size the backfill against the limiting resource
At 5,000 rows per second, the scan-and-update work alone takes:
500,000,000 / 5,000 = 100,000 seconds
= 27 hours 46 minutes 40 secondsWith 1,000-row chunks this is 500,000 chunks. A serial worker taking 200 milliseconds per chunk achieves that rate only if the throughput stays stable. Retries, pauses, validation and maintenance extend the elapsed time.
Now assume each backfill update generates 1 KB of write-ahead log, and foreground writes average the same hypothetical amount:
backfill WAL = 5,000 × 1 KB = 5 MB/second foreground WAL = 10,000 × 1 KB = 10 MB/second combined WAL = 15 MB/second replica sustainable replay = 12 MB/second backlog growth = 3 MB/second = 10.8 GB/hour
The raw extra backfill WAL is 500 GB over the full migration. These are decimal units and workload assumptions, not PostgreSQL guarantees. Full-page images, indexes, row width and other activity can change measured log volume.
With 10 MB/second already consumed by foreground work, the stated replica budget leaves only 2 MB/second for backfill, or a theoretical 2,000 rows per second. At that rate:
500,000,000 / 2,000 = 250,000 seconds
= 69 hours 26 minutes 40 secondsRunning exactly at the replica's stated capacity leaves no burst or recovery headroom. Choose a lower operating target or improve capacity. Throttle using measured replica lag, foreground latency, log generation, disk space and maintenance pressure. Adding workers can make the bottleneck worse rather than shortening the safe migration.
6. Prove completeness while new writes remain valid
Validate both presence and meaning. Suppose 499.9 million rows have non-null mode and 100,000 remain null. The null rate is 0.02%, but the migration is not complete. If another 20,000 non-null rows disagree with the legacy boolean, there are 120,000 invalid rows, or 0.024% of the table. A null-only dashboard misses the semantic errors.
Keep the future-write invariant active throughout validation so rows already checked cannot become invalid behind the scan. Use authoritative state and a documented consistency boundary; a lagging replica can make a correct primary appear incomplete or conceal recent changes. Compare shadow reads before changing the primary read path.
For supported constraint types, PostgreSQL 18 permits adding a constraint without initially validating historical rows, then validating separately. New writes are still checked. Validation scans and takes a lock, though it need not block ordinary updates in the same way as an immediate full validation. Confirm the exact constraint and lock behavior rather than applying this pattern indiscriminately to uniqueness or every schema operation.
For an explicit check, account for SQL null semantics: a condition that evaluates to unknown may not reject a null. Required presence and equality need a constraint expression that actually establishes both. Passing counts or samples is useful evidence, but required integrity should have a complete validation and continued enforcement story.
7. Treat index creation as a separate stateful operation
Create a new index only if the new query path needs it. PostgreSQL's concurrent index build allows writes to continue but still performs scans, waits for transactions and consumes resources. Failure can leave an invalid index that is unavailable to queries while still adding update overhead. Check validity and follow a documented repair or retry procedure.
A concurrent index build cannot run inside an ordinary transaction block. Do not wrap the entire migration in one enormous transaction and assume all online operations remain available. Record index state separately from row-backfill state; completion of one does not prove completion of the other.
8. Make the rollback boundary explicit
During read cutover, the boolean is still authoritative and mode agrees with it. Reverting reads is straightforward within that contract. Next deploy writers capable of operating under the new authority, retire or fence all legacy writers, and coordinate the change of write policy with removal or replacement of the legacy-derived trigger. A trigger that still derives from the boolean would erase new-mode writes. Update compatibility constraints at the same boundary: an equality constraint tying mode to the boolean cannot remain unchanged once digest is allowed. Before enabling digest, replace it with constraints on the new authoritative domain and required presence, while keeping incompatible writers fenced out.
Keep digest disabled until every required reader, writer and approved rollback binary understands it. Once digest is written, the old boolean cannot faithfully represent all business state. Rolling back to an old application binary may discard meaning even when the old column still exists. Recovery may require a forward fix or an explicitly approved conversion with known information loss.
Only contract after the observation window, dependency review and recovery checks. Remove old reads and writes before dropping their storage. Review jobs, analytics consumers, exports and restoration procedures too. A backup from before cutover is not a no-loss rollback if later writes must be retained.
Dropping an old column is not a promise of immediate disk reclamation. Treat storage cleanup and logical schema contraction as separate operational concerns.
9. Test the migration, not only the final schema
| Failure | Risk | Response |
|---|---|---|
| Long transaction blocks DDL | Lock waits disrupt requests | Bound waits, inspect blockers and retry deliberately |
| Uninventoried old writer | Values diverge after validation | Enforce the write contract and fence incompatible paths |
| Worker crash | Checkpoint and data disagree | Commit before checkpoint; replay idempotently |
| Hot rows keep being skipped | False completion | Track and resolve skipped work explicitly |
| Replica falls behind | Stale reads and recovery risk | Throttle using measured resource budgets |
| Digest reaches old code | Lossy interpretation or overwrite | Gate new semantics until incompatible versions are retired |
Inject a foreground update between backfill read and write, crash around commit and checkpoint, fail over during a phase and test an invalid index build. Monitor foreground latency, error rates, unfinished rows, mismatches, lag and available disk. A migration is not accepted merely because a worker reached the end of the key range.
Trade-offs and follow-ups
Database compatibility logic centralizes coverage but adds operational complexity and write overhead. Application dual-writing makes behavior visible in code but requires complete writer coordination. A shadow-table approach can suit major rebuilds, at the cost of another change stream, ordering rules and cutover protocol. Choose based on the transformation and workload, not a universal preference.
- What if digest is already stored? Stop treating old-code rollback as lossless; preserve the new values and choose a compatible recovery path.
- Can a sample prove every row is correct? No. Use it for diagnosis and confidence during rollout, with a complete integrity validation before claiming completion.
- Why not use one giant transaction? Long locks, log retention, contention and recovery impact can defeat availability goals.
- What if the transformation is not invertible? Preserve needed source information and define the point beyond which rollback requires a business decision.
Self-review rubric
A strong answer names the authority at each phase, establishes compatible writes before backfill, prevents stale updates and makes retries idempotent. It sizes the migration against replica and foreground budgets, validates values as well as coverage and distinguishes read rollback from semantic rollback. An excellent answer handles hidden writers, skipped rows, lock waits and restoration after new states have been introduced.
Sources and attribution
- PostgreSQL 18: ALTER TABLE — version-specific locking, constraint validation and column-removal behavior.
- PostgreSQL 18: CREATE INDEX — concurrent build behavior, invalid indexes and transaction restrictions.
Retrieved September 27, 2026; documentation publication dates unstated. Check the deployed version before applying operational details. The architecture, notification example, capacity assumptions and worked calculations are original practice, with no company interview attribution.
Continue your preparation
Choose a connected learning path or browse more System design questions. Read our editorial method and attribution policy.