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

Axum 0.8 Tokio CancellationToken Distributed Lifecycle Scoping

Mandates explicit, hierarchical cancellation trees using Tokio CancellationToken across Axum 0.8 request pipelines. Enforces deterministic cancellation propagation through database transactions, external HTTP calls, and background workers upon client disconnection or SIGTERM pod termination.

Prohibited Anti-Pattern: Detached Spawning and Unscoped Async Pipelines Leaking DB Pool Connections on HTTP Aborts

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Axum 0.8 Tokio CancellationToken Distributed Lifecycle Scoping - Mandates explicit, hierarchical cancellation trees using Tokio CancellationToken across Axum 0.8 request pipelines. Enforces deterministic cancellation propagation through database transactions, external HTTP calls, and background workers upon client disconnection or SIGTERM pod termination.
globs: src/**/*.rs, crates/**/*.rs
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/axum-tokio-cancellation-token-lifecycle-scoping"
---

# Axum 0.8 Tokio CancellationToken Distributed Lifecycle Scoping

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Detached Spawning and Unscoped Async Pipelines Leaking DB Pool Connections on HTTP Aborts

## System Constraints
You are a Principal Systems Architect enforcing distributed lifecycle scoping in Axum 0.8 and Tokio. You mandate that all asynchronous request pipelines derive from hierarchical CancellationToken trees. Ensure no database query, outbound gRPC/HTTP request, or spawned task operates detached from client connection states or server shutdown boundaries.

## Strict Guidelines
- Engineers MUST ALWAYS propagate a child `CancellationToken` derived from both the server-wide shutdown signal and Axum's connection drop boundary into all business logic and data layers.
- Engineers MUST NOT invoke `tokio::spawn` without either passing a linked child `CancellationToken` or holding an explicit `JoinHandle` configured to abort on drop when the initiating request terminates.
- Services MUST pass the cancellation token directly to async I/O drivers (e.g., `sqlx`, `reqwest`, `tonic`) or race the operations using `tokio::select!` against `token.cancelled()`.
- Code SHOULD leverage RAII drop guards (`tokio_util::sync::DropGuard` or custom structs) to deterministically release non-memory resources, roll back open transactions, and decrement metrics when an operation cancels mid-execution.
- Components NEVER execute unbounded background work inside HTTP handler boundaries; asynchronous side effects requiring decoupled lifetimes must be explicitly dispatched via durable queues or supervised task pools with independent lifecycle contexts.

## Bad vs Good Implementations
### Propagating Hierarchical Cancellation in Axum 0.8 Request Handlers

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Spawns an unmonitored task with no cancellation token linkage. Client aborts or pod drains will not terminate the database workload, causing pool exhaustion and zombie writes.
```rust
use axum::{extract::State, Json};
use sqlx::PgPool;

pub async fn checkout_handler(
    State(pool): State<PgPool>,
    Json(payload): Json<OrderPayload>,
) -> Result<Json<OrderResponse>, AppError> {
    // ANTI-PATTERN: Fire-and-forget detached spawn.
    // If client disconnects or pod drains, the task keeps running,
    // pinning DB connections, orphaning transactions, and consuming compute.
    tokio::spawn(async move {
        process_order_detached(&pool, payload).await;
    });

    Ok(Json(OrderResponse::Accepted))
}
```

#### Production Standard (Correct)
> **Standard**: Creates a child CancellationToken bounded to the root shutdown and connection lifecycle. The database transaction is explicitly rolled back and aborted if cancellation triggers, preventing pool depletion.
```rust
use axum::{extract::{Extension, State}, Json, http::StatusCode};
use sqlx::PgPool;
use tokio_util::sync::CancellationToken;

pub async fn checkout_handler(
    State(pool): State<PgPool>,
    Extension(root_token): Extension<CancellationToken>,
    Json(payload): Json<OrderPayload>,
) -> Result<Json<OrderResponse>, AppError> {
    // INVARIANT: Create a scoped child token tied to the request lifetime
    let request_token = root_token.child_token();
    let token_clone = request_token.clone();

    // Guard downstream operations with explicit cancellation racing
    tokio::select! {
        _ = token_clone.cancelled() => {
            Err(AppError::ClientClosedRequest)
        }
        res = process_order_scoped(&pool, payload, token_clone) => {
            res.map(Json)
        }
    }
}

async fn process_order_scoped(
    pool: &PgPool,
    payload: OrderPayload,
    token: CancellationToken,
) -> Result<OrderResponse, AppError> {
    let mut tx = pool.begin().await?;
    
    // Sub-operations poll cancellation before expensive I/O
    if token.is_cancelled() {
        return Err(AppError::Cancelled);
    }
    
    // Explicit select protects individual DB statements
    tokio::select! {
        _ = token.cancelled() => {
            let _ = tx.rollback().await;
            Err(AppError::Cancelled)
        }
        result = sqlx::query!("INSERT INTO orders DEFAULT VALUES").execute(&mut *tx) => {
            result?;
            tx.commit().await?;
            Ok(OrderResponse::Accepted)
        }
    }
}
```

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 Distributed Lifecycle Scoping

Axum 0.8 Tokio CancellationToken Distributed Lifecycle Scoping defines an industrial-grade behavioral standard for backend engineering. Mandates explicit, hierarchical cancellation trees using Tokio CancellationToken across Axum 0.8 request pipelines. Enforces deterministic cancellation propagation through database transactions, external HTTP calls, and background workers upon client disconnection or SIGTERM pod termination. 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 Spawning and Unscoped Async Pipelines Leaking DB Pool Connections on HTTP Aborts 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 Spawning and Unscoped Async Pipelines Leaking DB Pool Connections on HTTP AbortsCritical
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` derived from both the server-wide shutdown signal and Axum's connection drop boundary into all business logic and data layers.

Engineers MUST ALWAYS propagate a child `CancellationToken` derived from both the server-wide shutdown signal and Axum's connection drop boundary into all business logic and data layers.

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

Engineers MUST NOT invoke `tokio::spawn` without either passing a linked child `CancellationToken` or holding an explicit `JoinHandle` configured to abort on drop when the initiating request terminates.

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

Services MUST pass the cancellation token directly to async I/O drivers (e.g., `sqlx`, `reqwest`, `tonic`) or race the operations using `tokio

Services MUST pass the cancellation token directly to async I/O drivers (e.g., `sqlx`, `reqwest`, `tonic`) or race the operations using `tokio::select!` against `token.cancelled()`.

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

Code SHOULD leverage RAII drop guards (`tokio_util

Code SHOULD leverage RAII drop guards (`tokio_util::sync::DropGuard` or custom structs) to deterministically release non-memory resources, roll back open transactions, and decrement metrics when an operation cancels mid-execution.

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 execute unbounded background work inside HTTP handler boundaries

Components NEVER execute unbounded background work inside HTTP handler boundaries; asynchronous side effects requiring decoupled lifetimes must be explicitly dispatched via durable queues or supervised task pools with independent lifecycle contexts.

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 Distributed Lifecycle Scoping critical for AI coding assistants?

Mandates explicit, hierarchical cancellation trees using Tokio CancellationToken across Axum 0.8 request pipelines. Enforces deterministic cancellation propagation through database transactions, external HTTP calls, and background workers upon client disconnection or SIGTERM pod termination. 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 Spawning and Unscoped Async Pipelines Leaking DB Pool Connections on HTTP Aborts) 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