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

Axum 0.8 Tokio Cooperative Task Cancellation Invariant

Enforces deterministic cancellation token propagation and drop safety across Axum 0.8 handler trees and Tower middleware layers. Prevents orphaned database transactions, hung connection pools, and leaked socket handles caused by unmonitored client TCP disconnects and detached asynchronous task spawns.

Prohibited Anti-Pattern: Detached Task Spawning and Cancellation-Unsafe Async Handlers Leaking DB Pool Resources on Client Disconnect

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Axum 0.8 Tokio Cooperative Task Cancellation Invariant - Enforces deterministic cancellation token propagation and drop safety across Axum 0.8 handler trees and Tower middleware layers. Prevents orphaned database transactions, hung connection pools, and leaked socket handles caused by unmonitored client TCP disconnects and detached asynchronous task spawns.
globs: src/**/*.rs, crates/**/*.rs
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/axum-tokio-cooperative-cancellation-invariant"
---

# Axum 0.8 Tokio Cooperative Task Cancellation Invariant

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Detached Task Spawning and Cancellation-Unsafe Async Handlers Leaking DB Pool Resources on Client Disconnect

## System Constraints
You are a Principal Rust Architect enforcing zero-leak cooperative task cancellation across Axum 0.8 services and Tokio runtimes. You must prohibit unmonitored `tokio::spawn` calls, enforce the use of `tokio_util::sync::CancellationToken` and `TaskTracker`, verify cancellation-safety of all async operations crossing transactional boundaries, and ensure proper RAII rollbacks when client connections are aborted.

## Strict Guidelines
- Engineers MUST ALWAYS propagate a derived `CancellationToken` through Axum 0.8 request extensions or explicit parameters to child task trees.
- Engineers MUST NOT invoke raw, unmonitored `tokio::spawn` inside Axum handlers for non-detached side-effects; handlers MUST bind background work to a `tokio_util::task::TaskTracker` paired with a cooperative cancellation token.
- Code MUST ensure all async operations wrapping multi-step database transactions are cancellation-safe; transactions MUST be explicitly rolled back or committed via RAII guard structures when an enclosing future is dropped.
- Services MUST monitor client connection termination by listening to incoming connection cancellation or utilizing `axum::serve::WithGracefulShutdown` coordinated with application-wide tokens.
- Components NEVER use unbounded or un-cancellable `tokio::select!` branches where dropping a branch midway corrupts state or starves connection pool permits.

## Bad vs Good Implementations
### Unbounded Detached Spawn vs. Cooperative CancellationToken with TaskTracker

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Spawning detached futures with `tokio::spawn` inside request handlers loses all association with the initiating request lifecycle and graceful shutdown signals. If the server shuts down or the client cancels the operation, the detached task continues, holding scarce database pool connections open and causing resource exhaustion or inconsistent state mutations.
```rust
use axum::{extract::State, http::StatusCode, response::IntoResponse, Json};
use sqlx::PgPool;
use serde::Deserialize;

#[derive(Deserialize)]
pub struct JobRequest { pub payload: String }

pub async fn handler(
    State(pool): State<PgPool>,
    Json(req): Json<JobRequest>,
) -> impl IntoResponse {
    // ANTI-PATTERN: Raw tokio::spawn without cancellation token or tracker.
    // If the HTTP client disconnects or the server shuts down, this task continues indefinitely.
    // If it fails mid-execution or hangs on an external lock, the DB connection permit leaks.
    tokio::spawn(async move {
        let mut tx = pool.begin().await.unwrap();
        sqlx::query("INSERT INTO audit_logs (data) VALUES ($1)")
            .bind(&req.payload)
            .execute(&mut *tx)
            .await
            .unwrap();
        tokio::time::sleep(std::time::Duration::from_secs(30)).await;
        tx.commit().await.unwrap();
    });

    StatusCode::ACCEPTED
}
```

