Use savepoint rollback to recover transaction usability while preserving the distinction between release and durable commit.
A local rollback is not a completed transaction
A worker processes a synthetic input batch inside one database transaction. It inserts a valid record, attempts a malformed record and then wants to continue with a third record. Catching the exception in application code does not necessarily make the database transaction usable again. In PostgreSQL, an error can leave the transaction in an aborted state until the appropriate rollback. A savepoint gives the application a deliberate recovery boundary inside the larger transaction.
The important distinction is between recovering part of the work and committing any of it. Rolling back to a savepoint discards later changes while retaining earlier transactional work. Releasing a savepoint removes the marker while keeping its changes inside the enclosing transaction. Neither operation makes those changes durable independently of the outer commit. A subsequent full rollback can still discard everything in that transaction.
This guide uses a temporary table with synthetic integer identifiers and labels. It is an evergreen explanation of transaction structure. The SQL is a PostgreSQL example; a separate offline state model can test the intended control flow, but it is not evidence that a PostgreSQL server executed the commands. Record a real server integration run separately when the required environment is available.
Put the savepoint around an optional unit
Choose a savepoint boundary based on the unit the application can legitimately discard. If the second record is optional and independent of the first, a per-record savepoint can make sense. If all records together represent one invariant, skipping the bad record may create an invalid aggregate. Savepoints provide a mechanism for partial rollback, not permission to reinterpret a failed batch as a successful one.
Keep the transaction owner explicit. A lower-level helper can create and roll back a savepoint, but it should not commit the caller's outer transaction merely because its own work succeeded. Conversely, the caller must not assume that a helper's RELEASE SAVEPOINT means the helper's result is durable. Name result states carefully: a step can be accepted within the transaction while the overall batch is still uncommitted.
PostgreSQL documents that a rollback to a named savepoint destroys savepoints established after that point while leaving the named savepoint available. This permits another attempt within that recovery boundary. Avoid reusing the same name in deeply nested helpers unless their interaction is deliberate; shadowed savepoint names make it difficult to understand which marker a rollback reaches.
Walk through a recoverable duplicate
The following original SQL creates a session-local fixture. The attempted duplicate identifier is intentional. In an interactive psql session, the error is followed by a rollback to the savepoint so the transaction can continue. A script runner configured to stop at the first SQL error will need an explicit test harness that expects that failure and issues the recovery command on the same connection.
-- Author: Sandeep Belgavi. Synthetic PostgreSQL savepoint fixture.
CREATE TEMP TABLE fixture_record (
id integer PRIMARY KEY,
label text NOT NULL
);
BEGIN;
INSERT INTO fixture_record VALUES (11, 'accepted-a');
SAVEPOINT optional_record;
INSERT INTO fixture_record VALUES (11, 'duplicate-a'); -- expected error
ROLLBACK TO SAVEPOINT optional_record;
INSERT INTO fixture_record VALUES (12, 'accepted-b');
RELEASE SAVEPOINT optional_record;
SELECT id, label FROM fixture_record ORDER BY id;
ROLLBACK;
SELECT count(*) AS durable_rows FROM fixture_record;Before the outer rollback, the transaction's query should show identifiers 11 and 12 with their accepted labels. After the rollback, the temporary table should contain zero rows because both accepted inserts belonged to the same uncommitted transaction. The table itself remains because it was created before BEGIN. That placement makes the final count observable without confusing table creation rollback with row rollback.
Now repeat the fixture with an outer COMMIT instead. The rows remain visible on that session after commit. This pair of runs is more informative than checking only that the duplicate was skipped: it demonstrates who owns durability. Do not run the example against an existing application table or change its identifiers to real records. The temporary fixture supplies everything needed to observe the mechanism.
Keep application and connection state aligned
The application exception handler must know whether the database command failed inside a savepoint, whether recovery succeeded and whether the connection is still usable. A rollback command can itself fail if the connection has been lost. In that case the application must not report that it safely recovered the step. The result is an infrastructure failure requiring the transaction owner to abandon or reconcile the attempt.
Use the same database connection for the savepoint and its rollback. Returning a connection to a pool while it still owns an open or failed transaction can leak state into the next borrower. Pool reset behavior is a useful defense, but it should not replace explicit transaction ownership. A helper that silently obtains another connection for recovery cannot roll back the original connection's transaction.
External effects sit outside this mechanism. If a worker sends a message or writes a remote object between the savepoint and the failed SQL command, rolling back the database does not undo those effects. Keep such effects behind a separately designed protocol, such as a durable handoff after commit. The article does not claim that savepoints implement a distributed transaction or a general compensation system.
Decide which errors are recoverable
Do not catch every database exception and continue. A malformed synthetic record may be a recoverable input outcome. A missing relation, unexpected permission failure or broken invariant may indicate that the entire operation is invalid. Define a narrow set of expected failures and preserve their diagnostic information. Unexpected failures should normally reach the outer transaction owner rather than being converted into a skipped record.
Serialization failures require particular care. Retrying a small statement with stale application decisions may not be the correct recovery for a transaction that must be retried as a whole. The isolation contract and driver behavior determine the appropriate scope. Keep the savepoint example focused on local statement failure, and test the actual database's retry requirements separately before extending it to broader concurrency handling.
Even expected errors have costs. A savepoint around every tiny operation adds bookkeeping, and repeatedly provoking constraint violations can obscure a poorly validated input pipeline. Validate what can be checked cheaply before issuing SQL, while retaining database constraints as the authoritative boundary. Measure the actual workload if savepoint overhead matters; the synthetic example supplies no throughput or latency estimate.
Model recovery without pretending to run a server
An offline teaching model can maintain a working row set, a committed row set and a stack of snapshots. A savepoint copies the working state into a marker. Rollback restores that marker and removes later markers. Release removes the marker while retaining working changes. Commit transfers working state to the durable state. Full rollback restores the pre-transaction state.
That model can include an aborted flag to demonstrate why continuing immediately after an error is wrong for the PostgreSQL flow. Its expected outcomes are educational invariants, not an implementation of PostgreSQL locking, WAL, cursor behavior or transaction snapshots. Label the model clearly and keep the SQL integration fixture alongside it so readers can compare the abstraction with a real database when available.
Meaningful tests assert that release does not commit, that rollback to a marker preserves earlier work, and that a full rollback removes changes made both before and after the marker. Include a missing-marker error and nested markers whose later entries disappear after rollback. Check the final row sets independently of status strings so a misleading success message cannot hide an incorrect state transition.
Integrate the boundary into a worker contract
An agent-driven worker should receive a structured outcome such as accepted-in-transaction, rejected-input or transaction-failed. It should not infer durability from a natural-language message saying a step finished. The transaction owner decides when commit has succeeded and produces a separate durable receipt. This keeps planning language from obscuring the state the database actually guarantees.
For a fixed batch transformation, ordinary deterministic code is sufficient. An agent may help explain an invalid fixture or choose among supported transformations, but it should not improvise transaction recovery commands. The dependable design is a small, documented state machine: establish the boundary, run the optional unit, recover an expected failure, and let the outer owner decide the final commit or rollback.
Run the example yourself
The synthetic fixtures, expected output and tests behind this guide are in the companion code on GitHub; its README lists the prerequisites, exact commands, expected output and limits.