This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
backendcritical PriorityID: tokio-async-cancellation-transaction-raii-guard

Tokio Async-Cancellation Scope-Safe Transaction RAII Guard

Enforces synchronous Drop RAII guards with background rollback dispatching for database transactions across Tokio yield points. Prevents connection pool starvation, orphaned row-level locks, and phantom writes caused by dropped futures in cancellation scenarios like timeouts and select branches. Guarantees deterministic abort execution even when async executors drop executing futures without running async cleanup blocks.

Prohibited Anti-Pattern: Dropping uncommitted async database transactions across Tokio cancellation boundaries without an RAII-dispatched background rollback

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Tokio Async-Cancellation Scope-Safe Transaction RAII Guard - Enforces synchronous Drop RAII guards with background rollback dispatching for database transactions across Tokio yield points. Prevents connection pool starvation, orphaned row-level locks, and phantom writes caused by dropped futures in cancellation scenarios like timeouts and select branches. Guarantees deterministic abort execution even when async executors drop executing futures without running async cleanup blocks.
globs: src/**/*.rs
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/tokio-async-cancellation-transaction-raii-guard"
---

# Tokio Async-Cancellation Scope-Safe Transaction RAII Guard

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Dropping uncommitted async database transactions across Tokio cancellation boundaries without an RAII-dispatched background rollback

## System Constraints
You are a Principal Rust Architect enforcing deterministic transaction life-cycles under Tokio async cancellation. You must mandate scope-safe RAII rollback guards around database operations to prevent orphaned locks when futures are cancelled.

## Strict Guidelines
- Engineers MUST ALWAYS wrap raw async transactions in an RAII guard that dispatches background rollback or connection eviction upon synchronous drop unless explicitly committed.
- Engineers MUST NOT rely on manual async `.rollback().await` calls at the end of functions, as Tokio cancellation points (`tokio::select!`, `tokio::time::timeout`) bypass subsequent async instructions.
- Code SHOULD leverage explicit ownership transitions (e.g., `guard.commit().await?`) that disarm the RAII rollback trigger only upon verified database acknowledgement.
- Services MUST ensure that if an RAII guard drops without being committed, it dispatches non-blocking rollback tasks via `tokio::spawn` or discards/resets the physical connection from the pool.
- Components NEVER hold uncommitted database locks across untimed external RPC calls or unshielded cancellation yields.

## Bad vs Good Implementations
### Manual Rollback Vulnerable to Future Cancellation vs RAII Rollback Guard

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: When tokio::time::timeout fires, the inner future is abruptly dropped at the sleep yield point. The async rollback is never awaited, leaving row locks open and the connection in an unhandled state.
```rust
use tokio::time::{timeout, Duration};
use sqlx::{PgPool, Postgres, Transaction};

pub async fn process_order(pool: &PgPool, order_id: i64) -> Result<(), Box<dyn std::error::Error>> {
    // ANTI-PATTERN: If timeout triggers during downstream .await, this future is dropped immediately.
    // The transaction is never committed or explicitly rolled back, leaving connection locks held
    // until the pool health-checker or TCP keepalive tears down the connection.
    let mut tx: Transaction<'_, Postgres> = pool.begin().await?;

    timeout(Duration::from_millis(500), async {
        sqlx::query!("UPDATE inventory SET stock = stock - 1 WHERE id = $1 FOR UPDATE", order_id)
            .execute(&mut *tx)
            .await?;

        // Downstream RPC or long yield point vulnerable to cancellation
        tokio::time::sleep(Duration::from_millis(600)).await;

        tx.commit().await?;
        Ok::<(), Box<dyn std::error::Error>>(())
    }).await??;

    Ok(())
}
```

#### Production Standard (Correct)
> **Standard**: The TxGuard owns the transaction and implements Drop. If tokio::time::timeout cancels the scope midway, TxGuard::drop synchronously extracts the uncommitted transaction and spawns a background rollback task on the runtime, deterministically freeing row locks.
```rust
use tokio::time::{timeout, Duration};
use sqlx::{PgPool, Postgres, Transaction};

/// Scope-safe RAII transaction wrapper that guarantees rollback on drop.
pub struct TxGuard {
    tx: Option<Transaction<'static, Postgres>>,
}

impl TxGuard {
    pub fn new(tx: Transaction<'static, Postgres>) -> Self {
        Self { tx: Some(tx) }
    }

    pub async fn commit(mut self) -> Result<(), sqlx::Error> {
        if let Some(tx) = self.tx.take() {
            tx.commit().await?;
        }
        Ok(())
    }
}

impl Drop for TxGuard {
    fn drop(&mut self) {
        if let Some(tx) = self.tx.take() {
            // Safe asynchronous rollback dispatch within synchronous Drop
            tokio::spawn(async move {
                let _ = tx.rollback().await;
            });
        }
    }
}

pub async fn process_order(pool: &'static PgPool, order_id: i64) -> Result<(), Box<dyn std::error::Error>> {
    let tx = pool.begin().await?;
    let mut guard = TxGuard::new(tx);

    timeout(Duration::from_millis(500), async {
        if let Some(ref mut tx) = guard.tx {
            sqlx::query!("UPDATE inventory SET stock = stock - 1 WHERE id = $1 FOR UPDATE", order_id)
                .execute(&mut **tx)
                .await?;
        }

        tokio::time::sleep(Duration::from_millis(600)).await;
        Ok::<(), Box<dyn std::error::Error>>(())
    }).await??;

    // Explicitly commit, disarming the drop-guard
    guard.commit().await?;
    Ok(())
}
```

Recommended MCP Servers (mcp-serverlist.com)

Equip agent with system tools to verify code for this stack.

