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

Axum 0.8 Tokio Cooperative Task Budgeting & Deterministic Cancellation

Enforces deterministic cancellation and resource cleanup across Axum 0.8 and Tower middleware chains during abrupt client disconnects under heavy load. Mandates cooperative task budgeting, cancellation-safe transactional state machines, and hierarchical token propagation to prevent resource leaks, zombie background tasks, and connection pool exhaustion.

Prohibited Anti-Pattern: Unattached Background Spawning and Cancellation-Unsafe Async State Transitions Leading to Connection Leaks and Zombie Work

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Axum 0.8 Tokio Cooperative Task Budgeting & Deterministic Cancellation - Enforces deterministic cancellation and resource cleanup across Axum 0.8 and Tower middleware chains during abrupt client disconnects under heavy load. Mandates cooperative task budgeting, cancellation-safe transactional state machines, and hierarchical token propagation to prevent resource leaks, zombie background tasks, and connection pool exhaustion.
globs: src/**/*.rs, crates/**/*.rs
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/axum-08-tokio-cooperative-cancellation-standard"
---

# Axum 0.8 Tokio Cooperative Task Budgeting & Deterministic Cancellation

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Unattached Background Spawning and Cancellation-Unsafe Async State Transitions Leading to Connection Leaks and Zombie Work

## System Constraints
You are a Principal Rust Systems Architect specializing in high-throughput network services with Axum 0.8 and Tokio. Your responsibility is to strictly enforce cooperative task budgeting, deterministic cancellation semantics, and robust resource cleanup across Tower middleware chains and Axum request pipelines. When clients disconnect prematurely, handlers must terminate synchronously or orchestrate safe rollback without leaving orphaned async tasks, leaked database handles, or corrupted shared memory.

## Strict Guidelines
- Engineers MUST ALWAYS bind detached async background work to a parent `tokio_util::sync::CancellationToken` or handle lifecycle termination via `tokio::task::JoinHandle` abort handles.
- Engineers MUST NOT invoke fire-and-forget `tokio::spawn` within Axum route handlers for state-mutating operations without explicit rollback guards or completion guarantees.
- Handlers executing compute-intensive or unbounded iteration MUST yield cooperatively via `tokio::task::yield_now().await` or `tokio::task::consume_budget().await` to maintain event-loop responsiveness.
- Services MUST ensure all multi-step transactional operations (e.g., SQL transactions, distributed locks) utilize RAII rollback guards that execute clean teardown if a client disconnect drops the future at an `.await` boundary.
- Middleware and streaming endpoints MUST verify body consumption and channel write outcomes to promptly detect client disconnects (`io::ErrorKind::BrokenPipe` / `ConnectionReset`) and halt downstream processing immediately.
- Handlers MUST NEVER use cancellation-unsafe primitives inside `tokio::select!` branches where dropping a branch future causes state desynchronization or unreturned pool connections.

## Bad vs Good Implementations
### Cancellation Safety and Background Work Binding in Axum Handlers

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: If the client disconnects while awaiting the database or intermediate async calls, the future is abruptly dropped. Without structured cancellation and explicit budget yielding, spawned background tasks run unconstrained without a cancellation token, resulting in phantom execution, pool contention, and memory pressure.
```rust
use axum::{extract::State, http::StatusCode, response::IntoResponse, Json};
use serde::Deserialize;
use std::sync::Arc;

#[derive(Deserialize)]
pub struct OrderRequest { pub user_id: u64, pub amount: u64 }
pub struct AppState { pub db: sqlx::PgPool }

pub async fn place_order(
    State(state): State<Arc<AppState>>,
    Json(payload): Json<OrderRequest>,
) -> Result<impl IntoResponse, StatusCode> {
    // ANTI-PATTERN: Client disconnect drops handler future before commit,
    // or spawns unbounded background task that outlives context without cancellation coordination.
    let mut tx = state.db.begin().await.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
    
    sqlx::query!("UPDATE accounts SET balance = balance - $1 WHERE id = $2", payload.amount as i64, payload.user_id as i64)
        .execute(&mut *tx)
        .await
        .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;

    // Fire-and-forget task continues running even if client severed connection;
    // leaks resources under heavy load and cannot be throttled or tracked.
    tokio::spawn(async move {
        // Heavy external reporting / audit logging
        std::thread::sleep(std::time::Duration::from_millis(500));
    });

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

#### Production Standard (Correct)
> **Standard**: Leverages transactional RAII cleanup to guarantee that connection handles roll back if the client abruptly drops the future. It uses `tokio::task::consume_budget()` to cooperatively yield scheduler control and ties concurrent background tasks to a hierarchical `CancellationToken`.
```rust
use axum::{extract::State, http::StatusCode, response::IntoResponse, Json};
use serde::Deserialize;
use std::sync::Arc;
use tokio_util::sync::CancellationToken;

