Choose an Isolation Level
Two customers book the last pottery wheel. Reproduce the write skew in PostgreSQL, retry a serializable transaction, and compare the result with a constraint or a lock.
Expert · Lesson 10 of 12
Software Architecture
Move a live parcel table from a Boolean to a service code. Backfill in batches, find stale values, and prove when label readers can switch.

A courier depot is scanning parcels while you change how the booking system records service class. Today the label printer reads a Boolean called express. Tomorrow it will read a text code. On a quiet test database you could rewrite the column and redeploy the printer. At the depot, an old worker may still print a label for a parcel a new server has just accepted. If the two disagree, a paid express parcel can enter the standard delivery cage without causing a single application error.
Use a deliberately small mapping. An express parcel gets X and a standard parcel gets S. During this change those are the only permitted services. A proposed evening service needs a later release because an old Boolean reader cannot represent it. Assume the existing column is declared NOT NULL and each parcel has a stable integer primary key named id. These details determine whether the transformation is reversible. If historical nulls mean “the customer has not chosen yet,” mapping them to standard would invent a decision.
Draw the path of one parcel before writing the migration. The booking API inserts it, a supervisor can change its priority, and the label worker reads it hours later. A nightly import also updates existing bookings. An API release reaching every web server proves little about that import. Record who can write the old column, who reads it, how to identify each running version, and how long a queued job can survive its producer. Include the script operators use when the booking screen is down.
Our first compatibility rule is that the Boolean remains authoritative until every writer has been upgraded. During that interval all readers use it. A new code may be missing or stale while old writers are still running. That is acceptable because no label is printed from it yet. A second rule applies after the writer rollout. Every successful insert or priority change sets both values from the same decision in the same transaction. Sending two independent requests to update the columns breaks that rule if the process dies between them.
Add a nullable column without a default in a short transaction. The command is cheap in terms of data movement, yet it still needs a table lock. A long reporting transaction can make a fast schema change wait, and arriving requests may queue behind that wait. Here is a sample acquisition budget for a rehearsal. On timeout, roll back the failed transaction, inspect what holds the lock and choose another opportunity. A one-second timeout is a policy choice for this example.
BEGIN;
SET LOCAL lock_timeout = '1s';
ALTER TABLE parcel ADD COLUMN class_code text;
COMMIT;
Keep the schema transaction separate from deployment and backfill. Putting all three in one migration transaction can retain the schema lock while millions of rows are processed. Rehearse with an old client as soon as the column exists. Test a real insert, read and priority edit. Pay attention to consumers that decode a positional SELECT star result, exporters that promise a fixed column order, and code that treats an unfamiliar field as an invalid response.
Suppose parcels 101, 102 and 103 carry false, true and false respectively. All three initially have a missing code. Deploy the compatible writer to the API, workers, import and operator path. A new express booking numbered 104 now arrives with true and X in one commit. Drain remaining old writers and finish or replace long-lived transactions before trusting that future changes will obey the rule. Keep the label reader on the Boolean throughout this stage.
Consider a race during deployment. A new writer inserts parcel 105 as standard with code S. An older import subsequently upgrades its Boolean to true and leaves S in place. This parcel will never be selected by a worker looking for missing codes. Draining the old writers ends the cause of the divergence, but the bad value survives. We will audit both missing values and populated disagreements. A migration that merely counts how many rows have a new value would certify this mislabelled parcel.
Run the following batch repeatedly, committing each invocation independently. The primary key makes the join one to one. The worker locks its chosen rows and computes the result from the row in the database. It never sends a cached spreadsheet of old priorities back to the server. PostgreSQL documents this pattern and the interpretation of affected rows in its UPDATE reference.
WITH batch AS (
SELECT id FROM parcel
WHERE class_code IS NULL AND express IS NOT NULL
ORDER BY id LIMIT 500 FOR UPDATE SKIP LOCKED
)
UPDATE parcel AS p
SET class_code = CASE WHEN p.express THEN 'X' ELSE 'S' END
FROM batch
WHERE p.id = batch.id AND p.class_code IS NULL
RETURNING p.id;
For a hand rehearsal, reduce the limit to two. With no competing lock, the first invocation returns IDs 101 and 102 in unspecified output order. Their codes become S and X. The second invocation handles 103. Parcel 104 needs no work, while 105 deliberately remains a discrepancy for the audit. If a worker dies before committing a batch, that batch rolls back. If it dies after committing but before acknowledging success, rerunning the selection skips its completed rows. No separate cursor has to agree with the commit.
To see the cost of that convenience, hold a row lock on 101 in another session before the first batch. Other rows can make progress, and a later pass picks up 101 after the lock is released. An empty batch can therefore mean that every remaining candidate was locked. It cannot certify completion. Do not advance an irreversible high-water mark past skipped rows. For a large backlog, consider bounded primary-key ranges with explicit revisits so repeated searches for the remaining nulls do not continually scan the completed prefix. The SELECT locking clause describes what a skipping reader can see.
Size the batches against traffic at the depot. Measure booking latency, replica replay delay, write-ahead log generation and the time spent in each batch. For example, if the depot agrees on a two-second maximum replica delay for label reads and the delay climbs to five seconds, pause the backfill and let replay catch up. A smaller batch shortens each individual transaction but can add overhead for the same total work. Judge the setting by the service customers receive and the time needed to clear the backlog. Keep the writer compatibility code running during a pause.
After the old writers are drained and the initial batches finish, run the audit below. Both numbers come from one statement snapshot. With the five sample parcels, after the two clean batches you expect missing to equal zero and wrong to equal one. Find the offending row by selecting its ID with the same discrepancy predicate. Repair it under a row lock using the current Boolean as the source. If an operator has already corrected the priority, recompute under that lock. Recording the old audit value in a later unconditional update can undo the operator's change.
SELECT count(*) FILTER (WHERE class_code IS NULL) AS missing,
count(*) FILTER (
WHERE class_code IS NOT NULL AND class_code IS DISTINCT FROM
CASE WHEN express THEN 'X' ELSE 'S' END
) AS wrong
FROM parcel;
Once the known discrepancies are repaired, install a check constraint in a short transaction using a bounded lock wait. The explicit null test matters because an ordinary SQL check accepts an unknown result. The legacy Boolean already excludes null. The following declaration enforces the mapping on new inserts and updates without immediately scanning historical rows. Perform validation separately so the stronger lock needed to install the constraint is released before the historical scan starts.
ALTER TABLE parcel ADD CONSTRAINT parcel_class_matches
CHECK (class_code IS NOT NULL AND
class_code = CASE WHEN express THEN 'X' ELSE 'S' END)
NOT VALID;
ALTER TABLE parcel VALIDATE CONSTRAINT parcel_class_matches;
A clean audit is evidence about one instant. Successful validation plus continued enforcement protects the handoff from that instant onward. If validation fails, keep readers on the Boolean, examine the remaining rows and correct them using the same authority. The constraint is already checking incoming writes; a forgotten old writer may now show up as a failed booking. Monitor application errors alongside database validation. Review lock requirements and the semantics of delayed validation in the PostgreSQL ALTER TABLE reference.
Switch a small set of label readers to the validated code. Print or simulate labels for both sample classes, compare the resulting routing cage and promised service, and observe errors and queue age. A correct code in storage cannot catch a printer that interprets X backwards. Expand to all readers once the comparison passes. Continue writing both representations during the rollback period. A reader rollback is then a configuration or application change with current data available on either path.
Before removing the legacy field, check background jobs, exports, views and prepared queries, including rarely used reports. Exercise a restart of the oldest version still permitted for rollback. When the team closes that rollback window, retire binaries that reference the old column. Coordinate the final writer transition explicitly. For example, briefly gate writes and drain in-flight writers, install the final code-only constraints requiring S or X and a non-null value, remove the cross-column check and legacy column, and switch to the prepared code-only writer before reopening writes. Rehearse that short gate and its abort point. If even that interruption violates the service budget, use an additional compatibility release or database bridge and demonstrate the overlapping versions in rehearsal.
Repeat the five-parcel example with 102 temporarily locked and 105 still inconsistent. Your worker reports zero eligible rows while 102 is locked. The release manager asks to switch all label printers now. Give a decision and name the observations that would change it.
Keep the old reader. Release the lock, finish the missing row, repair 105 from its current priority, and require zero missing and zero disagreements plus successful constraint validation. Demonstrate one standard and one express label through the new reader and a working fallback during the rollback window. The decisive evidence is that every parcel eligible for printing has a valid route and that the next booking preserves that property.
YOUR TAKE
Choose one reaction for this article.
A cookie helps limit repeat responses. Your feedback is private.