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

Axum 0.8 / Tokio Async Cancellation Safety in State Mutations

Enforces cancellation safety across asynchronous state mutations, transactional database operations, and shared resource acquisitions in Axum 0.8 handlers. Eliminates silent state corruption, partial writes, and orphaned transaction locks caused by dropped futures during client disconnects or tokio::select! branch termination.

Prohibited Anti-Pattern: Awaiting multi-step database mutations or shared state locks directly inside cancellation-vulnerable request futures

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Axum 0.8 / Tokio Async Cancellation Safety in State Mutations - Enforces cancellation safety across asynchronous state mutations, transactional database operations, and shared resource acquisitions in Axum 0.8 handlers. Eliminates silent state corruption, partial writes, and orphaned transaction locks caused by dropped futures during client disconnects or tokio::select! branch termination.
globs: src/**/*.rs
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/axum-tokio-cancellation-safety-state-mutations"
---

# Axum 0.8 / Tokio Async Cancellation Safety in State Mutations

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Awaiting multi-step database mutations or shared state locks directly inside cancellation-vulnerable request futures

## System Constraints
You are a Principal Rust Architect enforcing zero-corruption concurrency invariants for Axum 0.8 and Tokio. When HTTP clients terminate connections early, or when branches inside `tokio::select!` resolve, remaining pending futures are instantaneously dropped at their last `.await` point. You must mandate that critical multi-step database mutations, non-atomic business state updates, and transactional blocks run to completion in decoupled background tasks (`tokio::spawn`) or utilize atomic, drop-resilient transactional rollbacks, guaranteeing that early drops cannot cause orphaned locks or partial state persistence.

## Strict Guidelines
- Engineers MUST ALWAYS isolate non-idempotent or multi-step database mutations from direct cancellation points using `tokio::spawn` or explicit linear state machines.
- Engineers MUST NOT run multi-statement state updates across `.await` points inside branches of `tokio::select!` unless each branch is proven cancellation-safe.
- Code MUST ensure that SQL transactions automatically rollback on early drop by relying on RAII guard objects (e.g., `sqlx::Transaction` drop semantics) rather than manual commit/rollback sequences interleaved with cancellation points.
- Services MUST spawn background jobs (`tokio::spawn`) when handling operations that must be atomic across multiple third-party external calls (e.g., payment capture + local database balance decrement) to decouple execution from the client's HTTP request lifecycle.
- Components NEVER hold intermediate in-memory synchronization locks (such as `tokio::sync::MutexGuard`) across unrelated external I/O `.await` points where dropping the future leaves invariant breaches.

## Bad vs Good Implementations
### Multi-Step Database Mutation with Client Drop Vulnerability

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: If the HTTP client terminates the TCP connection during the `tokio::time::sleep` or between query steps, Axum drops the handler future. While `sqlx::Transaction` will drop and trigger a SQL rollback, any interleaving state changes (e.g., audit log broadcasts, redis tokens, metrics) remain half-applied. In cases without an explicit transaction, this leaves debit complete without credit.
```rust
use axum::{extract::State, http::StatusCode, response::IntoResponse, Json};
use sqlx::PgPool;
use serde::Deserialize;

#[derive(Deserialize)]
pub struct TransferRequest {
    from_id: i64,
    to_id: i64,
    amount: i64,
}

// ANTI-PATTERN: If client disconnects or timeout aborts between debit and credit,
// or inside tokio::select!, partial execution leaves corrupted financial state.
pub async fn transfer_funds(
    State(pool): State<PgPool>,
    Json(payload): Json<TransferRequest>,
) -> Result<impl IntoResponse, StatusCode> {
    let mut tx = pool.begin().await.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;

    // Point of vulnerability 1: Cancellation here leaves nothing written
    sqlx::query!("UPDATE accounts SET balance = balance - $1 WHERE id = $2", payload.amount, payload.from_id)
        .execute(&mut *tx)
        .await
        .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;

    // Simulate downstream external latency / risk point
    tokio::time::sleep(std::time::Duration::from_millis(50)).await;

    // Point of vulnerability 2: If future is dropped here by client disconnect,
    // transaction might roll back, but partial external ledgering/metrics are desynced.
    sqlx::query!("UPDATE accounts SET balance = balance + $1 WHERE id = $2", payload.amount, payload.to_id)
        .execute(&mut *tx)
        .await
        .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;

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

#### Production Standard (Correct)
> **Standard**: By spawning the transactional unit of work via `tokio::spawn`, execution ownership moves to the Tokio runtime. Early client disconnection only drops the receiver (`rx_reply`), while the spawned worker task executes atomically to completion (either full commit or full rollback via the SQL driver), eliminating orphaned locks and partial non-atomic state drift.
```rust
use axum::{extract::State, http::StatusCode, response::IntoResponse, Json};
use sqlx::PgPool;
use serde::Deserialize;
use tokio::sync::oneshot;

