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

Axum 0.8 & Tower Async Cancellation Safety Invariant

Enforces strict async cancellation safety across Axum 0.8 handlers and Tower middleware layers. In Tokio runtimes, premature client disconnects drop the request future synchronously at any `.await` boundary, leading to severed transactions, half-applied state transitions, and connection starvation unless atomic mutations are shielded or decoupled.

Prohibited Anti-Pattern: Executing Non-Atomic Multi-Step Mutations Inside Ephemeral Request Futures Subject to Client Disconnect Drops

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Axum 0.8 & Tower Async Cancellation Safety Invariant - Enforces strict async cancellation safety across Axum 0.8 handlers and Tower middleware layers. In Tokio runtimes, premature client disconnects drop the request future synchronously at any `.await` boundary, leading to severed transactions, half-applied state transitions, and connection starvation unless atomic mutations are shielded or decoupled.
globs: src/**/*.rs
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/axum-tower-async-cancellation-safety-invariant"
---

# Axum 0.8 & Tower Async Cancellation Safety Invariant

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Executing Non-Atomic Multi-Step Mutations Inside Ephemeral Request Futures Subject to Client Disconnect Drops

## System Constraints
You are a Principal Software Architect enforcing Axum 0.8 and Tower async cancellation safety invariants. In Rust's Tokio runtime, dropping a Future at an `.await` point causes immediate synchronous destruction of local stack variables and deferred operations. You must ensure that critical multi-step mutations, database transactions, external side effects, and shared state locks are never exposed to abrupt drops caused by client HTTP cancellations.

## Strict Guidelines
- Engineers MUST ALWAYS decouple critical multi-step mutations from the HTTP client connection lifecycle using detached `tokio::spawn` tasks or transactional outbox patterns.
- Engineers MUST NOT interleave high-latency external network calls (such as third-party APIs or message publishers) within open database transaction boundaries inside an Axum handler.
- Code SHOULD verify cancellation safety of all Tower `Service::call` and middleware implementations to prevent orphaned permits and inconsistent state across yields.
- Services MUST leverage RAII drop guards and dedicated background supervisors when non-cancellable tasks (such as financial transactions or audit trails) must execute to completion.
- Components NEVER assume an Axum handler will complete after executing an `.await` statement; any code following an await must be safe to abandon without corrupting system invariants.

## Bad vs Good Implementations
### Cancellation-Vulnerable Database Mutation vs. Shielded Background Task

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: When an HTTP client aborts the connection (e.g., timeout, navigation away), Axum drops the handler future. If dropped during the external API call or the commit step, the local transaction is rolled back via Drop, resulting in split-brain state where the external charge succeeded but database records were cancelled.
```rust
use axum::{extract::State, http::StatusCode, Json};
use sqlx::PgPool;
use serde::Deserialize;

#[derive(Deserialize)]
pub struct PaymentRequest {
    user_id: i64,
    amount_cents: i64,
}

// ANTI-PATTERN: If the client drops connection during stripe_client.charge().await,
// the handler future is dropped. The DB transaction drops (rolls back), but Stripe charged the user.
// Conversely, if client drops during tx.commit().await, Stripe is charged with no DB record.
pub async fn process_payment_bad(
    State(pool): State<PgPool>,
    Json(payload): Json<PaymentRequest>,
) -> Result<StatusCode, StatusCode> {
    let mut tx = pool.begin().await.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
    
    sqlx::query!("UPDATE accounts SET balance = balance - $1 WHERE id = $2", payload.amount_cents, payload.user_id)
        .execute(&mut *tx)
        .await
        .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;

    // CANCELLATION HAZARD: Client abort drops future right here!
    let charge_id = external_stripe_charge(payload.user_id, payload.amount_cents).await
        .map_err(|_| StatusCode::BAD_GATEWAY)?;

    sqlx::query!("INSERT INTO payments (charge_id, user_id) VALUES ($1, $2)", charge_id, payload.user_id)
        .execute(&mut *tx)
        .await
        .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;

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

async fn external_stripe_charge(_user: i64, _amount: i64) -> Result<String, ()> { Ok("ch_123".into()) }
```

