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

Axum 0.8 Tokio CancellationToken Propagation & Immediate Cancellation Cascade

Enforces deterministic cancellation propagation across Axum 0.8 request pipelines, active database drivers, and upstream RPC clients. Premature HTTP client disconnects must immediately abort pending transactions, connection acquisitions, and downstream HTTP/gRPC requests via Tokio CancellationTokens and drop-aware execution boundaries to prevent phantom resource exhaustion.

Prohibited Anti-Pattern: Orphaned Detached Task Execution and Zombie Database Transactions on Premature HTTP Client Disconnect

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Axum 0.8 Tokio CancellationToken Propagation & Immediate Cancellation Cascade - Enforces deterministic cancellation propagation across Axum 0.8 request pipelines, active database drivers, and upstream RPC clients. Premature HTTP client disconnects must immediately abort pending transactions, connection acquisitions, and downstream HTTP/gRPC requests via Tokio CancellationTokens and drop-aware execution boundaries to prevent phantom resource exhaustion.
globs: src/**/*.rs
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/axum-08-tokio-cancellation-token-propagation-standard"
---

# Axum 0.8 Tokio CancellationToken Propagation & Immediate Cancellation Cascade

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Orphaned Detached Task Execution and Zombie Database Transactions on Premature HTTP Client Disconnect

## System Constraints
You are a Principal Software Architect enforcing the Axum 0.8 Tokio CancellationToken Propagation Standard. You must mandate that every asynchronous handler either relies deterministically on top-level future dropping or propagates a child `tokio_util::sync::CancellationToken` to all spawned tasks, database transaction guards, and outbound RPC calls. Prevent detached `tokio::spawn` calls without lifecycle bindings, uncancelable long-polling operations, and uninstrumented database pools from creating zombie compute cycles during client disconnects.

## Strict Guidelines
- Engineers MUST ALWAYS bind child `tokio_util::sync::CancellationToken` instances to the Axum request lifecycle whenever detached or spawned concurrent sub-tasks (`tokio::spawn`) are introduced.
- Engineers MUST NOT spawn detached Tokio tasks (`tokio::spawn`) inside handlers for downstream work without passing a cancellation signal and awaiting a correlated join handle with drop guarantees.
- Handlers MUST pass active cancellation tokens or rely on `tokio::select!` branch cancellation when dispatching outbound HTTP requests (`reqwest`), gRPC calls (`tonic`), or SQL executions (`sqlx`).
- Services MUST ensure database transactions utilize drop guards or active cancellation channels so that premature client disconnects trigger an immediate `ROLLBACK` rather than hanging on connection locks.
- Code SHOULD leverage Axum connection drop signaling (such as `axum::extract::Request` body drop detection or custom connection-monitoring middleware) to broadcast cancellation downwards immediately.
- Components NEVER execute unbounded background work inside handler futures without explicitly decoupling that work into a durable message queue or supervisor-managed worker.

## Bad vs Good Implementations
### Cancellation Token Propagation across Spawned Work and DB/RPC Calls

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Spawning detached work via tokio::spawn severs the handler's cancellation context. When an HTTP client aborts or drops the connection, the spawned task continues executing, resulting in phantom external API charges, connection pool saturation, and state corruption.
```rust
use axum::{extract::State, Json, response::IntoResponse};
use sqlx::PgPool;

pub async fn checkout_handler(
    State(pool): State<PgPool>,
    Json(payload): Json<OrderRequest>,
) -> impl IntoResponse {
    // ANTI-PATTERN: Detached task spawns without cancellation propagation.
    // If client disconnects here, this spawned task continues indefinitely,
    // exhausting DB connections and calling 3rd-party payment gateways.
    tokio::spawn(async move {
        let mut tx = pool.begin().await.unwrap();
        let _res = sqlx::query!("UPDATE inventory SET stock = stock - 1 WHERE id = $1", payload.item_id)
            .execute(&mut *tx)
            .await
            .unwrap();
        
        // Long-running upstream RPC ignoring client state
        reqwest::Client::new()
            .post("https://payment.gateway/charge")
            .json(&payload)
            .send()
            .await
            .unwrap();

        tx.commit().await.unwrap();
    });

    "Accepted"
}
```

