Transactions
A transaction is a group of statements that commit together or roll back together. In Rust you begin a transaction on a connection, run queries on that handle, and commit — or drop the handle and roll back.
Detailed Explanation
Two inserts that must both happen — a user and their default workspace — belong in one transaction. Without it, a crash after the first insert leaves an orphan. BEGIN / COMMIT / ROLLBACK are the SQL words. SQLx's pool.begin(), Diesel's connection.transaction(|| ...), and SeaORM's db.transaction are the Rust words.
Drop without commit is rollback in the async crates. That is the RAII story: an early ? drops the transaction and undoes the work. You do not write a finally that rolls back. You do write commit().await? on the success path. Forgetting commit is a silent rollback that looks like "the insert succeeded in the logs" if you logged before commit.
Isolation is a separate knob (READ COMMITTED, REPEATABLE READ, SERIALIZABLE). The default depends on the engine. Lost updates and phantom reads are still possible at low isolation. You pick a level when you have a known anomaly, not because it sounds strict. Higher isolation aborts more transactions; you retry.
Do not hold a transaction open while you call a remote HTTP API. You hold a connection from the pool for the whole time. The pool empties, other requests wait, and you have coupled a network timeout to a database lock. Do the remote call before or after, not in the middle.
When you open a transaction: multi-row writes that must be atomic, read-modify-write that needs a consistent snapshot. When you do not: a single INSERT (already atomic) or a read that can be stale.
Savepoints (BEGIN then SAVEPOINT) let you roll back a nested piece without killing the outer transaction. Rust wrappers expose this unevenly. If you think you have a nested transaction, read the crate docs; you may have an independent connection and no atomicity at all. One connection, one transaction, explicit savepoints if you need them.
Code Examples
struct Tx {
committed: bool,
}
impl Drop for Tx {
fn drop(&mut self) {
if !self.committed {
println!("rollback");
}
}
}
fn main() {
{
let mut tx = Tx { committed: false };
tx.committed = true;
println!("commit");
}
// prints:
// commit
}Common Gotchas
Drop rolls back
A missing `commit` looks like a successful function that stored nothing. Always commit on the happy path.
Do not await a foreign HTTP call inside a transaction
You hold a pool connection and possibly row locks. Split the steps.
A single statement is already atomic
A transaction around one `INSERT` adds only round-trips unless you need it for a later read of that row in the same snapshot.
Retries need idempotency
A serialisation failure should retry the transaction, not a half-applied business action you already emailed about.