Transactions
RasterizedDB runs every statement inside a transaction. Use an explicit BEGIN … COMMIT block whenever several statements must succeed or fail together, and use this page to choose an isolation level, handle write conflicts, lock rows, and decide how durable each commit must be.
The engine uses multi-version concurrency control (MVCC): an update writes a new version of the row instead of overwriting it, and each statement reads through a snapshot. Readers never wait for writers, uncommitted work is invisible to other sessions, and a rollback undoes inserts, updates and deletes alike.
Transaction blocks
BEGIN;
UPDATE accounts SET balance = balance - 100 WHERE id = 1;
UPDATE accounts SET balance = balance + 100 WHERE id = 2;
COMMIT;Every PostgreSQL spelling is accepted:
| Statement | Effect |
|---|---|
BEGIN, BEGIN WORK, BEGIN TRANSACTION, START TRANSACTION | Open a block. Transaction modes can follow (see below). |
COMMIT, COMMIT WORK, COMMIT TRANSACTION, END, END WORK, END TRANSACTION | Commit the block. |
ROLLBACK, ROLLBACK WORK, ROLLBACK TRANSACTION, ABORT | Discard everything the block did. |
COMMIT AND CHAIN, ROLLBACK AND CHAIN | End the block and immediately open a new one with the same isolation level and access mode. AND NO CHAIN is the default. |
A BEGIN inside an open block is answered with a warning (SQLSTATE 25001) and the open block carries on. A COMMIT or ROLLBACK with no block open is answered with a warning (25P01) and does nothing.
Transaction modes
The modes can be written after BEGIN / START TRANSACTION, separated by spaces or commas:
BEGIN ISOLATION LEVEL REPEATABLE READ, READ ONLY;
START TRANSACTION READ WRITE;| Mode | Meaning |
|---|---|
ISOLATION LEVEL READ COMMITTED | A fresh snapshot for every statement. The default. |
ISOLATION LEVEL REPEATABLE READ | One snapshot for the whole block. |
ISOLATION LEVEL SERIALIZABLE | Accepted, runs as REPEATABLE READ (see Isolation levels). |
ISOLATION LEVEL READ UNCOMMITTED | Accepted, runs as READ COMMITTED. |
READ ONLY | Any write in the block fails with SQLSTATE 25006. |
READ WRITE | Writes allowed. The default. |
DEFERRABLE, NOT DEFERRABLE | Accepted and ignored. |
Failed blocks
When any statement inside a block fails, the block is marked failed. Every later statement is refused with SQLSTATE 25P02 ("current transaction is aborted, commands ignored until end of transaction block") until you end the block. A COMMIT of a failed block rolls it back and reports ROLLBACK. This guarantees that a block can never commit after silently skipping a statement that did not work.
To recover from one failed statement without losing the rest of the block, use a savepoint (next section).
A connection that drops while a block is open rolls the block back.
Multi-statement strings and batches
A query string holding several statements, such as INSERT …; INSERT …; sent in one simple-query message, runs as one implicit transaction, as in PostgreSQL: if a later statement fails, the earlier ones are rolled back too. The same applies to a pipelined batch of extended-protocol statements ending in one Sync. A BEGIN inside such a string turns the implicit transaction into an ordinary block that lasts until its COMMIT or ROLLBACK.
Transaction control statements, CREATE DATABASE, DROP DATABASE, ALTER DATABASE, VACUUM, CHECKPOINT, COPY and IMPORT never open an implicit transaction, so a string containing them runs statement by statement.
Savepoints
Savepoints mark a point inside a block that you can roll back to without abandoning the whole block. ORMs and drivers build "nested transactions" from them.
BEGIN;
INSERT INTO orders (id, customer_id) VALUES (1001, 7);
SAVEPOINT before_items;
INSERT INTO order_items (order_id, sku, qty) VALUES (1001, 'A-1', 2);
-- something went wrong with the items
ROLLBACK TO SAVEPOINT before_items;
INSERT INTO order_items (order_id, sku, qty) VALUES (1001, 'A-2', 1);
RELEASE SAVEPOINT before_items;
COMMIT;| Statement | Effect |
|---|---|
SAVEPOINT name | Set a savepoint. |
ROLLBACK TO SAVEPOINT name, ROLLBACK TO name | Undo everything since the savepoint, including DDL. The savepoint stays set. |
RELEASE SAVEPOINT name, RELEASE name | Forget the savepoint; its work becomes part of the enclosing block. |
ROLLBACK TO SAVEPOINTalso clears the failed state of a block, so the block can continue and commit.- A name can be reused. The newest savepoint with that name shadows the older one; rolling back to it leaves the older one standing.
- A savepoint name that does not exist is refused with SQLSTATE
3B001. - In a failed block only
ROLLBACK,ROLLBACK TO SAVEPOINTandCOMMITare accepted;SAVEPOINTandRELEASEare refused with25P02.
Isolation levels
Two behaviours are offered, under the four standard names:
| Requested | Runs as | What a statement sees |
|---|---|---|
READ UNCOMMITTED | READ COMMITTED | A dirty read is never produced. |
READ COMMITTED (default) | READ COMMITTED | Everything committed before the statement began. Each statement takes a new snapshot. |
REPEATABLE READ | REPEATABLE READ | Everything committed before the snapshot was fixed. One snapshot for the whole block. |
SERIALIZABLE | REPEATABLE READ | As REPEATABLE READ. Write skew is not detected. |
A single statement always reads through one snapshot, whatever the level: a join, a subquery, UPDATE … FROM, DELETE … USING and RETURNING all see the same consistent state, even while other sessions commit.
A transaction always sees its own uncommitted writes. A transaction that was still running when your snapshot was taken stays invisible to you even after it commits.
SERIALIZABLE is weaker than its name. Two transactions that each read a set of rows and then each write a row the other's read would have matched can both commit (write skew), because detecting that needs predicate locking, which this engine does not have. Conflicts on the same row are caught at both levels (see Write conflicts). If your application depends on true serializability, enforce the invariant with explicit row locks (SELECT … FOR UPDATE) or a constraint.
Setting the level
-- For one block, on BEGIN:
BEGIN ISOLATION LEVEL REPEATABLE READ;
-- For the current block, before its first query:
BEGIN;
SET TRANSACTION ISOLATION LEVEL REPEATABLE READ;
-- As the default for every later block in this session:
SET SESSION CHARACTERISTICS AS TRANSACTION ISOLATION LEVEL REPEATABLE READ;
SET default_transaction_isolation = 'repeatable read';| Setting | Scope | Values |
|---|---|---|
default_transaction_isolation | What a BEGIN that names no level gets. | read committed, repeatable read, serializable, read uncommitted |
default_transaction_read_only | What a BEGIN that names no access mode gets. | on / off (also true, false, yes, no, 1, 0) |
transaction_isolation | The current block, as SET TRANSACTION. | as above |
transaction_read_only | The current block, as SET TRANSACTION. | as above |
SET, SET LOCAL (inside a block), RESET and = DEFAULT all work, and SHOW transaction_isolation reports the level that actually runs (so a SERIALIZABLE block shows repeatable read). A value these settings do not take is refused with SQLSTATE 22023.
Rules that match PostgreSQL:
SET TRANSACTIONoutside a block warns (25P01) and changes nothing.- Once a statement has run in a block, its level is fixed: changing it is refused with
25001and fails the block.
Write conflicts and retries
Two transactions that change the same row cannot both win. What happens to the second one depends on its isolation level.
READ COMMITTED. A write that meets a row another transaction is changing waits for that transaction to end, then runs again against the newly committed data, as PostgreSQL does. If the row no longer matches the WHERE clause, it is skipped. The wait ends early on:
| Cause | SQLSTATE |
|---|---|
lock_timeout elapsed | 55P03 |
statement_timeout elapsed, or the statement was cancelled | 57014 |
| A deadlock was found (checked once a wait has lasted one second) | 40P01 |
REPEATABLE READ and SERIALIZABLE. A write to a row that another transaction changed after this transaction's snapshot was taken fails with SQLSTATE 40001 ("could not serialize access due to concurrent update"). The same happens to a SELECT … FOR UPDATE that locks such a row. Nothing of the failed statement was applied, and the block is now failed: roll it back and run the whole transaction again.
You can also see 40001 at READ COMMITTED in a rare case: two blocks that each insert a unique key the other has already written but not committed.
Treat 40001 and 40P01 as "run the transaction again". A retry loop in Rust with tokio-postgres:
use tokio_postgres::{error::SqlState, Client, Error, IsolationLevel};
fn retryable(e: &Error) -> bool {
matches!(
e.code(),
Some(code) if *code == SqlState::T_R_SERIALIZATION_FAILURE
|| *code == SqlState::T_R_DEADLOCK_DETECTED
)
}
async fn transfer(client: &mut Client, from: i64, to: i64, amount: i64) -> Result<(), Error> {
let mut attempt = 0;
loop {
attempt += 1;
let tx = client
.build_transaction()
.isolation_level(IsolationLevel::RepeatableRead)
.start()
.await?;
let work = async {
tx.execute(
"UPDATE accounts SET balance = balance - $1 WHERE id = $2",
&[&amount, &from],
)
.await?;
tx.execute(
"UPDATE accounts SET balance = balance + $1 WHERE id = $2",
&[&amount, &to],
)
.await?;
Ok::<(), Error>(())
}
.await;
let outcome = match work {
Ok(()) => tx.commit().await,
Err(e) => {
let _ = tx.rollback().await;
Err(e)
}
};
match outcome {
Ok(()) => return Ok(()),
Err(e) if retryable(&e) && attempt < 5 => continue,
Err(e) => return Err(e),
}
}
}The pattern is the same in any language: catch the error, check its SQLSTATE for 40001 or 40P01, roll back, and repeat the whole transaction (not just the failed statement), with a bounded number of attempts.
Locking rows
A locking clause on a SELECT locks the rows it returns until the transaction ends. The classic use is a job queue where each worker must claim different rows:
BEGIN;
SELECT id FROM job WHERE status = 'pending' ORDER BY id LIMIT 10 FOR UPDATE SKIP LOCKED;
UPDATE job SET status = 'running' WHERE id IN (1, 2, 3);
COMMIT;| Clause | Lock taken |
|---|---|
FOR UPDATE | Exclusive: no other transaction may lock or write the row. |
FOR NO KEY UPDATE | Treated as FOR UPDATE. |
FOR SHARE | Shared: other FOR SHARE lockers are allowed, writers are not. |
FOR KEY SHARE | Treated as FOR SHARE. |
| Option | When a row is already locked |
|---|---|
| (none) | Wait for the holder, up to 10 seconds, then fail with an error naming the holder. |
NOWAIT | Fail at once with SQLSTATE 55P03. |
SKIP LOCKED | Leave the row out of the result. |
FOR UPDATE OF table_name, … is accepted; the engine locks every relation the statement reads, which is never fewer rows than you asked for. A locking clause is refused (0A000) on a statement whose rows are not table rows, such as one with DISTINCT or a set operation (UNION / INTERSECT / EXCEPT).
How an UPDATE or DELETE meets a row someone has locked:
- If rows of the table are locked when the statement starts, it fails at once with
55P03on a row another transaction holds, where PostgreSQL would wait. - Otherwise it marks each row just before writing it. A
FOR UPDATEthat arrives after that waits for the writer's transaction to end. If the lock came first and the statement has written nothing yet, it waits for the holder and runs again; if it has already written other rows, it fails with55P03.
Once one transaction has written more than 1,024 rows of one table, its per-row marks become a single mark on the whole table until it ends: every FOR UPDATE on that table waits for it, NOWAIT fails with 55P03, and SKIP LOCKED skips every row. A batch job that updates thousands of rows of a queue table in one block therefore holds up every worker's claim on that table; run such jobs in smaller transactions.
Locking whole tables
BEGIN;
LOCK TABLE inventory IN SHARE ROW EXCLUSIVE MODE;
-- ...
COMMIT;LOCK [TABLE] name [, …] [IN mode MODE] [NOWAIT] takes PostgreSQL's eight modes: ACCESS SHARE, ROW SHARE, ROW EXCLUSIVE, SHARE UPDATE EXCLUSIVE, SHARE, SHARE ROW EXCLUSIVE, EXCLUSIVE and ACCESS EXCLUSIVE (the default). It can only be used inside a block and lasts until the block ends. With NOWAIT, a lock that cannot be granted at once fails with 55P03; otherwise the wait is bounded by lock_timeout.
Timeouts
These session settings bound how long a statement or a session may wait. Each takes a number of milliseconds or a value with a unit (ms, s, min, h, d), and 0 means no limit.
| Setting | Default | What it bounds | SQLSTATE when exceeded |
|---|---|---|---|
statement_timeout | 0 (none) | How long one statement may run. | 57014 |
lock_timeout | 0 (none) | How long one lock wait may last, including the wait for a conflicting writer. | 55P03 |
idle_in_transaction_session_timeout | server's --idle-in-transaction-session-timeout, 0 | How long a session may sit idle inside an open block. The session is ended and its block rolled back. | 25P03 |
idle_session_timeout | server's --idle-session-timeout, 0 | How long a session may sit idle outside a block. The session is ended. | 57P05 |
SET lock_timeout = '5s';
SET statement_timeout = 30000;
SHOW lock_timeout; lock_timeout
--------------
5sSet lock_timeout in migrations: a DDL statement waits for every open transaction that uses the table, and a bound turns an indefinite stall into an error you can retry.
Durability
By default a commit returns only after its log records are on disk (fdatasync). You can trade the last moments of durability for faster commits, per session or for the whole server.
-- This session only:
SET synchronous_commit = off;
-- Only for the current block (back to the previous value when it ends):
BEGIN;
SET LOCAL synchronous_commit = off;
INSERT INTO events (id, kind) VALUES (1, 'click');
COMMIT;
-- Back to following the server's setting:
RESET synchronous_commit;
SHOW synchronous_commit;| Value | Effect |
|---|---|
on (also local, remote_write, remote_apply, true, yes, 1) | A commit waits for its sync. |
off (also false, no, 0) | A commit returns once its records are written to the operating system; a background writer syncs them within wal_writer_delay (200 ms by default). |
With synchronous_commit = off, the server process crashing loses nothing, because the data is already in the operating system's cache. Only an operating-system crash or power loss can lose commits, and then only those from the last wal_writer_delay. The database cannot be corrupted either way: what is lost is whole transactions at the end of the log, never part of one.
The server-wide default comes from --synchronous-commit and --wal-writer-delay-ms, and a superuser can change it on a running server with SET CONFIG wal.synchronous_commit = off, which reaches sessions that are already open (unless they set their own value); see Configuration. SHOW wal_writer_delay reports the current delay. A transaction that only read data writes nothing to disk at commit.
DDL inside transactions
Most schema changes roll back with their block, as in PostgreSQL, so a migration that fails part-way leaves the schema as it found it and can simply be run again.
Transactional (undone by ROLLBACK, ROLLBACK TO SAVEPOINT, a failed block, a dropped connection, or a crash before the commit):
CREATE TABLE, includingCREATE TABLE … ASandCREATE TABLE … PARTITION BYALTER TABLE, includingALTER TABLE … RENAME TOCREATE INDEX,CREATE UNIQUE INDEX,DROP INDEXDROP TABLE(it is deferred and runs once the commit is durable; until then the block can still read the table)TRUNCATE(rows come back on rollback; the disk space is returned by the next vacuum)- role statements (
CREATE ROLE,GRANT, …)
A DDL statement in a block keeps its ACCESS EXCLUSIVE lock on the table until the block ends, so other sessions' reads and writes of that table wait until you commit or roll back. Before running, it copies aside the files it can change, so an ALTER TABLE of a large table inside a block takes longer than the same statement outside one.
Refused inside a block with SQLSTATE 25001 (run them on their own):
CREATE DATABASE,DROP DATABASEIMPORT(see Import from PostgreSQL)- converting a table to a partitioned one (
ALTER TABLE … PARTITION BY,CREATE INDEX … USING partition) and reshaping partitions (SPLIT PARTITION,MERGE PARTITIONS,ISOLATE KEY,SPLIT KEY); see Partitioning - branch statements (
CREATE BRANCH,DROP BRANCH,RESET BRANCH,PROMOTE BRANCH,MERGE BRANCH); see Branching DISCARD ALL
Migration tools that wrap every migration in a transaction usually let you turn that off for one migration (for sqlx, put -- no-transaction at the top of the file).
Sessions and connection pools
RESET ALL returns every setting of the session to its default. DISCARD ALL (refused inside a block) also deallocates prepared statements and closes portals; this is what pools such as Npgsql's send between borrowers.
Limits
SERIALIZABLEruns asREPEATABLE READand does not detect write skew.- A plain
SETinside a block that is then rolled back is not undone (PostgreSQL undoes it).SET LOCALdoes end with its block. - A locking read waits at most 10 seconds for a row lock; this bound is fixed.
- An
UPDATEorDELETEthat finds a row already locked byFOR UPDATEwhen it starts fails with55P03instead of waiting. - A transaction left open holds back space reclamation for every table: rows it might still need to see cannot be vacuumed. Keep blocks short and set
idle_in_transaction_session_timeoutfor clients that may leave one open. See Maintenance. - Two-phase commit (
PREPARE TRANSACTION) is not part of the released server.