#### Production Standard (Correct)
> **Standard**: Decouples volatile HTTP request futures from mission-critical multi-step transactions. The handler immediately persists an intent and delegates the unsafe external/DB mutation to a detached `tokio::spawn` task. Client disconnects no longer sever pending mutations mid-flight.
```rust
use axum::{extract::State, http::StatusCode, Json};
use sqlx::PgPool;
use serde::Deserialize;
use uuid::Uuid;

#[derive(Deserialize, Clone)]
pub struct PaymentRequest {
    user_id: i64,
    amount_cents: i64,
}

pub async fn process_payment_good(
    State(pool): State<PgPool>,
    Json(payload): Json<PaymentRequest>,
) -> Result<Json<Uuid>, StatusCode> {
    let idempotency_key = Uuid::new_v4();

    // 1. Atomically record pending intent inside standard client request lifecycle
    sqlx::query!(
        "INSERT INTO payment_intents (id, user_id, amount_cents, status) VALUES ($1, $2, $3, 'pending')",
        idempotency_key,
        payload.user_id,
        payload.amount_cents
    )
    .execute(&pool)
    .await
    .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;

    // 2. Shield the non-cancellable execution path using tokio::spawn.
    // Client disconnects will NOT cancel background worker execution.
    let pool_clone = pool.clone();
    tokio::spawn(async move {
        if let Err(e) = execute_payment_pipeline(pool_clone, idempotency_key, payload).await {
            tracing::error!(error = ?e, %idempotency_key, "Payment execution failed in background");
        }
    });

    Ok(Json(idempotency_key))
}

async fn execute_payment_pipeline(
    pool: PgPool,
    intent_id: Uuid,
    payload: PaymentRequest,
) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
    // Background execution runs to completion regardless of HTTP socket termination
    let charge_id = external_stripe_charge(payload.user_id, payload.amount_cents).await?;
    
    let mut tx = pool.begin().await?;
    sqlx::query!("UPDATE accounts SET balance = balance - $1 WHERE id = $2", payload.amount_cents, payload.user_id)
        .execute(&mut *tx)
        .await?;
        
    sqlx::query!(
        "UPDATE payment_intents SET status = 'completed', provider_charge_id = $1 WHERE id = $2",
        charge_id,
        intent_id
    )
    .execute(&mut *tx)
    .await?;
    
    tx.commit().await?;
    Ok(())
}

async fn external_stripe_charge(_user: i64, _amount: i64) -> Result<String, &'static str> { Ok("ch_123".into()) }
```

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 & Tower Async Cancellation Safety Invariant

Axum 0.8 & Tower Async Cancellation Safety Invariant defines an industrial-grade behavioral standard for backend engineering. Enforces strict async cancellation safety across Axum 0.8 handlers and Tower middleware layers. In Tokio runtimes, premature client disconnects drop the request future synchronously at any `.await` boundary, leading to severed transactions, half-applied state transitions, and connection starvation unless atomic mutations are shielded or decoupled. 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: Executing Non-Atomic Multi-Step Mutations Inside Ephemeral Request Futures Subject to Client Disconnect Drops 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 DriftExecuting Non-Atomic Multi-Step Mutations Inside Ephemeral Request Futures Subject to Client Disconnect DropsCritical
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 decouple critical multi-step mutations from the HTTP client connection lifecycle using detached `tokio

Engineers MUST ALWAYS decouple critical multi-step mutations from the HTTP client connection lifecycle using detached `tokio::spawn` tasks or transactional outbox patterns.

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 interleave high-latency external network calls (such as third-party APIs or message publishers) within open database transaction boundaries inside an Axum handler.

Engineers MUST NOT interleave high-latency external network calls (such as third-party APIs or message publishers) within open database transaction boundaries inside an Axum handler.

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 verify cancellation safety of all Tower `Service

Code SHOULD verify cancellation safety of all Tower `Service::call` and middleware implementations to prevent orphaned permits and inconsistent state across 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.
4

Services MUST leverage RAII drop guards and dedicated background supervisors when non-cancellable tasks (such as financial transactions or audit trails) must execute to completion.

Services MUST leverage RAII drop guards and dedicated background supervisors when non-cancellable tasks (such as financial transactions or audit trails) must execute to completion.

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 assume an Axum handler will complete after executing an `.await` statement

Components NEVER assume an Axum handler will complete after executing an `.await` statement; any code following an await must be safe to abandon without corrupting system invariants.

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 & Tower Async Cancellation Safety Invariant critical for AI coding assistants?

Enforces strict async cancellation safety across Axum 0.8 handlers and Tower middleware layers. In Tokio runtimes, premature client disconnects drop the request future synchronously at any `.await` boundary, leading to severed transactions, half-applied state transitions, and connection starvation unless atomic mutations are shielded or decoupled. 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 (Executing Non-Atomic Multi-Step Mutations Inside Ephemeral Request Futures Subject to Client Disconnect Drops) 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