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

Axum 0.8 Tokio Cooperative Cancellation Token Propagation Standard

Enforces deterministic cancellation cascades when client TCP connections terminate prematurely in Axum 0.8 services. Mandates integration of Tokio CancellationToken across asynchronous boundaries to prevent orphaned gRPC calls and lingering database operations. Guarantees immediate resource reclamation without thread exhaustion or lock contention.

Prohibited Anti-Pattern: Fire-and-Forget Spawning and Zombie Task Execution on Client TCP Disconnect

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Axum 0.8 Tokio Cooperative Cancellation Token Propagation Standard - Enforces deterministic cancellation cascades when client TCP connections terminate prematurely in Axum 0.8 services. Mandates integration of Tokio CancellationToken across asynchronous boundaries to prevent orphaned gRPC calls and lingering database operations. Guarantees immediate resource reclamation without thread exhaustion or lock contention.
globs: src/**/*.rs
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/axum-tokio-cooperative-cancellation-propagation"
---

# Axum 0.8 Tokio Cooperative Cancellation Token Propagation Standard

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Fire-and-Forget Spawning and Zombie Task Execution on Client TCP Disconnect

## System Constraints
You are a Principal Systems Architect enforcing Axum 0.8 and Tokio cooperative cancellation standards. In Axum 0.8, when a client drops the TCP connection, Hyper terminates the handler's top-level future. You must ensure that this cancellation deterministically propagates down through every downstream asynchronous child task, Tonic gRPC stream, and SQL transaction without spawning unmonitored tasks or leaking database connections.

## Strict Guidelines
- Engineers MUST ALWAYS tie detached background futures to a parent `tokio_util::sync::CancellationToken` or `tokio::task::JoinSet` rather than using unmonitored `tokio::spawn`.
- Engineers MUST NOT rely on implicit future drop semantics alone for multi-stage transactions where external resources lack automatic RAII-based abort mechanisms.
- Code SHOULD propagate cancellation tokens into downstream gRPC requests via Tonic cancellation channels or `tokio::select!` branches to immediately send `RST_STREAM` frames.
- Services MUST ensure that SQL transactions (such as `sqlx::Transaction`) are explicitly aborted or handled via drop guards before releasing connections back to the pool upon cancellation.
- Components NEVER ignore Tokio cooperative cancellation points during long-running compute loops; `tokio::task::yield_now()` or token checks MUST be placed across iterations.

## Bad vs Good Implementations
### Cancellation propagation across background gRPC client and SQL transaction

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Using `tokio::spawn` without a cancellation token decouples the workflow from the Axum request lifecycle. If the client drops TCP connectivity (e.g., closes browser or network timeout), the spawned task continues executing, calling external payment gateways and committing transactions for an abandoned request.
```rust
use axum::{extract::State, Json, response::IntoResponse};
use sqlx::PgPool;

pub async fn checkout_handler(
    State(pool): State<PgPool>,
    Json(payload): Json<CheckoutRequest>,
) -> impl IntoResponse {
    // ANTI-PATTERN: Decouples task from request lifecycle.
    // If client disconnects, this task runs to completion as a zombie process,
    // holding DB locks and consuming remote RPC quotas.
    tokio::spawn(async move {
        let mut tx = pool.begin().await.unwrap();
        let _ = execute_payment_rpc(&payload).await;
        let _ = insert_order(&mut *tx, &payload).await;
        tx.commit().await.unwrap();
    });

    axum::http::StatusCode::ACCEPTED
}
```

#### Production Standard (Correct)
> **Standard**: Attaching a `CancellationToken::drop_guard` guarantees that when Axum aborts the handler future due to client TCP disconnection, the guard triggers cancellation recursively across all child tokens. Downstream Tonic gRPC invocations and SQL transactions roll back deterministically without orphaned execution.
```rust
use axum::{extract::State, http::StatusCode, response::IntoResponse, Json};
use sqlx::PgPool;
use tokio_util::sync::CancellationToken;
use tokio_util::task::TaskTracker;

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

    let mut tx = pool.begin().await.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;

    // Cooperatively select between the token cancellation and downstream operations
    tokio::select! {
        _ = token.cancelled() => {
            // Axum client disconnected: immediate deterministic abort
            let _ = tx.rollback().await;
            Err(StatusCode::REQUEST_TIMEOUT)
        }
        res = execute_scoped_checkout(&mut tx, &payload, token.child_token()) => {
            // Disarm drop guard once successfully executed
            drop_guard.disarm();
            res.map_err(|_| StatusCode::BAD_GATEWAY)?;
            tx.commit().await.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
            Ok(StatusCode::OK)
        }
    }
}

async fn execute_scoped_checkout(
    tx: &mut sqlx::Transaction<'_, sqlx::Postgres>,
    payload: &CheckoutRequest,
    token: CancellationToken,
) -> Result<(), AppError> {
    tokio::select! {
        _ = token.cancelled() => Err(AppError::Cancelled),
        rpc_res = call_grpc_billing(payload) => {
            rpc_res?;
            insert_order(tx, payload).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 Cancellation Token Propagation Standard

Axum 0.8 Tokio Cooperative Cancellation Token Propagation Standard defines an industrial-grade behavioral standard for backend engineering. Enforces deterministic cancellation cascades when client TCP connections terminate prematurely in Axum 0.8 services. Mandates integration of Tokio CancellationToken across asynchronous boundaries to prevent orphaned gRPC calls and lingering database operations. Guarantees immediate resource reclamation without thread exhaustion or lock contention. 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: Fire-and-Forget Spawning and Zombie Task Execution on Client TCP 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 DriftFire-and-Forget Spawning and Zombie Task Execution on Client TCP 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 tie detached background futures to a parent `tokio_util

Engineers MUST ALWAYS tie detached background futures to a parent `tokio_util::sync::CancellationToken` or `tokio::task::JoinSet` rather than using unmonitored `tokio::spawn`.

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 rely on implicit future drop semantics alone for multi-stage transactions where external resources lack automatic RAII-based abort mechanisms.

Engineers MUST NOT rely on implicit future drop semantics alone for multi-stage transactions where external resources lack automatic RAII-based abort mechanisms.

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 SHOULD propagate cancellation tokens into downstream gRPC requests via Tonic cancellation channels or `tokio

Code SHOULD propagate cancellation tokens into downstream gRPC requests via Tonic cancellation channels or `tokio::select!` branches to immediately send `RST_STREAM` frames.

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 that SQL transactions (such as `sqlx

Services MUST ensure that SQL transactions (such as `sqlx::Transaction`) are explicitly aborted or handled via drop guards before releasing connections back to the pool upon cancellation.

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 ignore Tokio cooperative cancellation points during long-running compute loops

Components NEVER ignore Tokio cooperative cancellation points during long-running compute loops; `tokio::task::yield_now()` or token checks MUST be placed across iterations.

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 Cancellation Token Propagation Standard critical for AI coding assistants?

Enforces deterministic cancellation cascades when client TCP connections terminate prematurely in Axum 0.8 services. Mandates integration of Tokio CancellationToken across asynchronous boundaries to prevent orphaned gRPC calls and lingering database operations. Guarantees immediate resource reclamation without thread exhaustion or lock contention. 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 (Fire-and-Forget Spawning and Zombie Task Execution on Client TCP 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