#### Production Standard (Correct)
> **Standard**: The fix uses `tokio_util::task::TaskTracker` to ensure background work is monitored and accounted for during server drain/shutdown, and propagates a child `CancellationToken` down the execution tree. In case of cancellation, the branch drops the `sqlx::Transaction` handle cleanly, triggering a deterministic rollback and returning pool connections immediately.
```rust
use axum::{extract::{Extension, State}, http::StatusCode, response::IntoResponse, Json};
use sqlx::PgPool;
use serde::Deserialize;
use tokio_util::sync::CancellationToken;
use tokio_util::task::TaskTracker;
use std::time::Duration;

#[derive(Deserialize)]
pub struct JobRequest { pub payload: String }

pub async fn handler(
    State(pool): State<PgPool>,
    Extension(tracker): Extension<TaskTracker>,
    Extension(parent_token): Extension<CancellationToken>,
    Json(req): Json<JobRequest>,
) -> Result<impl IntoResponse, StatusCode> {
    let child_token = parent_token.child_token();

    // PRODUCTION FIX: Track the spawned task and wire cooperative cancellation
    tracker.spawn(async move {
        tokio::select! {
            _ = child_token.cancelled() => {
                tracing::warn!("Task cancelled cooperatively; aborting execution without orphan lock");
            }
            res = execute_transaction(pool, req.payload, child_token.clone()) => {
                if let Err(err) = res {
                    tracing::error!(error = %err, "Transactional worker execution failed");
                }
            }
        }
    });

    Ok(StatusCode::ACCEPTED)
}

async fn execute_transaction(
    pool: PgPool,
    payload: String,
    token: CancellationToken,
) -> Result<(), sqlx::Error> {
    let mut tx = pool.begin().await?;
    
    sqlx::query("INSERT INTO audit_logs (data) VALUES ($1)")
        .bind(&payload)
        .execute(&mut *tx)
        .await?;

    tokio::select! {
        _ = token.cancelled() => {
            // Drops tx, invoking automatic rollback
            return Ok(());
        }
        _ = tokio::time::sleep(Duration::from_secs(5)) => {}
    }

    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 Cooperative Task Cancellation Invariant

Axum 0.8 Tokio Cooperative Task Cancellation Invariant defines an industrial-grade behavioral standard for backend engineering. Enforces deterministic cancellation token propagation and drop safety across Axum 0.8 handler trees and Tower middleware layers. Prevents orphaned database transactions, hung connection pools, and leaked socket handles caused by unmonitored client TCP disconnects and detached asynchronous task spawns. 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 Task Spawning and Cancellation-Unsafe Async Handlers Leaking DB Pool Resources on 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 DriftDetached Task Spawning and Cancellation-Unsafe Async Handlers Leaking DB Pool Resources on 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 propagate a derived `CancellationToken` through Axum 0.8 request extensions or explicit parameters to child task trees.

Engineers MUST ALWAYS propagate a derived `CancellationToken` through Axum 0.8 request extensions or explicit parameters to child task trees.

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 invoke raw, unmonitored `tokio

Engineers MUST NOT invoke raw, unmonitored `tokio::spawn` inside Axum handlers for non-detached side-effects; handlers MUST bind background work to a `tokio_util::task::TaskTracker` paired with a cooperative cancellation token.

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 all async operations wrapping multi-step database transactions are cancellation-safe

Code MUST ensure all async operations wrapping multi-step database transactions are cancellation-safe; transactions MUST be explicitly rolled back or committed via RAII guard structures when an enclosing future is dropped.

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 monitor client connection termination by listening to incoming connection cancellation or utilizing `axum

Services MUST monitor client connection termination by listening to incoming connection cancellation or utilizing `axum::serve::WithGracefulShutdown` coordinated with application-wide 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.
5

Components NEVER use unbounded or un-cancellable `tokio

Components NEVER use unbounded or un-cancellable `tokio::select!` branches where dropping a branch midway corrupts state or starves connection pool permits.

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 Cooperative Task Cancellation Invariant critical for AI coding assistants?

Enforces deterministic cancellation token propagation and drop safety across Axum 0.8 handler trees and Tower middleware layers. Prevents orphaned database transactions, hung connection pools, and leaked socket handles caused by unmonitored client TCP disconnects and detached asynchronous task spawns. 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 Task Spawning and Cancellation-Unsafe Async Handlers Leaking DB Pool Resources on 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