#[derive(Deserialize)]
pub struct TransferRequest {
    from_id: i64,
    to_id: i64,
    amount: i64,
}

// PRODUCTION FIX: Critical multi-statement mutations are isolated in a detached,
// guaranteed-completion spawned task. Client disconnect cannot interrupt atomic execution.
pub async fn transfer_funds(
    State(pool): State<PgPool>,
    Json(payload): Json<TransferRequest>,
) -> Result<impl IntoResponse, StatusCode> {
    let (tx_reply, rx_reply) = oneshot::channel();

    tokio::spawn(async move {
        let res = async {
            let mut tx = pool.begin().await?;

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

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

            tx.commit().await?;
            Ok::<(), sqlx::Error>(())
        }
        .await;

        let _ = tx_reply.send(res);
    });

    match rx_reply.await {
        Ok(Ok(())) => Ok(StatusCode::OK),
        Ok(Err(_)) => Err(StatusCode::INTERNAL_SERVER_ERROR),
        Err(_) => Err(StatusCode::INTERNAL_SERVER_ERROR),
    }
}
```

Recommended MCP Servers (mcp-serverlist.com)

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

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Axum 0.8 / Tokio Async Cancellation Safety in State Mutations

Axum 0.8 / Tokio Async Cancellation Safety in State Mutations defines an industrial-grade behavioral standard for backend engineering. Enforces cancellation safety across asynchronous state mutations, transactional database operations, and shared resource acquisitions in Axum 0.8 handlers. Eliminates silent state corruption, partial writes, and orphaned transaction locks caused by dropped futures during client disconnects or tokio::select! branch termination. 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: Awaiting multi-step database mutations or shared state locks directly inside cancellation-vulnerable request futures 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 DriftAwaiting multi-step database mutations or shared state locks directly inside cancellation-vulnerable request futuresCritical
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 isolate non-idempotent or multi-step database mutations from direct cancellation points using `tokio

Engineers MUST ALWAYS isolate non-idempotent or multi-step database mutations from direct cancellation points using `tokio::spawn` or explicit linear state machines.

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 run multi-statement state updates across `.await` points inside branches of `tokio

Engineers MUST NOT run multi-statement state updates across `.await` points inside branches of `tokio::select!` unless each branch is proven cancellation-safe.

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 SQL transactions automatically rollback on early drop by relying on RAII guard objects (e.g., `sqlx

Code MUST ensure that SQL transactions automatically rollback on early drop by relying on RAII guard objects (e.g., `sqlx::Transaction` drop semantics) rather than manual commit/rollback sequences interleaved with cancellation points.

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 spawn background jobs (`tokio

Services MUST spawn background jobs (`tokio::spawn`) when handling operations that must be atomic across multiple third-party external calls (e.g., payment capture + local database balance decrement) to decouple execution from the client's HTTP request lifecycle.

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 intermediate in-memory synchronization locks (such as `tokio

Components NEVER hold intermediate in-memory synchronization locks (such as `tokio::sync::MutexGuard`) across unrelated external I/O `.await` points where dropping the future leaves invariant breaches.

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 Async Cancellation Safety in State Mutations critical for AI coding assistants?

Enforces cancellation safety across asynchronous state mutations, transactional database operations, and shared resource acquisitions in Axum 0.8 handlers. Eliminates silent state corruption, partial writes, and orphaned transaction locks caused by dropped futures during client disconnects or tokio::select! branch termination. 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 (Awaiting multi-step database mutations or shared state locks directly inside cancellation-vulnerable request futures) 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