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

Axum 0.8 Structured Task-Cancellation Barrier via CancellationToken Hierarchies

In Axum 0.8, HTTP/3 QUIC stream resets and client connection drops abruptly terminate handler futures at yield points. Without an explicit structured task-cancellation barrier using tokio_util CancellationToken hierarchies and RAII rollback guards, spawned background tasks leak compute and orphaned database transactions persist indefinitely.

Prohibited Anti-Pattern: Spawning Unlinked tokio::spawn Tasks and Unguarded Long-Running IO in Dropped Handlers

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Axum 0.8 Structured Task-Cancellation Barrier via CancellationToken Hierarchies - In Axum 0.8, HTTP/3 QUIC stream resets and client connection drops abruptly terminate handler futures at yield points. Without an explicit structured task-cancellation barrier using tokio_util CancellationToken hierarchies and RAII rollback guards, spawned background tasks leak compute and orphaned database transactions persist indefinitely.
globs: src/**/*.rs, crates/**/*.rs
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/axum-structured-task-cancellation-barrier"
---

# Axum 0.8 Structured Task-Cancellation Barrier via CancellationToken Hierarchies

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Spawning Unlinked tokio::spawn Tasks and Unguarded Long-Running IO in Dropped Handlers

## System Constraints
You are a Principal Rust Architect enforcing structured concurrency and fail-fast cancellation barriers in Axum 0.8 services. You must prevent orphaned database transactions, lingering threadpool allocations, and resource leaks caused by client disconnects and HTTP/3 QUIC stream resets. Enforce tokio_util::sync::CancellationToken propagation, RAII transaction rollback semantics, and strict task-tracker hierarchies.

## Strict Guidelines
- Engineers MUST ALWAYS propagate a child `CancellationToken` or wrap cancellable handler logic inside `tokio::select!` biased toward client cancellation signals.
- Engineers MUST NOT invoke naked `tokio::spawn` inside request handlers for work that depends on or outlives the request context without binding it to a `tokio_util::task::TaskTracker` or child token.
- Database transactions MUST rely on transactional RAII drop semantics (`sqlx::Transaction` auto-rollback on future drop) and MUST NOT perform uncommitted multi-stage IO operations in disconnected worker threads.
- Services MUST extract or generate a cancellation token per request through middleware or custom extractors to track client disconnection explicitly.
- Handlers NEVER execute CPU-intensive blocking workloads via `tokio::task::spawn_blocking` without polling or passing an atomic cancellation flag or token to allow early termination.

## Bad vs Good Implementations
### Unbounded Background Task Spawning with Orphaned DB Transaction

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: When an HTTP/3 client cancels a request or drops connection, Axum drops the handler future. Spawning an unlinked `tokio::spawn` completely detaches execution, causing orphaned RPC calls and unnecessary database writes that ignore the client's cancellation.
```rust
use axum::{extract::State, response::IntoResponse, Json};
use sqlx::PgPool;

pub async fn process_order(
    State(pool): State<PgPool>,
    Json(payload): Json<OrderPayload>,
) -> impl IntoResponse {
    // ANTI-PATTERN: Spawning unlinked background tasks ignores client disconnects.
    // If the HTTP/3 stream cancels, this task continues processing and writing
    // to the database, burning compute and creating ghost orders.
    tokio::spawn(async move {
        let mut tx = pool.begin().await.unwrap();
        heavy_billing_rpc(&payload).await.unwrap();
        sqlx::query!("INSERT INTO orders (id) VALUES ($1)", payload.id)
            .execute(&mut *tx)
            .await
            .unwrap();
        tx.commit().await.unwrap();
    });

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

#### Production Standard (Correct)
> **Standard**: Uses `CancellationToken` hierarchies and `TaskTracker` to guarantee that client disconnects, timeouts, and cancellations interrupt upstream RPCs immediately, allowing the database transaction to drop safely and roll back.
```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 process_order(
    State(pool): State<PgPool>,
    State(tracker): State<TaskTracker>,
    Json(payload): Json<OrderPayload>,
) -> Result<impl IntoResponse, StatusCode> {
    let token = CancellationToken::new();
    let child_token = token.child_token();

    // PRODUCTION FIX: Bind execution directly to cancellation token and tracker.
    // If the client disconnects before completion, select! cancels the branch,
    // and the sqlx::Transaction RAII guard triggers an immediate ROLLBACK on drop.
    tokio::select! {
        biased;
        _ = token.cancelled() => {
            Err(StatusCode::REQUEST_TIMEOUT)
        }
        res = tracker.track_future(async move {
            let mut tx = pool.begin().await.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
            
            // Guard against cancellation during long RPC
            tokio::select! {
                biased;
                _ = child_token.cancelled() => return Err(StatusCode::REQUEST_TIMEOUT),
                rpc_res = heavy_billing_rpc(&payload) => {
                    rpc_res.map_err(|_| StatusCode::BAD_GATEWAY)?;
                }
            }
            
            sqlx::query!("INSERT INTO orders (id) VALUES ($1)", payload.id)
                .execute(&mut *tx)
                .await
                .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
                
            tx.commit().await.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
            Ok(StatusCode::OK)
        }) => res,
    }
}
```

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Axum 0.8 Structured Task-Cancellation Barrier via CancellationToken Hierarchies

Axum 0.8 Structured Task-Cancellation Barrier via CancellationToken Hierarchies defines an industrial-grade behavioral standard for backend engineering. In Axum 0.8, HTTP/3 QUIC stream resets and client connection drops abruptly terminate handler futures at yield points. Without an explicit structured task-cancellation barrier using tokio_util CancellationToken hierarchies and RAII rollback guards, spawned background tasks leak compute and orphaned database transactions persist indefinitely. 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: Spawning Unlinked tokio::spawn Tasks and Unguarded Long-Running IO in Dropped Handlers 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 DriftSpawning Unlinked tokio::spawn Tasks and Unguarded Long-Running IO in Dropped HandlersCritical
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 child `CancellationToken` or wrap cancellable handler logic inside `tokio

Engineers MUST ALWAYS propagate a child `CancellationToken` or wrap cancellable handler logic inside `tokio::select!` biased toward client cancellation signals.

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 naked `tokio

Engineers MUST NOT invoke naked `tokio::spawn` inside request handlers for work that depends on or outlives the request context without binding it to a `tokio_util::task::TaskTracker` or child 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

Database transactions MUST rely on transactional RAII drop semantics (`sqlx

Database transactions MUST rely on transactional RAII drop semantics (`sqlx::Transaction` auto-rollback on future drop) and MUST NOT perform uncommitted multi-stage IO operations in disconnected worker threads.

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 extract or generate a cancellation token per request through middleware or custom extractors to track client disconnection explicitly.

Services MUST extract or generate a cancellation token per request through middleware or custom extractors to track client disconnection explicitly.

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

Handlers NEVER execute CPU-intensive blocking workloads via `tokio

Handlers NEVER execute CPU-intensive blocking workloads via `tokio::task::spawn_blocking` without polling or passing an atomic cancellation flag or token to allow early termination.

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 Structured Task-Cancellation Barrier via CancellationToken Hierarchies critical for AI coding assistants?

In Axum 0.8, HTTP/3 QUIC stream resets and client connection drops abruptly terminate handler futures at yield points. Without an explicit structured task-cancellation barrier using tokio_util CancellationToken hierarchies and RAII rollback guards, spawned background tasks leak compute and orphaned database transactions persist indefinitely. 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 (Spawning Unlinked tokio::spawn Tasks and Unguarded Long-Running IO in Dropped Handlers) 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