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

Axum 0.8 Tokio Task-Local Cancellation-Safe Transaction Rollback Guard

Enforces cancellation-safe transaction semantics in Axum 0.8 handlers driven by Tokio runtimes. Eliminates orphaned locks, dirty pool connections, and leaked task-local state caused by abrupt client disconnects dropping handler futures at arbitrary await points.

Prohibited Anti-Pattern: Procedural rollback in match arms bypassed by Tokio future drop on client disconnect

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Axum 0.8 Tokio Task-Local Cancellation-Safe Transaction Rollback Guard - Enforces cancellation-safe transaction semantics in Axum 0.8 handlers driven by Tokio runtimes. Eliminates orphaned locks, dirty pool connections, and leaked task-local state caused by abrupt client disconnects dropping handler futures at arbitrary await points.
globs: src/**/*.rs, crates/**/*.rs
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/axum-tokio-cancellation-safe-tx-guard"
---

# Axum 0.8 Tokio Task-Local Cancellation-Safe Transaction Rollback Guard

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Procedural rollback in match arms bypassed by Tokio future drop on client disconnect

## System Constraints
You are a Principal Rust Distributed Systems Engineer enforcing Axum 0.8 and Tokio task-level cancellation safety. Every HTTP handler awaiting database transactions MUST be resilient against abrupt cancellation (future dropping). You must mandate RAII-driven rollback mechanisms, task-local state cleanup, and cancellation shields around atomic finalization phases.

## Strict Guidelines
- Engineers MUST ALWAYS rely on RAII Drop semantics or explicit cancellation tokens rather than manual procedural rollback (.rollback().await) in error arms.
- Engineers MUST NOT execute multi-phase commits or critical state mutations directly inside cancellable handler branches without tokio::task::spawn or non-cancellable shielding.
- Code MUST ensure that database connection pools (such as sqlx::Pool) clean up transaction state via the Transaction struct's Drop implementation or detached background worker tasks.
- Services MUST clear or reset tokio::task_local! state when entering or exiting cancellation boundaries to prevent thread/task context leakage.
- Components NEVER hold advisory or row-level pessimistic locks across unshielded external network I/O await boundaries.

## Bad vs Good Implementations
### Vulnerable Procedural Rollback vs Cancellation-Safe RAII & Shielded Commit

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: When an HTTP client aborts the request during the 500ms sleep or debit query, Tokio drops the handler future immediately. The procedural rollback() calls in the error branches are bypassed. While sqlx::Transaction issues an async rollback on drop in the background, pending task-local states leak, and long-lived transactions waiting on cancellation-susceptible branches lock table rows until connection reset.
```rust
use axum::{extract::State, http::StatusCode, response::IntoResponse, Json};
use sqlx::{PgPool, Postgres, Transaction};

pub async fn transfer_funds(
    State(pool): State<PgPool>,
    Json(payload): Json<TransferRequest>,
) -> Result<impl IntoResponse, StatusCode> {
    let mut tx: Transaction<'_, Postgres> = pool.begin().await.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;

    // ANTI-PATTERN: If client disconnects here, the future drops.
    // Procedural rollback is never reached, leaving locks active until server timeout.
    let debit_res = sqlx::query!("UPDATE accounts SET balance = balance - $1 WHERE id = $2 AND balance >= $1", payload.amount, payload.from)
        .execute(&mut *tx)
        .await;

    if debit_res.is_err() {
        let _ = tx.rollback().await; // Skipped on cancellation!
        return Err(StatusCode::BAD_REQUEST);
    }

    // External I/O while holding unshielded lock
    tokio::time::sleep(std::time::Duration::from_millis(500)).await;

    let credit_res = sqlx::query!("UPDATE accounts SET balance = balance + $1 WHERE id = $2", payload.amount, payload.to)
        .execute(&mut *tx)
        .await;

    if credit_res.is_err() {
        let _ = tx.rollback().await;
        return Err(StatusCode::INTERNAL_SERVER_ERROR);
    }

    tx.commit().await.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
    Ok(StatusCode::OK)
}
```

