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

Axum 0.8 & Tower Async Cancellation and Downstream Drop Safety Invariants

Enforces deterministic teardown of downstream asynchronous tasks and RAII guard patterns when client disconnects or request bodies drop prematurely in Axum 0.8. Prevents background CPU starvation, orphan unbounded execution, and lingering pooled database connection checkouts caused by unhandled Rust async cancellation points. Mandates tokio::select! drop awareness, cancellation tokens, and explicit transaction rollbacks.

Prohibited Anti-Pattern: Spawning detached unbounded futures or holding unmonitored RAII transactional leases across cancellation-vulnerable await points

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Axum 0.8 & Tower Async Cancellation and Downstream Drop Safety Invariants - Enforces deterministic teardown of downstream asynchronous tasks and RAII guard patterns when client disconnects or request bodies drop prematurely in Axum 0.8. Prevents background CPU starvation, orphan unbounded execution, and lingering pooled database connection checkouts caused by unhandled Rust async cancellation points. Mandates tokio::select! drop awareness, cancellation tokens, and explicit transaction rollbacks.
globs: src/**/*.rs, crates/**/*.rs
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/axum-0-8-tower-cancellation-and-drop-safety-guardrail"
---

# Axum 0.8 & Tower Async Cancellation and Downstream Drop Safety Invariants

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Spawning detached unbounded futures or holding unmonitored RAII transactional leases across cancellation-vulnerable await points

## System Constraints
You are a Principal Rust Architect enforcing deterministic asynchronous cancellation, RAII safety, and drop semantics in Axum 0.8 and Tower services. In Rust, async cancellation occurs synchronously at any .await point via future dropping. You must ensure that premature client disconnections, stream aborts, or Tower timeout layer cancellations cleanly reclaim resources, release database connections to pools immediately, roll back uncommitted transactions, and prevent detached background tasks from consuming system resources unchecked.

## Strict Guidelines
- Engineers MUST ALWAYS treat every `.await` point within Axum handlers and Tower middleware as a potential synchronous cancellation exit via `Drop`.
- Engineers MUST NOT spawn unbounded background tasks with `tokio::spawn` inside request handlers unless explicitly tethered to a managed `CancellationToken` or worker pool with deliberate lifecycle supervision.
- Engineers MUST wrap multi-step database mutations within explicit transaction guards where connection checkouts and rollbacks are deterministic upon future drop, rather than relying on delayed pool cleanups.
- Code MUST avoid holding exclusive locks (such as `tokio::sync::Mutex` or transactional table locks) across cancellation-prone I/O streams or long-polling response body streams.
- Services MUST implement `tokio_util::sync::CancellationToken` or `axum::extract::Request::into_body` stream drop detection when orchestrating long-running transactional work or proxy pipelines.
- Components NEVER assume cleanup logic placed sequentially after an `.await` boundary will execute; stateful teardown MUST be encapsulated in explicit RAII `Drop` implementations or guarded by cancellation tokens.

## Bad vs Good Implementations
### Handling Client Disconnection and Database Transaction Drop Safety

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Spawning an unmonitored tokio task prevents the handler from propagating backpressure or respecting cancellation. Conversely, if executed in the handler directly without RAII guard verification, premature drops at .await boundaries can stall transaction rollback or waste database connections in pooled starvation states.
```rust
use axum::{extract::State, Json};
use sqlx::PgPool;
use serde::Deserialize;

#[derive(Deserialize)]
pub struct ProcessPayload { pub items: Vec<String> }

// ANTI-PATTERN: If client disconnects mid-processing, tokio::spawn detaches 
// work indefinitely, while uncommitted database handles may leak or linger.
pub async fn handle_batch(
    State(pool): State<PgPool>,
    Json(payload): Json<ProcessPayload>,
) -> &'static str {
    tokio::spawn(async move {
        let mut tx = pool.begin().await.unwrap();
        for item in payload.items {
            sqlx::query!("INSERT INTO audit_log (entry) VALUES ($1)", item)
                .execute(&mut *tx)
                .await
                .unwrap();
        }
        tx.commit().await.unwrap();
    });

    "accepted"
}
```