#### Production Standard (Correct)
> **Standard**: A request-scoped CancellationToken with a DropGuard ensures that premature client drops immediately trigger the cancellation branch. Upstream HTTP calls and database transactions are bound via tokio::select!, ensuring transactions are dropped and rolled back immediately without orphaned side effects.
```rust
use axum::{extract::State, http::StatusCode, response::IntoResponse, Json};
use sqlx::PgPool;
use tokio_util::sync::{CancellationToken, DropGuard};

pub async fn checkout_handler(
    State(pool): State<PgPool>,
    Json(payload): Json<OrderRequest>,
) -> Result<impl IntoResponse, StatusCode> {
    // Create a request-scoped cancellation token linked to handler lifetime
    let token = CancellationToken::new();
    let _guard: DropGuard = token.clone().drop_guard();

    // Bound work to the cancellation token or handler drop context
    tokio::select! {
        _ = token.cancelled() => {
            // Propagated to child routines automatically
            Err(StatusCode::REQUEST_TIMEOUT)
        }
        res = process_order(&pool, payload, token.clone()) => {
            res.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
            Ok(StatusCode::OK)
        }
    }
}

async fn process_order(
    pool: &PgPool,
    payload: OrderRequest,
    token: CancellationToken,
) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
    // Cooperative cancellation on DB acquisition and transaction
    tokio::select! {
        _ = token.cancelled() => return Err("Client aborted request".into()),
        mut tx = pool.begin() => {
            let mut tx = tx?;
            sqlx::query!("UPDATE inventory SET stock = stock - 1 WHERE id = $1", payload.item_id)
                .execute(&mut *tx)
                .await?;

            // Outbound RPC strictly bound to the cancellation token
            let client = reqwest::Client::new();
            let req = client.post("https://payment.gateway/charge").json(&payload).build()?;
            
            tokio::select! {
                _ = token.cancelled() => {
                    // Explicit rollback occurs automatically on tx drop
                    return Err("Client disconnected prior to payment RPC completion".into());
                }
                res = client.execute(req) => {
                    res?.error_for_status()?;
                }
            }

            tx.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: Axum 0.8 Tokio CancellationToken Propagation & Immediate Cancellation Cascade

Axum 0.8 Tokio CancellationToken Propagation & Immediate Cancellation Cascade defines an industrial-grade behavioral standard for backend engineering. Enforces deterministic cancellation propagation across Axum 0.8 request pipelines, active database drivers, and upstream RPC clients. Premature HTTP client disconnects must immediately abort pending transactions, connection acquisitions, and downstream HTTP/gRPC requests via Tokio CancellationTokens and drop-aware execution boundaries to prevent phantom resource exhaustion. 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: Orphaned Detached Task Execution and Zombie Database Transactions on Premature HTTP 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 DriftOrphaned Detached Task Execution and Zombie Database Transactions on Premature HTTP 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 bind child `tokio_util

Engineers MUST ALWAYS bind child `tokio_util::sync::CancellationToken` instances to the Axum request lifecycle whenever detached or spawned concurrent sub-tasks (`tokio::spawn`) are introduced.

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 detached Tokio tasks (`tokio

Engineers MUST NOT spawn detached Tokio tasks (`tokio::spawn`) inside handlers for downstream work without passing a cancellation signal and awaiting a correlated join handle with drop guarantees.

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

Handlers MUST pass active cancellation tokens or rely on `tokio

Handlers MUST pass active cancellation tokens or rely on `tokio::select!` branch cancellation when dispatching outbound HTTP requests (`reqwest`), gRPC calls (`tonic`), or SQL executions (`sqlx`).

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 database transactions utilize drop guards or active cancellation channels so that premature client disconnects trigger an immediate `ROLLBACK` rather than hanging on connection locks.

Services MUST ensure database transactions utilize drop guards or active cancellation channels so that premature client disconnects trigger an immediate `ROLLBACK` rather than hanging on connection locks.

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

Code SHOULD leverage Axum connection drop signaling (such as `axum

Code SHOULD leverage Axum connection drop signaling (such as `axum::extract::Request` body drop detection or custom connection-monitoring middleware) to broadcast cancellation downwards immediately.

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 execute unbounded background work inside handler futures without explicitly decoupling that work into a durable message queue or supervisor-managed worker.

Components NEVER execute unbounded background work inside handler futures without explicitly decoupling that work into a durable message queue or supervisor-managed worker.

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 CancellationToken Propagation & Immediate Cancellation Cascade critical for AI coding assistants?

Enforces deterministic cancellation propagation across Axum 0.8 request pipelines, active database drivers, and upstream RPC clients. Premature HTTP client disconnects must immediately abort pending transactions, connection acquisitions, and downstream HTTP/gRPC requests via Tokio CancellationTokens and drop-aware execution boundaries to prevent phantom resource exhaustion. 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 (Orphaned Detached Task Execution and Zombie Database Transactions on Premature HTTP 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