Best Practices for Safe PostgreSQL Schema Migrations
When you change a PostgreSQL schema in production, the database has to keep serving queries while you roll out new application versions…
When PostgreSQL runs overlapping transactions, it needs rules that control which changes each transaction can see. A transaction is a group of database statements that PostgreSQL commits or rolls back as a single unit. You set an isolation level to tell PostgreSQL which committed changes a transaction can read and when it should abort a transaction that could leave the database in an inconsistent state.
For most work, you can stick with PostgreSQL’s default, READ COMMITTED. Pick REPEATABLE READ when several statements in one transaction need a single stable view of the data. Pick SERIALIZABLE when concurrent transactions must end up with the same result as some one-at-a-time ordering, and build your application to retry transactions that PostgreSQL aborts. PostgreSQL uses multiversion concurrency control (MVCC), which lets statements read older versions of rows without generally blocking concurrent writers. The isolation level controls how PostgreSQL builds those views.
PostgreSQL accepts four standard SQL isolation-level names, though they produce only three distinct behaviors. READ UNCOMMITTED behaves the same way as READ COMMITTED. PostgreSQL’s documented anomaly table lays out how the remaining levels differ.
Four read anomalies explain what each level prevents. A dirty read exposes another transaction’s uncommitted change. A nonrepeatable read happens when a transaction reads a row a second time and sees a change that another transaction committed in between. A phantom read happens when a transaction runs the same query again and gets a different set of matching rows. A serialization anomaly happens when concurrent transactions commit results that no one-at-a-time ordering could produce. A snapshot is the set of row versions a transaction can see at a given point in time.
| Level | What PostgreSQL guarantees | Practical use |
|---|---|---|
READ UNCOMMITTED |
Behaves like READ COMMITTED; dirty reads do not occur. |
Choose READ COMMITTED instead so the code reflects the actual behavior. |
READ COMMITTED |
Each statement sees data committed before that statement began. | Use for ordinary work that does not depend on a stable view across multiple statements. |
REPEATABLE READ |
Statements share one snapshot set by the transaction’s first query or data-changing statement. PostgreSQL also prevents phantom reads at this level. | Use when several statements need one stable snapshot. |
SERIALIZABLE |
Successfully committed transactions behave as though they ran in some serial order. | Use when concurrent work must preserve a rule across multiple rows or tables. |
PostgreSQL’s REPEATABLE READ is stronger than the SQL standard’s minimum regarding phantom reads. Even so, it still allows serialization anomalies, so a stable snapshot alone does not make concurrent transactions behave as if they ran one at a time.
READ COMMITTED for statement-by-statement workAt READ COMMITTED, PostgreSQL gives each ordinary SELECT a fresh view of committed data when that statement starts. If another transaction commits a change between your first and second queries, your second query will see it.
This fits routine work where each statement can act on the latest committed data and the transaction does not rely on one frozen snapshot. On its own, READ COMMITTED does not protect a rule that spans multiple reads and writes. If your transaction sums values across several rows and then updates one row based on that total, another transaction may have changed those rows after your first query ran.
Updating commands behave a bit differently. If an UPDATE, DELETE, or locking read hits a row that another transaction has already changed, PostgreSQL can wait for that transaction to finish and then recheck the WHERE condition against the updated row. That lets a single command react to concurrent changes, though it still does not protect a multi-statement business rule. PostgreSQL explains this behavior in its transaction-isolation documentation.
REPEATABLE READ for a stable snapshotAt REPEATABLE READ, PostgreSQL gives the transaction one snapshot, set when the transaction runs its first query or data-modification statement. Every later statement in that transaction sees the same view, even if other transactions commit changes while it runs. Use this level for multi-step reads that need consistent numbers from a single point in time.
A stable snapshot still allows concurrent outcomes that break business rules. Imagine a schedule rule that requires at least one of two doctors to stay on call. Two transactions each check the table, see that both doctors are on call, and then each takes a different doctor off call. Under REPEATABLE READ, both transactions work from their initial snapshots and commit, leaving no doctor on call. Each transaction saw a consistent snapshot, yet their combined result could never happen if they had run one after the other.
Concurrent updates can also cause PostgreSQL to abort a REPEATABLE READ transaction. When that happens, your application has to rerun the entire transaction so it starts with a fresh snapshot. Use REPEATABLE READ when you need snapshot consistency, and reach for SERIALIZABLE or a carefully scoped lock when you need to enforce cross-row rules.
SERIALIZABLE to protect cross-row rulesAt SERIALIZABLE, PostgreSQL watches for patterns of concurrent reads and writes that could cause a serialization anomaly. It tracks those dependencies using predicate-locking mechanisms. These predicate locks do not block reads or writes. Instead, when PostgreSQL spots a dangerous pattern, it aborts one of the transactions before an inconsistent result can commit.
In the on-call doctor example, SERIALIZABLE guarantees that the committed transactions match some one-at-a-time order. PostgreSQL may abort one of the two transactions, and your application can retry it against the updated schedule. PostgreSQL’s application-level consistency guidance recommends SERIALIZABLE transactions when you need serializable behavior, and points to explicit locks as another option when you need to protect specific rows or tables.
SERIALIZABLE does not prevent every constraint error. Concurrent transactions can still trigger a unique-constraint violation even if each transaction checked that a key was missing before inserting it. Handle constraint errors based on what the operation is doing rather than assuming SERIALIZABLE makes every failure safe to retry.
PostgreSQL reports serialization failures with SQLSTATE 40001. When you see that code, retry the whole transaction, including the application code that chose the queries and values. If you retry only the statement that failed, your code may reuse decisions made from an outdated view of the data. PostgreSQL does not retry transactions on its own because only your application knows whether replaying that logic is safe. PostgreSQL’s serialization failure guidance details this requirement.
Deadlocks return SQLSTATE 40P01, and retrying the full transaction is often appropriate there as well. Unique violations (23505) and exclusion violations (23P01) can happen because of concurrent writes, though they can also signal persistent bugs or bad input, so avoid retrying them blindly. Put a cap on retry attempts that fits your workload, and make sure the transaction is safe to run more than once. PostgreSQL does not prescribe a standard retry count or delay.
PostgreSQL also does extra monitoring work for SERIALIZABLE transactions. That overhead does not automatically make SERIALIZABLE slower than explicit locking. Performance depends on your workload, how often transactions conflict, your query plans, and how often PostgreSQL aborts transactions for retry. Test both approaches under realistic traffic before deciding which one performs better for your system.
You can set the isolation level when you start a transaction:
BEGIN ISOLATION LEVEL SERIALIZABLE;
-- transaction work
COMMIT;
You can also use SET TRANSACTION, as long as you run it before the transaction’s first query or data-changing statement. PostgreSQL documents the full syntax in START TRANSACTION and SET TRANSACTION. For related syntax and configuration options, see how to set PostgreSQL transaction isolation levels.
Start with READ COMMITTED when each statement can read its own fresh committed view and the transaction does not enforce a cross-row rule. Move to REPEATABLE READ when several statements need one stable snapshot. Use SERIALIZABLE when correctness depends on concurrent transactions matching some one-at-a-time order, and make your application retry the full transaction on 40001 errors.
If you stay on a lower isolation level and need to protect specific rows, use explicit locks and check that their scope covers every conflicting change. For advice on rolling out and monitoring these settings in live systems, see managing PostgreSQL transaction isolation.
Give Vroni a GitHub issue, bug report, spec, or rough idea. It reads the repo, plans the change, writes code, runs checks, and works toward a review-ready pull request.
Take a look at vroni.com