Skip to content
atom®technologiesBook a call
Engineering notes

Rust async cancellation at a database transaction boundary

Separate the lifetime of a Tokio task from the outcome of its PostgreSQL transaction. Give one resource owner responsibility for the commit decision, bounded cleanup, and unresolved outcomes.

A software team at a whiteboard

Name the lifetime that is ending

A caller times out while a Rust worker is updating a database. The service must decide who still owns the transaction after that caller stops waiting. This discussion uses Tokio 1.48.0, tokio-postgres 0.7.15, and PostgreSQL 18: one ordinary async worker, an already-started top-level transaction, transactional table updates, and an exclusively owned connection. Connection pools, blocking tasks, and effects outside the transaction need their own lifecycle contracts.

Dropping a Tokio JoinHandle detaches the spawned task; it continues running. Calling abort requests cancellation. Tokio documents that this takes effect when the task yields, or shuts down an already-idle task without resuming it. Local values are then destroyed. Awaiting the handle observes task completion, including cancellation when cancellation wins. The task can also finish normally before the abort takes effect. Name these outcomes separately in the service contract.

Observe database cleanup separately

The tokio-postgres Transaction documentation says a transaction rolls back when dropped, and its explicit asynchronous rollback method reports errors to the caller. That cleanup behavior does not make a cancelled Tokio task an acknowledgement from PostgreSQL. An awaited task cancellation establishes that the task has stopped and its local destructors have run. When the service needs observed rollback, arrange for the resource owner to await rollback and inspect the database result.

The driver has another relevant lifetime. Its Connection future performs the actual server I/O and is generally run in a background task. The documentation says it finishes after a fatal connection error, or after the associated Client is dropped and outstanding work completes. Cancelling the request worker and ending connection I/O are separate actions. Keep the connection driver available while its owner is trying to receive a terminal database result.

Serialize the cancellation and commit decisions

Give one owner the transaction and the authority to choose its terminal action. In a cooperative design, a caller sends a cancellation request to that owner. If the owner accepts it before beginning commit, it stops admitting further transaction work and takes the rollback path. Only successful work may reach the commit choice; a statement error sends this example to cleanup. If a statement is still running, the owner must account for that statement and the connection before it can report cleanup complete. A caller disappearing must not discard that responsibility.

At the commit boundary, record that a commit attempt may have reached PostgreSQL as soon as the owner begins the attempt. This is a conservative application state, not a claim about the exact instant bytes leave the driver. Cancellation arriving during that interval cannot establish that the transaction rolled back. PostgreSQL COMMIT completes the current transaction; ROLLBACK discards the current transaction and has no effect outside a transaction block. A later rollback cannot undo an earlier completed commit.

The transaction owner follows the outcomeRequest cancellation changes what the owner should do next. Terminal database evidence determines what the service may report.
  1. Caller exits
    Retain resource ownership

    The caller stops waiting; one owner still holds the transaction and connection responsibilities.

  2. Before commit
    Choose cleanup once

    An accepted cancellation prevents a new commit attempt and directs the owner toward observed rollback.

  3. Commit attempted
    Await the terminal result

    Once commit may have been sent, cancellation alone cannot establish the database outcome.

  4. Budget exhausted
    Handoff unresolved work

    Retire the uncertain connection and retain an explicit owner for outcome reconciliation.

A query cancellation request is another operation

tokio-postgres exposes CancelToken for requesting cancellation of the query in progress on a connection. Its documentation explicitly calls cancellation racy: the query may finish normally before cancellation arrives. Successful delivery of the cancellation attempt provides no acknowledgement that the query was cancelled. Keep that result distinct from both Tokio task cancellation and the transaction result.

PostgreSQL 18 likewise requires the client to wait for the original command response to learn its outcome. Keep query-cancellation authority with the owner of the connection and its current work. A connection-scoped token should not become an untracked permission retained by an expired caller. The dedicated connection in this example is retired after cleanup; a pooled implementation needs a separately established rule for safe return and reuse.

Bound cleanup without losing the unresolved case

Use a cleanup budget owned by the service after the caller deadline. As an arithmetic example, the caller stops waiting at 200 milliseconds after admission and cleanup gets 1,000 additional milliseconds. The shared cleanup deadline is therefore 1,200 milliseconds after admission. If 700 milliseconds of that cleanup budget are spent resolving the active statement, only 300 remain. Giving every cleanup phase a fresh second would violate that bound. These numbers illustrate accounting, not measured timings or recommended production settings.

If the owner observes successful rollback before any commit attempt, it can report rolled back. If it observes commit completion, it must preserve that outcome despite caller cancellation. On a lost connection or expired cleanup budget without terminal evidence, retain an unresolved outcome and retire the connection. Retiring the connection prevents reuse; it does not establish when server work stopped. Assign reconciliation to a named owner with the operation identity and known transaction stage; a task-cancelled flag is insufficient evidence for replaying the business operation.

The handoff also needs a lifetime beyond the exiting task. Decide how the service records or transfers unresolved ownership before shutdown removes the task and connection driver. If that handoff cannot complete, surface the failure through the service operating procedure. A bounded cleanup attempt is useful only when exhausting its budget has an explicit disposition.

Review the observable states

A cancellation review should ask for separate evidence at handle drop, worker abort, query cancellation, and commit-result interruption. For each controlled case, record the task outcome, database outcome, connection disposition, and remaining owner. The discussion here is based on published runtime and database contracts; it is not a report of executed Rust or database tests. An implementation should demonstrate those boundaries in its own controlled environment, including the case where the caller times out and the transaction still commits.