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

Axum 0.8 Task-Scoped Cancellation Token Propagation & Connection Leak Prevention

Enforces deterministic cancellation hierarchies across Axum 0.8 request pipelines to prevent orphan async compute and database pool starvation upon client disconnect. Mandates wrapping spawned asynchronous child routines and heavy IO in scoped cancellation tokens tied to the request lifetime. Guarantees that dropping the top-level HTTP handler future cleanly aborts all downstream work and immediately returns pooled resources.

Prohibited Anti-Pattern: Spawning Detached Async Tasks and Unguarded Pool Checkouts Without Client Disconnect Propagation

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Axum 0.8 Task-Scoped Cancellation Token Propagation & Connection Leak Prevention - Enforces deterministic cancellation hierarchies across Axum 0.8 request pipelines to prevent orphan async compute and database pool starvation upon client disconnect. Mandates wrapping spawned asynchronous child routines and heavy IO in scoped cancellation tokens tied to the request lifetime. Guarantees that dropping the top-level HTTP handler future cleanly aborts all downstream work and immediately returns pooled resources.
globs: src/**/*.rs
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/axum-08-task-scoped-cancellation-token-propagation"
---

# Axum 0.8 Task-Scoped Cancellation Token Propagation & Connection Leak Prevention

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Spawning Detached Async Tasks and Unguarded Pool Checkouts Without Client Disconnect Propagation

## System Constraints
You are a Principal Rust Architect enforcing strict concurrency and cancellation discipline in Axum 0.8 web services. Mandate that every asynchronous subtask, long-running calculation, and external IO call initiated during an HTTP request is bound to a task-scoped cancellation hierarchy using `tokio_util::sync::CancellationToken` or explicit drop guards. Forbid unmonitored `tokio::spawn` invocations inside request handlers that survive socket disconnects, which cause pool starvation and zombie tasks.

## Strict Guidelines
- Engineers MUST ALWAYS construct a child `CancellationToken` derived from the request context or server shutdown hierarchy when executing multi-stage operations.
- Engineers MUST NOT invoke fire-and-forget `tokio::spawn` inside request handlers for tasks that logically depend on the client's continuous presence.
- Engineers MUST ALWAYS wrap blocking or multi-stage external resource calls in `tokio::select!` branches against the active `CancellationToken::cancelled()` future.
- Code SHOULD utilize RAII transaction and connection guards that trigger immediate transaction rollback or connection yield on dropped handler futures.
- Background worker operations requiring survival beyond request teardown MUST be explicitly dispatched through a persistent supervisor queue or `TaskTracker`, never via naked in-handler spawns.

## Bad vs Good Implementations
### Cancellation propagation in Axum 0.8 handler with Tokio task spawning

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: When an HTTP client aborts or disconnects, Axum drops the top-level handler future, but `tokio::spawn` detaches the child routine onto the runtime. The detached task continues running for 30 seconds, holding a pooled database connection, causing worker starvation and connection pool exhaustion under high cancellation rates.
```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 handle_process_job(
    State(pool): State<PgPool>,
    Json(req): Json<JobRequest>,
) -> Result<impl IntoResponse, StatusCode> {
    // ANTI-PATTERN: Spawning unmonitored task without cancellation propagation.
    // If the HTTP client aborts the connection, this task continues executing,
    // retaining a Postgres connection and wasting high-cost CPU cycles.
    tokio::spawn(async move {
        let mut conn = pool.acquire().await.unwrap();
        heavy_compute_and_persist(&mut conn, req.payload).await;
    });

    Ok(StatusCode::ACCEPTED)
}

async fn heavy_compute_and_persist(_conn: &mut sqlx::PgConnection, _payload: String) {
    tokio::time::sleep(tokio::time::Duration::from_secs(30)).await;
}
```

