NEW RasterizedDB 1.1.0 is out: sharding and the gateway, the message broker, roles and row-level security, compression, .NET on NuGet, and the enterprise edition. What's new ›
DOCS / RASTERIZEDDB SERVER / TRANSACTIONS

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

sql
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:

StatementEffect
BEGIN, BEGIN WORK, BEGIN TRANSACTION, START TRANSACTIONOpen a block. Transaction modes can follow (see below).
COMMIT, COMMIT WORK, COMMIT TRANSACTION, END, END WORK, END TRANSACTIONCommit the block.
ROLLBACK, ROLLBACK WORK, ROLLBACK TRANSACTION, ABORTDiscard everything the block did.
COMMIT AND CHAIN, ROLLBACK AND CHAINEnd 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:

sql
BEGIN ISOLATION LEVEL REPEATABLE READ, READ ONLY;
START TRANSACTION READ WRITE;
ModeMeaning
ISOLATION LEVEL READ COMMITTEDA fresh snapshot for every statement. The default.
ISOLATION LEVEL REPEATABLE READOne snapshot for the whole block.
ISOLATION LEVEL SERIALIZABLEAccepted, runs as REPEATABLE READ (see Isolation levels).
ISOLATION LEVEL READ UNCOMMITTEDAccepted, runs as READ COMMITTED.
READ ONLYAny write in the block fails with SQLSTATE 25006.
READ WRITEWrites allowed. The default.
DEFERRABLE, NOT DEFERRABLEAccepted 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.

sql
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;
StatementEffect
SAVEPOINT nameSet a savepoint.
ROLLBACK TO SAVEPOINT name, ROLLBACK TO nameUndo everything since the savepoint, including DDL. The savepoint stays set.
RELEASE SAVEPOINT name, RELEASE nameForget the savepoint; its work becomes part of the enclosing block.
  • ROLLBACK TO SAVEPOINT also 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 SAVEPOINT and COMMIT are accepted; SAVEPOINT and RELEASE are refused with 25P02.

Isolation levels

Two behaviours are offered, under the four standard names:

RequestedRuns asWhat a statement sees
READ UNCOMMITTEDREAD COMMITTEDA dirty read is never produced.
READ COMMITTED (default)READ COMMITTEDEverything committed before the statement began. Each statement takes a new snapshot.
REPEATABLE READREPEATABLE READEverything committed before the snapshot was fixed. One snapshot for the whole block.
SERIALIZABLEREPEATABLE READAs 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

sql
-- 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';
SettingScopeValues
default_transaction_isolationWhat a BEGIN that names no level gets.read committed, repeatable read, serializable, read uncommitted
default_transaction_read_onlyWhat a BEGIN that names no access mode gets.on / off (also true, false, yes, no, 1, 0)
transaction_isolationThe current block, as SET TRANSACTION.as above
transaction_read_onlyThe 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 TRANSACTION outside a block warns (25P01) and changes nothing.
  • Once a statement has run in a block, its level is fixed: changing it is refused with 25001 and 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:

CauseSQLSTATE
lock_timeout elapsed55P03
statement_timeout elapsed, or the statement was cancelled57014
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:

rust
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:

sql
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;
ClauseLock taken
FOR UPDATEExclusive: no other transaction may lock or write the row.
FOR NO KEY UPDATETreated as FOR UPDATE.
FOR SHAREShared: other FOR SHARE lockers are allowed, writers are not.
FOR KEY SHARETreated as FOR SHARE.
OptionWhen a row is already locked
(none)Wait for the holder, up to 10 seconds, then fail with an error naming the holder.
NOWAITFail at once with SQLSTATE 55P03.
SKIP LOCKEDLeave 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 55P03 on a row another transaction holds, where PostgreSQL would wait.
  • Otherwise it marks each row just before writing it. A FOR UPDATE that 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 with 55P03.

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

sql
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.

SettingDefaultWhat it boundsSQLSTATE when exceeded
statement_timeout0 (none)How long one statement may run.57014
lock_timeout0 (none)How long one lock wait may last, including the wait for a conflicting writer.55P03
idle_in_transaction_session_timeoutserver's --idle-in-transaction-session-timeout, 0How long a session may sit idle inside an open block. The session is ended and its block rolled back.25P03
idle_session_timeoutserver's --idle-session-timeout, 0How long a session may sit idle outside a block. The session is ended.57P05
sql
SET lock_timeout = '5s';
SET statement_timeout = 30000;
SHOW lock_timeout;
text
 lock_timeout
--------------
 5s

Set 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.

sql
-- 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;
ValueEffect
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, including CREATE TABLE … AS and CREATE TABLE … PARTITION BY
  • ALTER TABLE, including ALTER TABLE … RENAME TO
  • CREATE INDEX, CREATE UNIQUE INDEX, DROP INDEX
  • DROP 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 DATABASE
  • IMPORT (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

  • SERIALIZABLE runs as REPEATABLE READ and does not detect write skew.
  • A plain SET inside a block that is then rolled back is not undone (PostgreSQL undoes it). SET LOCAL does end with its block.
  • A locking read waits at most 10 seconds for a row lock; this bound is fixed.
  • An UPDATE or DELETE that finds a row already locked by FOR UPDATE when it starts fails with 55P03 instead 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_timeout for clients that may leave one open. See Maintenance.
  • Two-phase commit (PREPARE TRANSACTION) is not part of the released server.
✓ page rendered in 176 µs axum + tera + htmx · no other javascript