#### Production Standard (Correct)
> **Standard**: Uses biased tokio::select! with a CancellationToken and relies on sqlx::Transaction's Drop guard to automatically roll back mutations if client drops future before commit is reached. Avoids orphaned background execution.
```rust
use axum::{extract::State, http::StatusCode, Json};
use sqlx::PgPool;
use serde::Deserialize;
use tokio_util::sync::CancellationToken;
use tracing::{error, info};

#[derive(Deserialize)]
pub struct ProcessPayload { pub items: Vec<String> }

// PRODUCTION INVARIANT: Cooperative cancellation with explicit transactional RAII.
pub async fn handle_batch(
    State(pool): State<PgPool>,
    Json(payload): Json<ProcessPayload>,
) -> Result<StatusCode, StatusCode> {
    let token = CancellationToken::new();
    let _drop_guard = token.clone().drop_guard();

    let mut tx = pool.begin().await.map_err(|e| {
        error!("Failed to acquire db transaction: {e}");
        StatusCode::INTERNAL_SERVER_ERROR
    })?;

    for item in payload.items {
        tokio::select! {
            biased;
            _ = token.cancelled() => {
                info!("Client aborted connection, discarding transaction");
                // sqlx::Transaction automatically triggers rollback on Drop
                return Err(StatusCode::REQUEST_TIMEOUT);
            }
            res = sqlx::query!("INSERT INTO audit_log (entry) VALUES ($1)", item).execute(&mut *tx) => {
                if let Err(e) = res {
                    error!("Insert failed: {e}");
                    return Err(StatusCode::INTERNAL_SERVER_ERROR);
                }
            }
        }
    }

    tx.commit().await.map_err(|e| {
        error!("Commit failed: {e}");
        StatusCode::INTERNAL_SERVER_ERROR
    })?;

    Ok(StatusCode::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: Axum 0.8 & Tower Async Cancellation and Downstream Drop Safety Invariants

Axum 0.8 & Tower Async Cancellation and Downstream Drop Safety Invariants defines an industrial-grade behavioral standard for backend engineering. Enforces deterministic teardown of downstream asynchronous tasks and RAII guard patterns when client disconnects or request bodies drop prematurely in Axum 0.8. Prevents background CPU starvation, orphan unbounded execution, and lingering pooled database connection checkouts caused by unhandled Rust async cancellation points. Mandates tokio::select! drop awareness, cancellation tokens, and explicit transaction rollbacks. 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: Spawning detached unbounded futures or holding unmonitored RAII transactional leases across cancellation-vulnerable await points 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 DriftSpawning detached unbounded futures or holding unmonitored RAII transactional leases across cancellation-vulnerable await pointsCritical
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 treat every `.await` point within Axum handlers and Tower middleware as a potential synchronous cancellation exit via `Drop`.

Engineers MUST ALWAYS treat every `.await` point within Axum handlers and Tower middleware as a potential synchronous cancellation exit via `Drop`.

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 spawn unbounded background tasks with `tokio

Engineers MUST NOT spawn unbounded background tasks with `tokio::spawn` inside request handlers unless explicitly tethered to a managed `CancellationToken` or worker pool with deliberate lifecycle supervision.

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

Engineers MUST wrap multi-step database mutations within explicit transaction guards where connection checkouts and rollbacks are deterministic upon future drop, rather than relying on delayed pool cleanups.

Engineers MUST wrap multi-step database mutations within explicit transaction guards where connection checkouts and rollbacks are deterministic upon future drop, rather than relying on delayed pool cleanups.

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

Code MUST avoid holding exclusive locks (such as `tokio

Code MUST avoid holding exclusive locks (such as `tokio::sync::Mutex` or transactional table locks) across cancellation-prone I/O streams or long-polling response body streams.

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

Services MUST implement `tokio_util

Services MUST implement `tokio_util::sync::CancellationToken` or `axum::extract::Request::into_body` stream drop detection when orchestrating long-running transactional work or proxy pipelines.

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.
6

Components NEVER assume cleanup logic placed sequentially after an `.await` boundary will execute

Components NEVER assume cleanup logic placed sequentially after an `.await` boundary will execute; stateful teardown MUST be encapsulated in explicit RAII `Drop` implementations or guarded by cancellation tokens.

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 and Downstream Drop Safety Invariants critical for AI coding assistants?

Enforces deterministic teardown of downstream asynchronous tasks and RAII guard patterns when client disconnects or request bodies drop prematurely in Axum 0.8. Prevents background CPU starvation, orphan unbounded execution, and lingering pooled database connection checkouts caused by unhandled Rust async cancellation points. Mandates tokio::select! drop awareness, cancellation tokens, and explicit transaction rollbacks. 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 (Spawning detached unbounded futures or holding unmonitored RAII transactional leases across cancellation-vulnerable await points) 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