Core Concepts
Transactions
Transactions are a critical part of any DBMS - they allow multiple discrete operations to be combined into atomic units of work. While a transaction is in-progress, any work it performs is not visible to concurrent transactions until the transaction has successfully completed. In SQL, transactions are performed via BEGIN and COMMIT commands.
Outside a Pyranid transaction, each operation borrows a connection and leaves transaction control to the configured DataSource and JDBC driver. Pyranid does not force autocommit=true or call commit() for standalone operations. Production pools normally return connections with autocommit enabled; configure that explicitly if your DataSource does not.
Code inside the Database::transaction(TransactionalOperation) closure operates within a transaction. Pyranid completes it after the callback finishes. A normal callback return does not establish commit: rollback-only completion can return normally, pre-commit validation can refuse an aborted or unverified transaction, and cleanup can fail after commit. Use an explicit outcome when application control flow needs those distinctions.
database.transaction(() -> {
// Anything that happens in here is part of the transaction.
// If an exception bubbles out, the transaction will be rolled back.
});
database.transaction(() -> {
// Anything that happens in here is part of the transaction.
// If an exception bubbles out, the transaction will be rolled back.
});
All data access performed via Database::query(String) detects the presence of a transaction on the current thread of execution and automatically participates when the transaction belongs to the same DataSource instance. This is usually the behavior you want. See the Context section below for more information on the mechanics, and for how to get a handle to the current transaction in order to manipulate it (e.g. creating a java.sql.Savepoint).
While less common, it is sometimes useful to share a transaction across multiple threads of execution. The Sharing Across Threads section below describes this functionality in more detail.
For performance reasons, no java.sql.Connection is fetched from the javax.sql.DataSource until the first data access operation occurs.
Basics
The canonical example - a bank transfer between two accounts.
database.transaction(() -> {
// Apply each adjustment to the current balance in the database.
long debited = database.query("UPDATE account SET balance = balance - :amount WHERE id = :id")
.bind("amount", amount)
.bind("id", 1)
.execute();
if (debited != 1)
throw new IllegalStateException("Source account does not exist");
long credited = database.query("UPDATE account SET balance = balance + :amount WHERE id = :id")
.bind("amount", amount)
.bind("id", 2)
.execute();
if (credited != 1)
throw new IllegalStateException("Destination account does not exist");
});
// For convenience, transactional operations may return values
Optional<BigDecimal> newBalance = database.transaction(() -> {
// Make some changes
long debited = database.query("UPDATE account SET balance = balance - 10 WHERE id = :id")
.bind("id", 1)
.execute();
if (debited != 1)
throw new IllegalStateException("Source account does not exist");
long credited = database.query("UPDATE account SET balance = balance + 10 WHERE id = :id")
.bind("id", 2)
.execute();
if (credited != 1)
throw new IllegalStateException("Destination account does not exist");
// Return the new value
return database.query("SELECT balance FROM account WHERE id = :id")
.bind("id", 2)
.fetchObject(BigDecimal.class);
});
database.transaction(() -> {
// Apply each adjustment to the current balance in the database.
long debited = database.query("UPDATE account SET balance = balance - :amount WHERE id = :id")
.bind("amount", amount)
.bind("id", 1)
.execute();
if (debited != 1)
throw new IllegalStateException("Source account does not exist");
long credited = database.query("UPDATE account SET balance = balance + :amount WHERE id = :id")
.bind("amount", amount)
.bind("id", 2)
.execute();
if (credited != 1)
throw new IllegalStateException("Destination account does not exist");
});
// For convenience, transactional operations may return values
Optional<BigDecimal> newBalance = database.transaction(() -> {
// Make some changes
long debited = database.query("UPDATE account SET balance = balance - 10 WHERE id = :id")
.bind("id", 1)
.execute();
if (debited != 1)
throw new IllegalStateException("Source account does not exist");
long credited = database.query("UPDATE account SET balance = balance + 10 WHERE id = :id")
.bind("id", 2)
.execute();
if (credited != 1)
throw new IllegalStateException("Destination account does not exist");
// Return the new value
return database.query("SELECT balance FROM account WHERE id = :id")
.bind("id", 2)
.fetchObject(BigDecimal.class);
});
Arithmetic updates avoid overwriting concurrent balance changes. These examples roll back if either account is missing; applications must still validate transfer amounts and enforce sufficient-funds and other business rules.
References:
Database::transaction(TransactionalOperation)Database::transaction(ReturningTransactionalOperation<T>)
Context
Transaction context belongs to the current Java thread. Database::currentTransaction() returns a handle to the transaction active in the current scope, if one exists.
The handle is useful for creating/restoring savepoints, marking as "force rollback", registering post-transaction operations, etc.
You cannot directly issue commits or rollbacks via Transaction. In order to provide a simple closure-based API, Pyranid performs those operations internally.
// Gets a handle to the current transaction, if any.
Optional<Transaction> transaction = database.currentTransaction();
// Output is "false"
out.println(transaction.isPresent());
database.transaction(() -> {
// A transaction only exists for the life of the closure
Optional<Transaction> actualTransaction = database.currentTransaction();
// Output is "true"
out.println(actualTransaction.isPresent());
});
// Gets a handle to the current transaction, if any.
Optional<Transaction> transaction = database.currentTransaction();
// Output is "false"
out.println(transaction.isPresent());
database.transaction(() -> {
// A transaction only exists for the life of the closure
Optional<Transaction> actualTransaction = database.currentTransaction();
// Output is "true"
out.println(actualTransaction.isPresent());
});
References:
Sharing Across Threads
Should you need to share the same transaction across multiple threads, use the Database::participate(Transaction, TransactionalOperation) API.
Transactions are scoped to the DataSource instance that created them. A second Database built with the same DataSource instance can participate in the transaction; a Database built with a different DataSource fails fast instead of silently joining the wrong connection.
On Java 21+, a clean way to do this is with a virtual-thread executor:
database.transaction(() -> {
database.query("UPDATE account SET balance = balance - 10 WHERE id = :id")
.bind("id", 1)
.execute();
// Get a handle to the current transaction
Transaction transaction = database.currentTransaction().orElseThrow();
try (ExecutorService executor = Executors.newVirtualThreadPerTaskExecutor()) {
CompletableFuture.runAsync(() -> {
// In a different thread and participating in the existing transaction.
// No commit or rollback will occur when the closure completes, but if an
// exception bubbles out the transaction will be marked as rollback-only
database.participate(transaction, () -> {
database.query("UPDATE account SET balance = balance + 10 WHERE id = :id")
.bind("id", 2)
.execute();
});
}, executor).join();
}
});
database.transaction(() -> {
database.query("UPDATE account SET balance = balance - 10 WHERE id = :id")
.bind("id", 1)
.execute();
// Get a handle to the current transaction
Transaction transaction = database.currentTransaction().orElseThrow();
try (ExecutorService executor = Executors.newVirtualThreadPerTaskExecutor()) {
CompletableFuture.runAsync(() -> {
// In a different thread and participating in the existing transaction.
// No commit or rollback will occur when the closure completes, but if an
// exception bubbles out the transaction will be marked as rollback-only
database.participate(transaction, () -> {
database.query("UPDATE account SET balance = balance + 10 WHERE id = :id")
.bind("id", 2)
.execute();
});
}, executor).join();
}
});
If you are already using an executor-based or virtual-thread-based concurrency model, the pattern is the same: capture the current Transaction on the originating thread, then call Database::participate(Transaction, TransactionalOperation) inside the worker thread.
Transaction Context Is Thread-Local
Pyranid transaction context follows the current Java thread. Async frameworks that suspend work and resume it on another thread do not automatically carry the transaction context with them. This includes Kotlin coroutines when a suspension point resumes on a different dispatcher thread. Keep transactional database access on the transaction thread, or capture the current Transaction and call Database::participate(...) on the thread that performs the database work. All participating work must complete before the owning transaction closure returns.
If a participating thread is interrupted while waiting for another participant to release the transaction connection, Pyranid restores the interrupt flag and throws DatabaseException. This makes blocked participants cancellable; the thread currently executing a JDBC call still relies on driver behavior, Query::queryTimeout(...), or application-managed Statement::cancel().
Failure-derived interruption from a participate(...) callback follows a separate 4.9 rule: the flag is restored after the borrowed context is removed only when no Pyranid transaction remains bound on that thread. A worker with no prior transaction gets restoration on exit; same-thread participation inside its owner does not newly publish the flag while that owner remains bound. Already-pending flags, including actual interrupted lock waits, are preserved. The failed participation still marks its owner rollback-only. If code handles that failure inside the owner and intends cancellation, rethrow or restore the flag explicitly; no later restoration is queued for a handled failure.
Once the owning closure finishes, captured transaction handles no longer accept mutations, JDBC work, or new participate(...) calls. Join every participant before returning from that closure; a late rollback-only change cannot cancel a commit already in progress. Additional restrictions apply while another thread owns a savepoint scope.
References:
Rolling Back
Rollbacks are performed by Pyranid in 3 scenarios:
- An exception bubbles out of a transaction closure
- You explicitly mark a transaction as "rollback only"
- You create a savepoint and roll back to it
// Any exception that bubbles out will cause a rollback
database.transaction(() -> {
database.query("UPDATE account SET balance = balance - 10 WHERE id = :id")
.bind("id", 1)
.execute();
throw new IllegalStateException("Something's wrong!");
});
// You may mark a transaction as rollback-only, and it will roll back
// after the closure execution has completed
database.transaction(() -> {
database.query("UPDATE account SET balance = balance - 10 WHERE id = :id")
.bind("id", 1)
.execute();
// Hmm...I changed my mind
Transaction transaction = database.currentTransaction().orElseThrow();
transaction.setRollbackOnly(true);
});
// You may roll back part of a transaction with a savepoint
database.transaction(() -> {
Transaction transaction = database.currentTransaction().orElseThrow();
try {
transaction.withSavepoint(() -> {
database.query("UPDATE account SET balance = balance - 10 WHERE id = :id")
.bind("id", 1)
.execute();
// Hmm...I changed my mind about this part of the transaction
throw new IllegalStateException("Undo the savepoint work");
});
} catch (IllegalStateException ignored) {
// Work inside the savepoint was rolled back, and the outer transaction continues
}
});
// Any exception that bubbles out will cause a rollback
database.transaction(() -> {
database.query("UPDATE account SET balance = balance - 10 WHERE id = :id")
.bind("id", 1)
.execute();
throw new IllegalStateException("Something's wrong!");
});
// You may mark a transaction as rollback-only, and it will roll back
// after the closure execution has completed
database.transaction(() -> {
database.query("UPDATE account SET balance = balance - 10 WHERE id = :id")
.bind("id", 1)
.execute();
// Hmm...I changed my mind
Transaction transaction = database.currentTransaction().orElseThrow();
transaction.setRollbackOnly(true);
});
// You may roll back part of a transaction with a savepoint
database.transaction(() -> {
Transaction transaction = database.currentTransaction().orElseThrow();
try {
transaction.withSavepoint(() -> {
database.query("UPDATE account SET balance = balance - 10 WHERE id = :id")
.bind("id", 1)
.execute();
// Hmm...I changed my mind about this part of the transaction
throw new IllegalStateException("Undo the savepoint work");
});
} catch (IllegalStateException ignored) {
// Work inside the savepoint was rolled back, and the outer transaction continues
}
});
The lower-level Transaction::createSavepoint(), Transaction::rollback(Savepoint), and Transaction::releaseSavepoint(Savepoint) methods remain available for callers that need manual control. Prefer Transaction::withSavepoint(...) for common partial-rollback workflows because it handles rollback, release, and suppressed cleanup failures consistently. DuckDB's JDBC driver does not support savepoints.
Savepoints are stack-like on most drivers. Avoid manual out-of-order rollback or release of nested savepoints unless your driver documents the behavior you need.
If rollback-to-savepoint cleanup fails, or release cleanup reports a terminal failure such as cancelation or connection loss, the surrounding transaction becomes rollback-only even if your code catches the savepoint body's failure. Pyranid retains cleanup failures as suppressed exceptions on the original failure.
Savepoint Ownership
While Transaction::withSavepoint(...) is active, only the thread running its callback may use that transaction's JDBC connection. JDBC work from another participating thread fails immediately with IllegalStateException; it does not wait for the savepoint scope to end. This prevents a savepoint rollback from undoing another participant's successful work. Same-thread nesting is supported, and other participants may resume JDBC work after the scope returns or throws. Manually created savepoints do not provide this ownership guard; callers must coordinate their use across threads.
An exception escaping Database::participate(...) marks the whole transaction rollback-only, including a savepoint ownership conflict. Catching that exception outside participate(...) does not undo the rollback-only mark. If an ownership conflict is expected and the transaction should continue, handle it inside the participating callback and schedule its JDBC work after the savepoint scope ends. All savepoint scopes and participating work must finish before the owning transaction closure returns.
References:
Transaction::setRollbackOnly(Boolean)Transaction::createSavepoint()Transaction::rollback(java.sql.Savepoint)Transaction::releaseSavepoint(java.sql.Savepoint)Transaction::withSavepoint(TransactionalOperation)
Nesting
Each lexically-scoped "nested" transaction is independent of its enclosing transaction. There is no parent-child relationship.
However, if you would like this behavior, you may explicitly use the Database::participate(Transaction, TransactionalOperation) API to have a "child" participate in its parent transaction.
Nested transactions borrow separate physical connections and can pressure small connection pools. Participating worker threads must use a transaction from the same DataSource instance and must complete before the owning transaction closure returns; coordinate this with primitives in your application, such as CompletableFuture::join, ExecutorService::awaitTermination, or a CountDownLatch.
database.transaction(() -> {
database.query("UPDATE account SET balance = balance - 10 WHERE id = :id")
.bind("id", 1)
.execute();
// This transaction will commit
database.transaction(() -> {
database.query("UPDATE account SET balance = balance + 10 WHERE id = :id")
.bind("id", 2)
.execute();
});
// This transaction will not!
throw new IllegalStateException("I should not have used nested transactions here...");
});
database.transaction(() -> {
database.query("UPDATE account SET balance = balance - 10 WHERE id = :id")
.bind("id", 1)
.execute();
// This transaction will commit
database.transaction(() -> {
database.query("UPDATE account SET balance = balance + 10 WHERE id = :id")
.bind("id", 2)
.execute();
});
// This transaction will not!
throw new IllegalStateException("I should not have used nested transactions here...");
});
Join Or Begin, And Savepoint Or Begin
These application helpers use existing APIs; they do not introduce new transaction nesting modes:
static <T> Optional<T> joinOrBegin(
Database database, ReturningTransactionalOperation<T> operation) {
Transaction current = database.currentTransaction().orElse(null);
return current == null
? database.transaction(operation)
: database.participate(current, operation);
}
static <T> Optional<T> savepointOrBegin(
Database database, ReturningTransactionalOperation<T> operation) {
Transaction current = database.currentTransaction().orElse(null);
return current == null
? database.transaction(operation)
: current.withSavepoint(operation);
}
static <T> Optional<T> joinOrBegin(
Database database, ReturningTransactionalOperation<T> operation) {
Transaction current = database.currentTransaction().orElse(null);
return current == null
? database.transaction(operation)
: database.participate(current, operation);
}
static <T> Optional<T> savepointOrBegin(
Database database, ReturningTransactionalOperation<T> operation) {
Transaction current = database.currentTransaction().orElse(null);
return current == null
? database.transaction(operation)
: current.withSavepoint(operation);
}
A failure in joinOrBegin's joined scope marks the owner rollback-only. Catching that failure does not restore commit eligibility: the outer callback can return normally while its outcome is ROLLED_BACK. Use transactionWithOutcome when the caller needs to inspect that result.
With savepointOrBegin, a successfully restored savepoint discards its work while allowing the owner to continue. Driver savepoint support and the usual cancellation/transaction-failure fences still apply. Both helpers use the currently visible transaction for the supplied source; they do not search older scopes hidden by another database's transaction. Avoid assuming these helpers make arbitrary cross-database nesting safe.
Connection Lease Requirements
An independent transaction requires an exclusive physical connection lease while it is active. A single-connection source cannot supply overlapping independent transactions safely. Pyranid rejects a candidate that is the exact JDBC connection object already owned by any enclosing transaction on the thread, before changing or disposing of that handle. A handled rejection leaves the original owner usable.
Distinct proxy objects can hide the same physical connection, and sharing across unrelated threads is not detected by this identity check. The source/pool remains responsible for exclusive physical leases. Use participate or withSavepoint when the intent is to share an existing transaction, and provision enough pool connections for intentional independent nesting.
Isolation
You may specify the normal DBMS isolation levels per-transaction as needed:
// If not specified, DEFAULT is assumed (whatever your DBMS prefers)
database.transaction(TransactionOptions.withIsolation(TransactionIsolation.SERIALIZABLE).build(), () -> {
database.query("UPDATE account SET balance = balance - 10 WHERE id = :id")
.bind("id", 1)
.execute();
database.query("UPDATE account SET balance = balance + 10 WHERE id = :id")
.bind("id", 2)
.execute();
});
// If not specified, DEFAULT is assumed (whatever your DBMS prefers)
database.transaction(TransactionOptions.withIsolation(TransactionIsolation.SERIALIZABLE).build(), () -> {
database.query("UPDATE account SET balance = balance - 10 WHERE id = :id")
.bind("id", 1)
.execute();
database.query("UPDATE account SET balance = balance + 10 WHERE id = :id")
.bind("id", 2)
.execute();
});
References:
TransactionIsolationTransactionOptionsDatabase::transaction(TransactionOptions, TransactionalOperation)Database::transaction(TransactionOptions, ReturningTransactionalOperation)
Read-Only Transactions
database.transaction(TransactionOptions.withReadOnly(true).build(), () -> {
List<Account> accounts = database.query("SELECT * FROM account")
.fetchList(Account.class);
});
database.transaction(
TransactionOptions.withIsolation(TransactionIsolation.REPEATABLE_READ)
.readOnly(true)
.build(),
() -> {
List<Account> accounts = database.query("SELECT * FROM account")
.fetchList(Account.class);
});
database.transaction(TransactionOptions.withReadOnly(true).build(), () -> {
List<Account> accounts = database.query("SELECT * FROM account")
.fetchList(Account.class);
});
database.transaction(
TransactionOptions.withIsolation(TransactionIsolation.REPEATABLE_READ)
.readOnly(true)
.build(),
() -> {
List<Account> accounts = database.query("SELECT * FROM account")
.fetchList(Account.class);
});
TransactionOptions::withReadOnly(true) maps to JDBC Connection::setReadOnly(true) for the physical transaction connection. Pyranid restores the connection's original read-only setting before returning it to the pool.
Read-Only Is a JDBC/DBMS Signal
Read-only behavior is enforced, optimized, routed, or ignored by the JDBC driver and DBMS. SQL Server and Oracle drivers may treat it as advisory or ignore it for normal transactions. SQLite's default JDBC configuration rejects changing the read-only flag after opening a connection, so TransactionOptions.withReadOnly(true) on an ordinary read-write source fails when the first statement begins the physical transaction. Open a separate SQLite source configured as read-only and inherit that setting with default transaction options. DuckDB also rejects per-connection changes; configure its read-only mode when opening the database. Pyranid does not parse SQL to reject writes itself.
Post-Transaction Operations
It is useful to be able to schedule code to run after a transaction has completed. Often, transaction management happens at a higher layer of code than business logic (e.g. a transaction-per-web-request pattern), so it is helpful to have a mechanism to "warp" local logic out to the higher layer.
Without this, you might run into subtle bugs like
- Write to database
- Send out notifications of system state change
- (Sometime later) transaction is rolled back
- Notification consumers are in an inconsistent state because they were notified of a change that was reversed by the rollback
// Business logic
class EmployeeService {
public void giveEveryoneRaises() {
database.query("UPDATE employee SET salary = salary * 2")
.execute();
payrollSystem.startLengthyWarmupProcess();
// Only send emails after the current transaction ends
database.currentTransaction().get().addPostTransactionOperation((transactionResult) -> {
if(transactionResult == TransactionResult.COMMITTED) {
// Successful commit? email everyone with the good news
for(Employee employee : findAllEmployees())
sendCongratulationsEmail(employee);
} else if(transactionResult == TransactionResult.ROLLED_BACK) {
// Rolled back? We can clean up
payrollSystem.cancelLengthyWarmupProcess();
} else if(transactionResult == TransactionResult.IN_DOUBT) {
// The final database outcome is unknown.
// Avoid commit-only side effects and reconcile separately.
payrollSystem.queueReconciliation();
}
});
}
// Rest of implementation elided
}
// Servlet filter which wraps requests in transactions
class DatabaseTransactionFilter implements Filter {
@Override
public void doFilter(ServletRequest servletRequest,
ServletResponse servletResponse,
FilterChain filterChain) throws IOException, ServletException {
database.transaction(() -> {
// Above business logic would happen somewhere down the filter chain
filterChain.doFilter(servletRequest, servletResponse);
// Business logic has completed at this point but post-transaction
// operations will not run until the closure exits
});
// By this point, post-transaction operations will have been run
}
// Rest of implementation elided
}
// Business logic
class EmployeeService {
public void giveEveryoneRaises() {
database.query("UPDATE employee SET salary = salary * 2")
.execute();
payrollSystem.startLengthyWarmupProcess();
// Only send emails after the current transaction ends
database.currentTransaction().get().addPostTransactionOperation((transactionResult) -> {
if(transactionResult == TransactionResult.COMMITTED) {
// Successful commit? email everyone with the good news
for(Employee employee : findAllEmployees())
sendCongratulationsEmail(employee);
} else if(transactionResult == TransactionResult.ROLLED_BACK) {
// Rolled back? We can clean up
payrollSystem.cancelLengthyWarmupProcess();
} else if(transactionResult == TransactionResult.IN_DOUBT) {
// The final database outcome is unknown.
// Avoid commit-only side effects and reconcile separately.
payrollSystem.queueReconciliation();
}
});
}
// Rest of implementation elided
}
// Servlet filter which wraps requests in transactions
class DatabaseTransactionFilter implements Filter {
@Override
public void doFilter(ServletRequest servletRequest,
ServletResponse servletResponse,
FilterChain filterChain) throws IOException, ServletException {
database.transaction(() -> {
// Above business logic would happen somewhere down the filter chain
filterChain.doFilter(servletRequest, servletResponse);
// Business logic has completed at this point but post-transaction
// operations will not run until the closure exits
});
// By this point, post-transaction operations will have been run
}
// Rest of implementation elided
}
Transaction Result
Post-transaction callbacks receive a TransactionResult enum value indicating how the transaction finished:
COMMITTED: the transaction committed successfully.ROLLED_BACK: no application transaction work committed, including failures before any transaction work can run.IN_DOUBT: the final database outcome is unknown. Reconcile authoritative state instead of assuming that a rollback succeeded.
Complete all participating work and savepoint scopes before the owning closure returns. A savepoint ownership conflict is an IllegalStateException, even if the transaction subsequently rolls back; fix the conflicting access rather than retrying it. See Transaction Outcomes for the corresponding metrics.
Pyranid runs every registered post-transaction callback. Callback failures surface as PostTransactionOperationException, either directly or suppressed under an existing transaction or cleanup failure. Check PostTransactionOperationException::getTransactionResult() to distinguish a successful commit followed by callback failure from a failed or in-doubt transaction.
Connection cleanup does not change the database outcome. Pyranid discards connections with an unknown outcome or uncertain connection state instead of returning them to the pool for reuse.
Obtaining a Transaction Outcome
Database::transactionWithOutcome(...) runs one transaction boundary and returns its database result, attempted callback value and final invocation failure together. It does not automatically retry or join an enclosing transaction. The four overloads accept the existing callbacks:
TransactionOutcome<Void> transactionWithOutcome(TransactionalOperation operation);
TransactionOutcome<Void> transactionWithOutcome(TransactionOptions options, TransactionalOperation operation);
<T> TransactionOutcome<T> transactionWithOutcome(ReturningTransactionalOperation<T> operation);
<T> TransactionOutcome<T> transactionWithOutcome(TransactionOptions options, ReturningTransactionalOperation<T> operation);
TransactionOutcome<Void> transactionWithOutcome(TransactionalOperation operation);
TransactionOutcome<Void> transactionWithOutcome(TransactionOptions options, TransactionalOperation operation);
<T> TransactionOutcome<T> transactionWithOutcome(ReturningTransactionalOperation<T> operation);
<T> TransactionOutcome<T> transactionWithOutcome(TransactionOptions options, ReturningTransactionalOperation<T> operation);
The overloads without options use default transaction options. Returning callbacks still return Optional<T>; void callbacks expose no attempted value. The returned TransactionOutcome<T> has four accessors:
| Accessor | Meaning |
|---|---|
getResult() | This boundary's COMMITTED, ROLLED_BACK or IN_DOUBT database result. |
getAttemptedValue() | The callback's normally returned value, even if completion later rolled back or failed. |
getFailure() | The final failure the traditional transaction API would throw, exposed as an Optional containing a RuntimeException. |
getCompletion() | The completion, including process-local boundary identifiers, also delivered to an optional observer. |
Value and failure describe separate facts:
| Execution | Result | Attempted value | Failure |
|---|---|---|---|
| Callback and completion succeed | COMMITTED | As returned | Empty |
| Callback returns a value, but rollback-only completion rolls back | ROLLED_BACK | Preserved | Empty |
| Callback throws and rollback succeeds | ROLLED_BACK | Empty | Retained, with existing checked-exception wrapping |
| Commit acknowledgment is uncertain | IN_DOUBT | Preserved if the callback returned one | Retained |
| Commit succeeds, then cleanup or a post-transaction hook fails | COMMITTED | Preserved | Retained |
An empty, void or accidentally null optional return yields no attempted value. A callback that throws yields none either, even if it constructed a value before throwing. A logical boundary without JDBC work still reports its logical commit or rollback result. getFailure() retains the same exception instance as getCompletion().getFailure(), with its causes and suppressed failures. Values and failures are retained by reference and are not guaranteed immutable or thread-safe.
Here Receipt, operation identity and all helper methods are application code. The callback promises a nonempty receipt on normal return, persists its receipt and outbox together, and can save either a business acceptance or rejection in a committed transaction:
TransactionOutcome<Receipt> outcome = database.transactionWithOutcome(() -> {
Receipt receipt = applyCommandAndPersistReceiptAndOutbox(command);
return Optional.of(receipt);
});
return switch (outcome.getResult()) {
case COMMITTED -> {
outcome.getFailure().ifPresent(this::reportCompletionFailure);
yield responseFromReceipt(outcome.getAttemptedValue().orElseThrow());
}
case ROLLED_BACK -> {
outcome.getFailure()
.filter(failure -> !isExpectedAbort(failure))
.ifPresent(failure -> { throw failure; });
yield handleAbortedAttempt(operationId, outcome.getFailure());
}
case IN_DOUBT -> recoverOrReportUnresolved(operationId);
};
TransactionOutcome<Receipt> outcome = database.transactionWithOutcome(() -> {
Receipt receipt = applyCommandAndPersistReceiptAndOutbox(command);
return Optional.of(receipt);
});
return switch (outcome.getResult()) {
case COMMITTED -> {
outcome.getFailure().ifPresent(this::reportCompletionFailure);
yield responseFromReceipt(outcome.getAttemptedValue().orElseThrow());
}
case ROLLED_BACK -> {
outcome.getFailure()
.filter(failure -> !isExpectedAbort(failure))
.ifPresent(failure -> { throw failure; });
yield handleAbortedAttempt(operationId, outcome.getFailure());
}
case IN_DOUBT -> recoverOrReportUnresolved(operationId);
};
Ordinary failures include programming errors such as NullPointerException; rethrow failures the application does not recognize. The API does not promise to return instead of throwing in every case. Argument validation before a boundary exists still throws, operational acquisition/begin failures within a boundary produce an outcome, and a final Error escapes after normal best-effort completion and observation. Existing post-transaction hook wrapping remains unchanged, including when the hook's cause is an Error.
Use this API at the actual owning command boundary. Wrapping it in transactionWithRetry(...) opens an independent transaction, and returning a failed inner outcome does not tell the outer retry executor that its attempt failed. Handled inner committed-plus-failure and in-doubt outcomes preserve existing retry fences. A normally successful independent inner commit does not currently fence a later outer serialization retry, which can run that inner work again. ROLLED_BACK alone is therefore not permission to replay arbitrary work.
An uncertain result requires application recovery using the original durable operation identity and a fresh usable connection. A missing or unavailable lookup is not proof that the command failed. The library supplies no durable business receipt, operation ledger or recovery UI, and an attempted value alone does not replace them.
Handled Statement Failures and Pre-Commit Validation
On PostgreSQL and DuckDB, handling a statement failure inside a callback can leave the database transaction aborted. Starting in 4.9, Pyranid checks for this before issuing physical commit. It refuses commit and uses the normal rollback path when it detects an abort or a required validation cannot establish transaction usability. Successful rollback reports ROLLED_BACK; rollback failure after work could execute remains IN_DOUBT.
Traditional transaction(...) now throws in those cases instead of returning a value for work the database discarded. transactionWithOutcome(...) returns the attempted value and final failure. There is no opt-out. Merely recording a handled exception does not force rollback: a usable transaction, driver recovery and supported savepoint recovery still permit commit.
DuckDB's transaction invalidation setting affects which handled failures leave the transaction usable. Under the driver's default policy, a handled preparation failure such as a missing-table error invalidates the transaction and pre-commit validation refuses commit. With SET default_transaction_invalidation_policy = 'SYNTACTIC_ERRORS_DO_NOT_INVALIDATE', a handled syntactic/preparation failure can leave it usable, so earlier writes can commit. Pyranid respects that driver state/policy and does not force every handled error to roll back or change the setting itself. Qualify the policy selected for your connection; constraint failures that invalidate a transaction are still refused.
PostgreSQL first reads the driver's transaction state without an extra database round trip. Readable usable state permits commit even after a recovered failure, including autosave=always. autosave=conservative does not recover arbitrary constraint failures. If driver state cannot be read, a recorded failure or participating raw/custom JDBC access triggers one internal SELECT 1. DuckDB uses that conditional query directly. Several accesses coalesce into one query; built-in-only healthy operations require none. A required query can fail for transport or resource reasons, so its refusal reports inability to establish usability rather than asserting that an earlier statement necessarily aborted the transaction.
Pyranid records the first failure while an operation holds the transaction connection, including preparation, binding, execution, streaming fetch/mapping and savepoint failures. Successful rollback to a Pyranid savepoint clears that failure record. Participating raw access and application binders, mappers, column/parameter hooks and statement customizers separately require validation even when they handle a JDBC failure internally and return normally. That access trigger survives savepoint recovery. Callbacks that receive no JDBC objects, such as completion observers, do not set it.
A refusal can inherit SQLState, vendor metadata and classifier flags from the first recorded failure, which the application may already have handled. That failure may differ from the error that eventually aborted the transaction. Query/cleanup evidence is retained on the new refusal without modifying the handled exception. A driver-state-only or access-trigger-only refusal may have no recorded cause or inherited classification. There is no public refused-commit marker; inspect the final failure message and retained evidence. transactionWithRetry(...) can therefore rerun a callback that handled a retryable failure when completion is refused, rollback succeeds and its retry policy accepts the inherited classification. Keep the entire callback safe to replay; a normal callback return no longer implies that no retry will occur.
On PostgreSQL, wrappers that hide the driver's transaction state reduce coverage of errors handled by built-in JDBC compatibility fallbacks. A fallback can handle a driver error without triggering conditional validation, allowing an aborted transaction to go undetected when there is no other trigger. Readable driver transaction state lets the pre-commit check detect those aborts. Parameter metadata handling has additional protections, but does not guarantee detection of every handled driver error. Qualify the selected driver and pool combination and its abort-detection behavior before relying on it.
This detection strategy covers PostgreSQL and DuckDB. Other dialects retain existing behavior, including whole-transaction aborts that may be followed by new work on a usable connection: for example, a swallowed InnoDB deadlock can discard earlier work while allowing later work to commit. Do not assume those transactions remain one continuous unit after handling such errors. Manual transaction control through unguarded raw handles remains outside Pyranid's managed contract. Driver internals and unqualified built-in compatibility paths remain detection limits rather than unconditional abort guarantees.
Interruption in Returned Outcomes
If no enclosing Pyranid transaction remains bound, an interrupted returned failure restores the thread's interrupt flag before return. Inside an enclosing transaction, returning that failure does not newly publish the flag; interruption remains reachable through getFailure(). This lets code handle an inner outcome and continue enclosing savepoint work. An already-pending flag is preserved. The application decides whether to rethrow the failure and unwind. Handling it can consume cancellation; the library does not defer restoration until the outermost boundary. Ordinary traditional failures use the same ambient-transaction gate after cleanup and hooks. Final propagating boundary Errors restore their reachable interruption evidence even with an enclosing transaction.
Observing Completion
An optional completion observer records the final result of a transaction boundary after connection cleanup and every post-transaction callback:
TransactionOptions options = TransactionOptions
.withIsolation(TransactionIsolation.DEFAULT)
.completionObserver(completion -> {
audit.recordTransaction(
completion.getTransactionId(),
completion.getEnclosingTransactionId(),
completion.getResult(),
completion.getFailure());
})
.build();
database.transaction(options, () -> {
database.query("UPDATE orders SET status = 'PAID' WHERE order_id = :id")
.bind("id", orderId)
.execute();
});
TransactionOptions options = TransactionOptions
.withIsolation(TransactionIsolation.DEFAULT)
.completionObserver(completion -> {
audit.recordTransaction(
completion.getTransactionId(),
completion.getEnclosingTransactionId(),
completion.getResult(),
completion.getFailure());
})
.build();
database.transaction(options, () -> {
database.query("UPDATE orders SET status = 'PAID' WHERE order_id = :id")
.bind("id", orderId)
.execute();
});
TransactionCompletion separates the database outcome from the transaction method's failure. A transaction can report COMMITTED together with a connection-cleanup or post-transaction callback failure. A normal rollback-only return reports ROLLED_BACK with an empty failure. A scope that performs no JDBC work retains its logical commit or rollback result.
The optional failure describes the final invocation failure, including suppressed cleanup and callback failures. The traditional transaction API throws it; the outcome API retains ordinary failures. Observers retain an optional Throwable because they also see final Errors that escape.
Each independently nested transaction receives its own completion and result. An inner commit remains committed even if the enclosing transaction later rolls back. The getEnclosingTransactionId() method correlates those boundaries without implying shared atomicity; identifiers are process-local, not durable business identifiers.
Observers run synchronously before the transaction method returns or throws. With transactionWithOutcome(...), the observer receives the same completion instance exposed by getCompletion(). Keep observers fast and thread-safe when options are shared. Their exceptions are contained, do not alter transaction outcomes, and cannot trigger a retry. Continue using addPostTransactionOperation(...) for application work whose failure must propagate. Completion observation is diagnostic; it is not a durable audit-delivery mechanism.
There is one observation per transaction attempt, including failed attempts in transactionWithRetry(...). A participate(...) scope shares its owner's completion rather than generating another boundary.
Retrying Serialization Failures
Use Database::transactionWithRetry(RetryPolicy, TransactionalOperation) when concurrent database transactions may safely be re-run after the database rolls one of them back, such as serialization conflicts or deadlocks.
Retry behavior is explicit: you choose total attempts, the retry condition, and the backoff strategy.
RetryPolicy retryPolicy = RetryPolicy.ofMaxAttempts(
3,
RetryPolicy.Backoff.fixed(Duration.ofMillis(25)),
RetryPolicy.Condition.serializationFailureOrDeadlock());
TransactionRetryResult<Void> retryResult = database.transactionWithRetry(retryPolicy, () -> {
database.query("""
UPDATE account
SET balance = balance - :amount
WHERE account_id = :accountId
""")
.bind("accountId", accountId)
.bind("amount", amount)
.execute();
});
RetryPolicy retryPolicy = RetryPolicy.ofMaxAttempts(
3,
RetryPolicy.Backoff.fixed(Duration.ofMillis(25)),
RetryPolicy.Condition.serializationFailureOrDeadlock());
TransactionRetryResult<Void> retryResult = database.transactionWithRetry(retryPolicy, () -> {
database.query("""
UPDATE account
SET balance = balance - :amount
WHERE account_id = :accountId
""")
.bind("accountId", accountId)
.bind("amount", amount)
.execute();
});
RetryPolicy::ofMaxAttempts(Integer, RetryPolicy.Backoff, RetryPolicy.Condition) means three total attempts in this example: the initial transaction plus up to two retries. Pyranid starts a fresh physical transaction for each attempt. The whole closure may run more than once, so keep non-idempotent external side effects outside the retried closure.
Database::transactionWithRetry(...) owns the transaction it retries. It rejects a call when the innermost ambient transaction on the calling thread uses the same DataSource instance, including through another Database wrapper. It checks only that innermost transaction. If databases A and B use different sources, an A retry invoked inside independently nested A and B transactions starts a new independent A transaction; its retries do not restart either surrounding transaction. Pyranid evaluates the retry policy only when it knows that no application transaction work committed. Serialization failures and deadlocks in the transaction body are eligible after a successful rollback; a commit-phase serialization failure is eligible only with a direct readable 40001, the dialect's serialization classification, no contradictory or unreadable cause/next/suppressed evidence, and successful follow-up rollback. A transport exception, causal I/O failure, missing or other subordinate SQLState prevents that proof. Vendor-only commit diagnostics, including Oracle 8177 and SQL Server 3960, remain uncertain at commit; statement/body diagnostics are unchanged. With the currently tested DuckDB JDBC driver, commit-time conflicts report no SQLState: all such conflicts are IN_DOUBT and are never automatically retried, even if the follow-up rollback succeeds. A failure while beginning the transaction, before any application transaction work can run, is also eligible even if cleanup rollback fails. Other commit failures, uncertain outcomes after application work, and failures after a successful commit—including cleanup and post-transaction callback failures—are never replayed.
Unlike Database::transaction(ReturningTransactionalOperation<T>), Database::transactionWithRetry(RetryPolicy, TransactionalOperation) returns a TransactionRetryResult so callers can inspect failures recovered before success. TransactionRetryResult::getValue() contains the successful transaction value, and TransactionRetryResult::getFailures() contains failed attempts that Pyranid retried before the transaction eventually succeeded.
// Risky: the email may send more than once
database.transactionWithRetry(retryPolicy, () -> {
database.query("UPDATE orders SET status = 'PAID' WHERE order_id = :orderId")
.bind("orderId", orderId)
.execute();
emailClient.sendReceipt(orderId);
});
// Risky: the email may send more than once
database.transactionWithRetry(retryPolicy, () -> {
database.query("UPDATE orders SET status = 'PAID' WHERE order_id = :orderId")
.bind("orderId", orderId)
.execute();
emailClient.sendReceipt(orderId);
});
Instead, return enough information to run the side effect after the retry helper succeeds:
TransactionRetryResult<ReceiptEmail> retryResult = database.transactionWithRetry(retryPolicy, () -> {
database.query("UPDATE orders SET status = 'PAID' WHERE order_id = :orderId")
.bind("orderId", orderId)
.execute();
return Optional.of(new ReceiptEmail(orderId));
});
retryResult.getValue().ifPresent(emailClient::sendReceipt);
for (DatabaseException failure : retryResult.getFailures()) {
logger.info("Recovered transaction failure", failure);
}
TransactionRetryResult<ReceiptEmail> retryResult = database.transactionWithRetry(retryPolicy, () -> {
database.query("UPDATE orders SET status = 'PAID' WHERE order_id = :orderId")
.bind("orderId", orderId)
.execute();
return Optional.of(new ReceiptEmail(orderId));
});
retryResult.getValue().ifPresent(emailClient::sendReceipt);
for (DatabaseException failure : retryResult.getFailures()) {
logger.info("Recovered transaction failure", failure);
}
For durable side effects, prefer the outbox pattern: write an outbox row inside the retried transaction and let a separate worker deliver it after commit.
RetryPolicy.Backoff::fixed(Duration) and RetryPolicy.Backoff::exponential(Duration, Duration) backoff strategies are built in:
RetryPolicy exponentialRetryPolicy = RetryPolicy.ofMaxAttempts(
5,
RetryPolicy.Backoff.exponential(
Duration.ofMillis(25),
Duration.ofSeconds(1)),
RetryPolicy.Condition.serializationFailureOrDeadlock());
RetryPolicy exponentialRetryPolicy = RetryPolicy.ofMaxAttempts(
5,
RetryPolicy.Backoff.exponential(
Duration.ofMillis(25),
Duration.ofSeconds(1)),
RetryPolicy.Condition.serializationFailureOrDeadlock());
Jitter and an Elapsed Retry Budget
Wrap an existing backoff in RetryPolicy.Backoff.fullJitter(...) to spread simultaneous retries across clients. Add withMaxElapsedTime(...) to limit how long Pyranid may continue admitting retries:
RetryPolicy boundedPolicy = RetryPolicy.ofMaxAttempts(
5,
RetryPolicy.Backoff.fullJitter(
RetryPolicy.Backoff.exponential(
Duration.ofMillis(25), Duration.ofMillis(500))),
RetryPolicy.Condition.serializationFailureOrDeadlock())
.withMaxElapsedTime(Duration.ofSeconds(2));
database.transactionWithRetry(boundedPolicy, options, () -> {
database.query("UPDATE inventory SET quantity = quantity - 1 WHERE sku = :sku")
.bind("sku", sku)
.execute();
});
RetryPolicy boundedPolicy = RetryPolicy.ofMaxAttempts(
5,
RetryPolicy.Backoff.fullJitter(
RetryPolicy.Backoff.exponential(
Duration.ofMillis(25), Duration.ofMillis(500))),
RetryPolicy.Condition.serializationFailureOrDeadlock())
.withMaxElapsedTime(Duration.ofSeconds(2));
database.transactionWithRetry(boundedPolicy, options, () -> {
database.query("UPDATE inventory SET quantity = quantity - 1 WHERE sku = :sku")
.bind("sku", sku)
.execute();
});
Full jitter chooses a random delay below the configured cap. A zero cap remains zero. Fixed and exponential backoffs remain deterministic unless wrapped in fullJitter(...).
An elapsed limit must be strictly positive. It starts with the first attempt and includes transaction work, cleanup, synchronous completion observers, policy evaluation, and waiting. The budget does not prevent the initial attempt. If the selected delay would consume the remaining budget, Pyranid stops instead of shortening it.
Interruption stops further attempts, including when backoff is zero. The transaction failure remains available to the caller, and the thread's interrupt flag is preserved.
Budget exhaustion throws the final original DatabaseException, with earlier failures retained as suppressed exceptions. A successful in-flight attempt may finish after the limit: this budget controls retry admission, not statement cancelation or transaction timeouts. Outcome safety checks still take precedence; a committed or uncertain transaction is never replayed merely because time remains.
Independently committed nested transactions are side effects of the retried closure: an enclosing rollback does not undo them. Avoid them inside retried work unless they are safe to repeat.
A savepoint ownership conflict is a programming error and is not eligible for automatic retry. See Savepoint Ownership for coordinating participating threads.
Policies have no elapsed limit by default. The getMaxElapsedTime() method returns the optional limit; withoutMaxElapsedTime() returns a copy without one. These copy methods leave the original policy unchanged.
Timeouts can be classified with DatabaseException::isTimeout() and opted into with RetryPolicy.Condition::timeout(), but Pyranid does not treat them as automatically safe to retry. A timeout may surface after the database has already performed part or all of the work.
Post-transaction operations registered with Transaction::addPostTransactionOperation(Consumer<TransactionResult>) run once per attempt. Failed attempts report ROLLED_BACK when no application transaction work committed, or IN_DOUBT when the outcome is unknown. An in-doubt attempt stops retries. A normally returning rollback-only attempt reports ROLLED_BACK; a successfully completed attempt reports COMMITTED, including a scope that performed no JDBC work.

