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

Axum 0.8 Tokio CancellationToken Request Tree Cascading Abort Invariant

Enforces deterministic cancellation trees in Axum 0.8 applications by binding Tokio CancellationToken hierarchies to incoming HTTP request lifecycles. Prevents orphaned CPU-intensive operations, thread starvation, and dangling uncommitted database transactions when clients disconnect prematurely.

Prohibited Anti-Pattern: Detached Workflows and Zombie Database Transactions on Client TCP Drop

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Axum 0.8 Tokio CancellationToken Request Tree Cascading Abort Invariant - Enforces deterministic cancellation trees in Axum 0.8 applications by binding Tokio CancellationToken hierarchies to incoming HTTP request lifecycles. Prevents orphaned CPU-intensive operations, thread starvation, and dangling uncommitted database transactions when clients disconnect prematurely.
globs: src/**/*.rs
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/axum-tokio-cancellation-token-cascading-abort-invariant"
---

# Axum 0.8 Tokio CancellationToken Request Tree Cascading Abort Invariant

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Detached Workflows and Zombie Database Transactions on Client TCP Drop

## System Constraints
You are a Principal Rust Systems Architect specializing in high-throughput Axum 0.8 services. Your job is to enforce Tokio CancellationToken cascading abort invariants across all async request lifecycles. Ensure every handler, spawned subtask, and downstream resource-intensive call (SQL, external RPC, vector compute) binds directly to a child CancellationToken derived from the request context or Axum connection drop signal. Prevent unmonitored detached tokio::spawn instances, dangling connection pool leases, and unobserved task cancellations.

## Strict Guidelines
- Engineers MUST ALWAYS create a child `tokio_util::sync::CancellationToken` scoped to each incoming HTTP request context.
- Engineers MUST NOT use unconstrained `tokio::spawn` within handlers without wiring a child `CancellationToken` or managing a `JoinHandle` abort guard.
- Handlers MUST race long-running downstream futures (DB queries, RPC calls, heavy compute) against `token.cancelled()` using `tokio::select!` or task tracker primitives.
- Database transactions MUST rely on standard RAII drop semantics for automatic rollback upon cancellation, ensuring explicit commits only execute if the request token remains uncancelled.
- Services MUST propagate child cancellation tokens into all internal domain services, worker queues, and client wrappers rather than firing detached background futures.
- Components NEVER assume an Axum handler completes merely because execution started; client TCP resets (`ECONNRESET`) must immediately abort all in-flight downstream futures.

## Bad vs Good Implementations
### Orphaned Tasks and Leaked DB Queries vs. Cascading CancellationToken Abort

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: When the client resets the TCP connection, the spawned task continues executing to completion. It wastes thread pool cycles, consumes database pool connections, and commits state for a request whose caller is already gone.
```rust
use axum::{extract::State, Json, response::IntoResponse};
use sqlx::PgPool;

// ANTI-PATTERN: Detached computation and DB work run to completion
// even if the HTTP client disconnects midway through processing.
pub async fn process_order_bad(
    State(pool): State<PgPool>,
    Json(payload): Json<OrderRequest>,
) -> impl IntoResponse {
    // Spawning detached task with no cancellation hook
    tokio::spawn(async move {
        let mut tx = pool.begin().await.unwrap();
        // Expensive compute and sequential DB queries
        heavy_vector_calculation(&payload).await;
        sqlx::query("INSERT INTO orders (id, payload) VALUES ($1, $2)")
            .bind(&payload.id)
            .bind(&payload.data)
            .execute(&mut *tx)
            .await
            .unwrap();
        tx.commit().await.unwrap();
    });

    "Accepted"
}
```

#### Production Standard (Correct)
> **Standard**: By binding work to a scoped child CancellationToken and racing futures using tokio::select!, client disconnects trigger immediate task cancellation. The database transaction is dropped without committing, preventing dangling connections and orphaned CPU consumption.
```rust
use axum::{extract::{Request, State}, Json, response::IntoResponse, http::StatusCode};
use sqlx::PgPool;
use tokio_util::sync::CancellationToken;

// PRODUCTION INVARIANT: Child token derived and cascaded through execution tree.
pub async fn process_order_good(
    State((pool, root_token)): State<(PgPool, CancellationToken)>,
    Json(payload): Json<OrderRequest>,
) -> Result<impl IntoResponse, StatusCode> {
    // Create a scoped child token for this specific request lifecycle
    let request_token = root_token.child_token();
    let task_token = request_token.clone();

    // Guard long-running async operation against request drop or explicit cancellation
    tokio::select! {
        biased;
        _ = request_token.cancelled() => {
            Err(StatusCode::REQUEST_TIMEOUT)
        }
        res = async move {
            let mut tx = pool.begin().await.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
            
            // Select internal steps against child token
            tokio::select! {
                biased;
                _ = task_token.cancelled() => Err(StatusCode::REQUEST_TIMEOUT),
                compute_res = heavy_vector_calculation(&payload) => {
                    sqlx::query("INSERT INTO orders (id, data) VALUES ($1, $2)")
                        .bind(&payload.id)
                        .bind(&payload.data)
                        .execute(&mut *tx)
                        .await
                        .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
                    
                    tx.commit().await.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
                    Ok(StatusCode::CREATED)
                }
            }
        } => res,
    }
}
```

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 Request Tree Cascading Abort Invariant

Axum 0.8 Tokio CancellationToken Request Tree Cascading Abort Invariant defines an industrial-grade behavioral standard for backend engineering. Enforces deterministic cancellation trees in Axum 0.8 applications by binding Tokio CancellationToken hierarchies to incoming HTTP request lifecycles. Prevents orphaned CPU-intensive operations, thread starvation, and dangling uncommitted database transactions when clients disconnect prematurely. 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: Detached Workflows and Zombie Database Transactions on Client TCP Drop 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 DriftDetached Workflows and Zombie Database Transactions on Client TCP DropCritical
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 create a child `tokio_util

Engineers MUST ALWAYS create a child `tokio_util::sync::CancellationToken` scoped to each incoming HTTP request context.

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 use unconstrained `tokio

Engineers MUST NOT use unconstrained `tokio::spawn` within handlers without wiring a child `CancellationToken` or managing a `JoinHandle` abort guard.

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 race long-running downstream futures (DB queries, RPC calls, heavy compute) against `token.cancelled()` using `tokio

Handlers MUST race long-running downstream futures (DB queries, RPC calls, heavy compute) against `token.cancelled()` using `tokio::select!` or task tracker primitives.

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

Database transactions MUST rely on standard RAII drop semantics for automatic rollback upon cancellation, ensuring explicit commits only execute if the request token remains uncancelled.

Database transactions MUST rely on standard RAII drop semantics for automatic rollback upon cancellation, ensuring explicit commits only execute if the request token remains uncancelled.

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 propagate child cancellation tokens into all internal domain services, worker queues, and client wrappers rather than firing detached background futures.

Services MUST propagate child cancellation tokens into all internal domain services, worker queues, and client wrappers rather than firing detached background futures.

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 an Axum handler completes merely because execution started

Components NEVER assume an Axum handler completes merely because execution started; client TCP resets (`ECONNRESET`) must immediately abort all in-flight downstream futures.

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 Request Tree Cascading Abort Invariant critical for AI coding assistants?

Enforces deterministic cancellation trees in Axum 0.8 applications by binding Tokio CancellationToken hierarchies to incoming HTTP request lifecycles. Prevents orphaned CPU-intensive operations, thread starvation, and dangling uncommitted database transactions when clients disconnect prematurely. 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 (Detached Workflows and Zombie Database Transactions on Client TCP Drop) 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