Recommended Agent Skills (askills.dev)

Ready-to-use executable skill functions tailored to this stack.

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Tokio Async-Cancellation Scope-Safe Transaction RAII Guard

Tokio Async-Cancellation Scope-Safe Transaction RAII Guard defines an industrial-grade behavioral standard for backend engineering. Enforces synchronous Drop RAII guards with background rollback dispatching for database transactions across Tokio yield points. Prevents connection pool starvation, orphaned row-level locks, and phantom writes caused by dropped futures in cancellation scenarios like timeouts and select branches. Guarantees deterministic abort execution even when async executors drop executing futures without running async cleanup blocks. Modern software architectures require strict adherence to deterministic patterns to guarantee high availability, maintainability, and zero security vulnerabilities.

Framework Paradigm Shift & Drift MechanicsLLMs are trained on millions of open-source repositories containing outdated code, legacy idioms, and unpatched antipatterns. When coding assistants generate implementations for this stack, they default to common statistical tokens: Dropping uncommitted async database transactions across Tokio cancellation boundaries without an RAII-dispatched background rollback Without an explicit system instruction file, developers spend hours debugging silent failures.
Failure Modes & Production Blast Radius

Hazard Analysis: What Breaks Without This Rule

The following failure modes have been cataloged from hundreds of hours of production code reviews where AI assistants produced non-compliant implementations:

Failure ModeAI Symptom (The Anti-Pattern)SeverityProduction Impact & Remedy
AI Hallucination & Deprecation DriftDropping uncommitted async database transactions across Tokio cancellation boundaries without an RAII-dispatched background rollbackCritical
Violating this industrial standard introduces regression bugs, security risks, and unexpected runtime failures in production.
Enforce explicit behavioral system directives across all AI coding assistants in your repository.
Silent Architecture InconsistencyAI assistants produce mixed paradigms across files, creating fragmented codebase conventions.Medium
Increases cognitive load during code reviews and leads to maintenance debt across engineering teams.
Pin project conventions in .cursor/rules, CLAUDE.md, and AGENTS.md so all team agents follow identical guardrails.
Architectural Directives in Detail

Step-by-Step Production Directives

Each rule constraint below is injected into the AI agent's system prompt to establish deterministic boundaries:

1

Engineers MUST ALWAYS wrap raw async transactions in an RAII guard that dispatches background rollback or connection eviction upon synchronous drop unless explicitly committed.

Engineers MUST ALWAYS wrap raw async transactions in an RAII guard that dispatches background rollback or connection eviction upon synchronous drop unless explicitly committed.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
2

Engineers MUST NOT rely on manual async `.rollback().await` calls at the end of functions, as Tokio cancellation points (`tokio

Engineers MUST NOT rely on manual async `.rollback().await` calls at the end of functions, as Tokio cancellation points (`tokio::select!`, `tokio::time::timeout`) bypass subsequent async instructions.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
3

Code SHOULD leverage explicit ownership transitions (e.g., `guard.commit().await?`) that disarm the RAII rollback trigger only upon verified database acknowledgement.

Code SHOULD leverage explicit ownership transitions (e.g., `guard.commit().await?`) that disarm the RAII rollback trigger only upon verified database acknowledgement.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
4

Services MUST ensure that if an RAII guard drops without being committed, it dispatches non-blocking rollback tasks via `tokio

Services MUST ensure that if an RAII guard drops without being committed, it dispatches non-blocking rollback tasks via `tokio::spawn` or discards/resets the physical connection from the pool.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
5

Components NEVER hold uncommitted database locks across untimed external RPC calls or unshielded cancellation yields.

Components NEVER hold uncommitted database locks across untimed external RPC calls or unshielded cancellation yields.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
Technical Questions & Answers

Frequently Asked Technical Questions

Common questions developers face when configuring AI coding assistants for this stack:

Q:Why is Tokio Async-Cancellation Scope-Safe Transaction RAII Guard critical for AI coding assistants?

Enforces synchronous Drop RAII guards with background rollback dispatching for database transactions across Tokio yield points. Prevents connection pool starvation, orphaned row-level locks, and phantom writes caused by dropped futures in cancellation scenarios like timeouts and select branches. Guarantees deterministic abort execution even when async executors drop executing futures without running async cleanup blocks. Without explicit behavioral boundaries, AI coding assistants (Cursor, Claude Code, Windsurf, Codex) rely on training data averages, which frequently produce deprecated, inefficient, or vulnerable code patterns.

Q:How does adopting this rule prevent AI hallucinations?

This rule explicitly declares what the AI must avoid (Dropping uncommitted async database transactions across Tokio cancellation boundaries without an RAII-dispatched background rollback) and prescribes verified positive examples. Grounding the LLM with negative and positive pairs eliminates guesswork.

Q:Which AI coding environments are supported?

This specification is multi-platform compatible: Cursor (.cursor/rules/*.mdc & .cursorrules), Anthropic Claude Code (CLAUDE.md), Windsurf (.windsurfrules), Codex / Cline (AGENTS.md), and GitHub Copilot (.github/copilot-instructions.md).

Q:Can I combine this rule with other technology stacks?

Yes. Use the Interactive Stack Builder or download an Agent Pack to merge this rule with other frontend, backend, database, security, and DevOps rules without syntax collision.

Open Specification · CC BY 4.0·Free for Personal, Team & Commercial In-Repo Use

Citation & Open Source Attribution Guidelines

This specification is licensed under Creative Commons Attribution 4.0 International (CC BY 4.0). You are completely free to adapt and share this rule in your workspace. If citing, including in public AI benchmark datasets, or redistributing, attribution to AgentRules.org is required.

1 Rule in Stack

Tokio