#[derive(Deserialize)]
pub struct OrderRequest { pub user_id: u64, pub amount: u64 }

pub struct AppState {
    pub db: sqlx::PgPool,
    pub cancel_token: CancellationToken,
}

pub async fn place_order(
    State(state): State<Arc<AppState>>,
    Json(payload): Json<OrderRequest>,
) -> Result<impl IntoResponse, StatusCode> {
    let child_token = state.cancel_token.child_token();
    
    // RAII Transaction: sqlx::Transaction automatically triggers ROLLBACK on drop
    // if dropped prematurely due to client cancellation.
    let mut tx = state.db.begin().await.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;

    sqlx::query!(
        "UPDATE accounts SET balance = balance - $1 WHERE id = $2",
        payload.amount as i64,
        payload.user_id as i64
    )
    .execute(&mut *tx)
    .await
    .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;

    // Enforce cooperative budgeting before final non-idempotent commit
    tokio::task::consume_budget().await;

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

    // Structured asynchronous job propagation respecting server shutdown and request boundaries
    let audit_token = child_token.clone();
    tokio::spawn(async move {
        tokio::select! {
            _ = audit_token.cancelled() => {
                tracing::warn!("Audit logging aborted due to cancellation signal");
            }
            _ = perform_audit_log(payload.user_id, payload.amount) => {
                tracing::info!("Audit log committed successfully");
            }
        }
    });

    Ok(StatusCode::CREATED)
}

async fn perform_audit_log(_user_id: u64, _amount: u64) {
    tokio::task::yield_now().await;
}
```

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 Budgeting & Deterministic Cancellation

Axum 0.8 Tokio Cooperative Task Budgeting & Deterministic Cancellation defines an industrial-grade behavioral standard for backend engineering. Enforces deterministic cancellation and resource cleanup across Axum 0.8 and Tower middleware chains during abrupt client disconnects under heavy load. Mandates cooperative task budgeting, cancellation-safe transactional state machines, and hierarchical token propagation to prevent resource leaks, zombie background tasks, and connection pool 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: Unattached Background Spawning and Cancellation-Unsafe Async State Transitions Leading to Connection Leaks and Zombie Work 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 DriftUnattached Background Spawning and Cancellation-Unsafe Async State Transitions Leading to Connection Leaks and Zombie WorkCritical
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 detached async background work to a parent `tokio_util

Engineers MUST ALWAYS bind detached async background work to a parent `tokio_util::sync::CancellationToken` or handle lifecycle termination via `tokio::task::JoinHandle` abort handles.

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 fire-and-forget `tokio

Engineers MUST NOT invoke fire-and-forget `tokio::spawn` within Axum route handlers for state-mutating operations without explicit rollback guards or completion 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 executing compute-intensive or unbounded iteration MUST yield cooperatively via `tokio

Handlers executing compute-intensive or unbounded iteration MUST yield cooperatively via `tokio::task::yield_now().await` or `tokio::task::consume_budget().await` to maintain event-loop responsiveness.

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 all multi-step transactional operations (e.g., SQL transactions, distributed locks) utilize RAII rollback guards that execute clean teardown if a client disconnect drops the future at an `.await` boundary.

Services MUST ensure all multi-step transactional operations (e.g., SQL transactions, distributed locks) utilize RAII rollback guards that execute clean teardown if a client disconnect drops the future at an `.await` boundary.

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

Middleware and streaming endpoints MUST verify body consumption and channel write outcomes to promptly detect client disconnects (`io

Middleware and streaming endpoints MUST verify body consumption and channel write outcomes to promptly detect client disconnects (`io::ErrorKind::BrokenPipe` / `ConnectionReset`) and halt downstream processing 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

Handlers MUST NEVER use cancellation-unsafe primitives inside `tokio

Handlers MUST NEVER use cancellation-unsafe primitives inside `tokio::select!` branches where dropping a branch future causes state desynchronization or unreturned pool connections.

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 Budgeting & Deterministic Cancellation critical for AI coding assistants?

Enforces deterministic cancellation and resource cleanup across Axum 0.8 and Tower middleware chains during abrupt client disconnects under heavy load. Mandates cooperative task budgeting, cancellation-safe transactional state machines, and hierarchical token propagation to prevent resource leaks, zombie background tasks, and connection pool 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 (Unattached Background Spawning and Cancellation-Unsafe Async State Transitions Leading to Connection Leaks and Zombie Work) 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