#### Production Standard (Correct)
> **Standard**: Uses RAII-driven drop mechanics so that any client disconnect automatically triggers sqlx's background connection rollback without relying on procedural catch blocks. The final tx.commit() is detached and shielded via tokio::task::spawn, preventing incomplete commits if the client disconnects precisely as the commit packet is being dispatched. Task-locals are scoped to guard against contextual cross-request pollution.
```rust
use axum::{extract::State, http::StatusCode, response::IntoResponse, Json};
use sqlx::{PgPool, Postgres, Transaction};

tokio::task_local! {
    static TRACE_TX_ID: String;
}

pub async fn transfer_funds(
    State(pool): State<PgPool>,
    Json(payload): Json<TransferRequest>,
) -> Result<impl IntoResponse, StatusCode> {
    let tx_id = uuid::Uuid::new_v4().to_string();

    // Scope task-local context safely across future cancellation boundaries
    TRACE_TX_ID.scope(tx_id, async move {
        let mut tx: Transaction<'_, Postgres> = pool.begin().await.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;

        // Phase 1: Mutations within transaction. RAII handles rollback automatically if dropped.
        let rows_affected = sqlx::query!(
            "UPDATE accounts SET balance = balance - $1 WHERE id = $2 AND balance >= $1",
            payload.amount,
            payload.from
        )
        .execute(&mut *tx)
        .await
        .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?
        .rows_affected();

        if rows_affected == 0 {
            // Explicit return drops tx; Drop implementation safely triggers asynchronous rollback
            return Err(StatusCode::BAD_REQUEST);
        }

        sqlx::query!(
            "UPDATE accounts SET balance = balance + $1 WHERE id = $2",
            payload.amount,
            payload.to
        )
        .execute(&mut *tx)
        .await
        .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;

        // Phase 2: Shield commit from client cancellation using tokio::task::spawn
        // Ensuring atomic completion once all invariants are met.
        tokio::task::spawn(async move {
            tx.commit().await
        })
        .await
        .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?
        .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;

        Ok(StatusCode::OK)
    }).await
}
```

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: Axum 0.8 Tokio Task-Local Cancellation-Safe Transaction Rollback Guard

Axum 0.8 Tokio Task-Local Cancellation-Safe Transaction Rollback Guard defines an industrial-grade behavioral standard for backend engineering. Enforces cancellation-safe transaction semantics in Axum 0.8 handlers driven by Tokio runtimes. Eliminates orphaned locks, dirty pool connections, and leaked task-local state caused by abrupt client disconnects dropping handler futures at arbitrary await points. 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: Procedural rollback in match arms bypassed by Tokio future drop on client disconnect 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 DriftProcedural rollback in match arms bypassed by Tokio future drop on client disconnectCritical
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 rely on RAII Drop semantics or explicit cancellation tokens rather than manual procedural rollback (.rollback().await) in error arms.

Engineers MUST ALWAYS rely on RAII Drop semantics or explicit cancellation tokens rather than manual procedural rollback (.rollback().await) in error arms.

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 execute multi-phase commits or critical state mutations directly inside cancellable handler branches without tokio

Engineers MUST NOT execute multi-phase commits or critical state mutations directly inside cancellable handler branches without tokio::task::spawn or non-cancellable shielding.

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 MUST ensure that database connection pools (such as sqlx

Code MUST ensure that database connection pools (such as sqlx::Pool) clean up transaction state via the Transaction struct's Drop implementation or detached background worker tasks.

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 clear or reset tokio

Services MUST clear or reset tokio::task_local! state when entering or exiting cancellation boundaries to prevent thread/task context leakage.

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 advisory or row-level pessimistic locks across unshielded external network I/O await boundaries.

Components NEVER hold advisory or row-level pessimistic locks across unshielded external network I/O await boundaries.

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 Axum 0.8 Tokio Task-Local Cancellation-Safe Transaction Rollback Guard critical for AI coding assistants?

Enforces cancellation-safe transaction semantics in Axum 0.8 handlers driven by Tokio runtimes. Eliminates orphaned locks, dirty pool connections, and leaked task-local state caused by abrupt client disconnects dropping handler futures at arbitrary await points. 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 (Procedural rollback in match arms bypassed by Tokio future drop on client disconnect) 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

Axum