#### Production Standard (Correct)
> **Standard**: Using `DropGuard` from `tokio_util::sync::CancellationToken`, the child token is deterministically signaled the exact instant Axum drops the handler future due to client disconnection. The worker halts instantly via `tokio::select!`, preventing unnecessary compute and immediately releasing the pooled database connection.
```rust
use axum::{extract::State, http::StatusCode, response::IntoResponse, Json};
use sqlx::PgPool;
use serde::Deserialize;
use tokio_util::sync::{CancellationToken, DropGuard};

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

pub async fn handle_process_job(
    State(pool): State<PgPool>,
    Json(req): Json<JobRequest>,
) -> Result<impl IntoResponse, StatusCode> {
    let token = CancellationToken::new();
    let _drop_guard: DropGuard = token.clone().drop_guard();
    let child_token = token.child_token();

    // Invariant: The spawned task observes the cancellation token.
    // Dropping the handler drops `_drop_guard`, which cancels `token`.
    let join_handle = tokio::spawn(async move {
        tokio::select! {
            biased;
            _ = child_token.cancelled() => {
                tracing::warn!("Client aborted request; aborting background computation");
            }
            res = execute_scoped_work(&pool, req.payload, &child_token) => {
                if let Err(err) = res {
                    tracing::error!(error = ?err, "Worker execution failed");
                }
            }
        }
    });

    // Await completion or return early; if handler future drops, guard cancels worker
    let _ = join_handle.await.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
    Ok(StatusCode::OK)
}

async fn execute_scoped_work(
    pool: &PgPool,
    payload: String,
    token: &CancellationToken,
) -> Result<(), sqlx::Error> {
    tokio::select! {
        biased;
        _ = token.cancelled() => Ok(()),
        conn_res = pool.acquire() => {
            let mut conn = conn_res?;
            // Pass token down to prevent blocking nested queries
            tokio::time::sleep(tokio::time::Duration::from_secs(30)).await;
            tracing::info!(%payload, "Successfully processed job");
            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 Task-Scoped Cancellation Token Propagation & Connection Leak Prevention

Axum 0.8 Task-Scoped Cancellation Token Propagation & Connection Leak Prevention defines an industrial-grade behavioral standard for backend engineering. Enforces deterministic cancellation hierarchies across Axum 0.8 request pipelines to prevent orphan async compute and database pool starvation upon client disconnect. Mandates wrapping spawned asynchronous child routines and heavy IO in scoped cancellation tokens tied to the request lifetime. Guarantees that dropping the top-level HTTP handler future cleanly aborts all downstream work and immediately returns pooled resources. 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 Detached Async Tasks and Unguarded Pool Checkouts Without Client Disconnect Propagation 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 Detached Async Tasks and Unguarded Pool Checkouts Without Client Disconnect PropagationCritical
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 construct a child `CancellationToken` derived from the request context or server shutdown hierarchy when executing multi-stage operations.

Engineers MUST ALWAYS construct a child `CancellationToken` derived from the request context or server shutdown hierarchy when executing multi-stage operations.

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` inside request handlers for tasks that logically depend on the client's continuous presence.

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

Engineers MUST ALWAYS wrap blocking or multi-stage external resource calls in `tokio

Engineers MUST ALWAYS wrap blocking or multi-stage external resource calls in `tokio::select!` branches against the active `CancellationToken::cancelled()` future.

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 utilize RAII transaction and connection guards that trigger immediate transaction rollback or connection yield on dropped handler futures.

Code SHOULD utilize RAII transaction and connection guards that trigger immediate transaction rollback or connection yield on dropped handler futures.

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

Background worker operations requiring survival beyond request teardown MUST be explicitly dispatched through a persistent supervisor queue or `TaskTracker`, never via naked in-handler spawns.

Background worker operations requiring survival beyond request teardown MUST be explicitly dispatched through a persistent supervisor queue or `TaskTracker`, never via naked in-handler spawns.

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 Task-Scoped Cancellation Token Propagation & Connection Leak Prevention critical for AI coding assistants?

Enforces deterministic cancellation hierarchies across Axum 0.8 request pipelines to prevent orphan async compute and database pool starvation upon client disconnect. Mandates wrapping spawned asynchronous child routines and heavy IO in scoped cancellation tokens tied to the request lifetime. Guarantees that dropping the top-level HTTP handler future cleanly aborts all downstream work and immediately returns pooled resources. 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 Detached Async Tasks and Unguarded Pool Checkouts Without Client Disconnect Propagation) 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