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

Axum 0.8 Tokio Hierarchical CancellationToken Drain Guardrail

Enforces strict parent-child CancellationToken hierarchies across Axum 0.8 Tower middleware pipelines and streaming handlers. Prevents orphaned background tasks, zombie streaming connections (SSE/WebSockets), and unbounded graceful shutdown delays by binding request life-cycles to Tokio TaskTrackers and scoped child tokens.

Prohibited Anti-Pattern: Spawning Detached Tokio Tasks or Unbounded Stream Pollers Without Child Cancellation Tokens Tied to Server Shutdown Hooks

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Axum 0.8 Tokio Hierarchical CancellationToken Drain Guardrail - Enforces strict parent-child CancellationToken hierarchies across Axum 0.8 Tower middleware pipelines and streaming handlers. Prevents orphaned background tasks, zombie streaming connections (SSE/WebSockets), and unbounded graceful shutdown delays by binding request life-cycles to Tokio TaskTrackers and scoped child tokens.
globs: src/**/*.rs
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/axum-0-8-tokio-hierarchical-cancellation-token-drain-guardrail"
---

# Axum 0.8 Tokio Hierarchical CancellationToken Drain Guardrail

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Spawning Detached Tokio Tasks or Unbounded Stream Pollers Without Child Cancellation Tokens Tied to Server Shutdown Hooks

## System Constraints
You are a Principal Rust Concurrency Architect enforcing deterministic lifecycle management and graceful shutdown semantics in Axum 0.8 and Tokio runtimes. Mandate hierarchical CancellationToken propagation and Tokio TaskTracker tracking across all request lifecycles, middleware pipelines, and background asynchronous jobs.

## Strict Guidelines
- Engineers MUST ALWAYS create a root `tokio_util::sync::CancellationToken` at application bootstrap and derive scoped child tokens via `.child_token()` for sub-domains, background workers, and individual HTTP request lifecycles.
- Engineers MUST NOT call `tokio::spawn` within Axum route handlers or Tower middleware without registering the `JoinHandle` into a managed `tokio_util::task::TaskTracker` bound to the server drain sequence.
- Code SHOULD inject the request-scoped `CancellationToken` into request extensions via middleware, allowing streaming responses (SSE, WebSockets) and long-running DB queries to abort immediately upon client disconnect or server shutdown.
- Services MUST wire `axum::serve(listener, router).with_graceful_shutdown(...)` to trigger root token cancellation followed by `tracker.close()` and `tracker.wait().await` with a strict bounded fallback timeout.
- Components NEVER drop `CancellationToken` references or await streaming iterators without a `tokio::select!` branch watching `token.cancelled()`.

## Bad vs Good Implementations
### Graceful Shutdown with Hierarchical CancellationToken and TaskTracker Drain

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Detached `tokio::spawn` calls lack cancellation links to the server lifecycle. When the server process receives SIGTERM or SIGINT, active background tasks and infinite stream loops continue running until forced kill, corrupting state and leaving database connections open.
```rust
use axum::{routing::get, Router};
use tokio::net::TcpListener;

async fn sse_handler() -> axum::response::Response {
    // ANTI-PATTERN: Detached task ignores shutdown and leaks memory
    tokio::spawn(async move {
        loop {
            tokio::time::sleep(tokio::time::Duration::from_secs(1)).await;
            println!("processing heartbeat...");
        }
    });
    axum::response::Html("streaming").into_response()
}

#[tokio::main]
async fn main() {
    let app = Router::new().route("/stream", get(sse_handler));
    let listener = TcpListener::bind("0.0.0.0:3000").await.unwrap();
    // Incomplete shutdown: Drops immediately or leaks detached tasks
    axum::serve(listener, app).await.unwrap();
}
```

#### Production Standard (Correct)
> **Standard**: Uses a root `CancellationToken` propagating child tokens to tasks tracked via `tokio_util::task::TaskTracker`. When shutdown signals fire, the token initiates deterministic cancellation across all active pipelines, while `tracker.wait()` safely drains pending operations up to a bounded timeout.
```rust
use axum::{extract::Extension, response::IntoResponse, routing::get, Router};
use std::time::Duration;
use tokio::net::TcpListener;
use tokio_util::sync::CancellationToken;
use tokio_util::task::TaskTracker;

async fn sse_handler(
    Extension(parent_token): Extension<CancellationToken>,
    Extension(tracker): Extension<TaskTracker>,
) -> impl IntoResponse {
    let child_token = parent_token.child_token();
    let task_token = child_token.clone();
    
    tracker.spawn(async move {
        tokio::select! {
            _ = task_token.cancelled() => {
                // Deterministic cleanup upon client abort or shutdown drain
            }
            _ = async {
                loop {
                    tokio::time::sleep(Duration::from_secs(1)).await;
                    // Normal async work
                }
            } => {}
        }
    });

    axum::response::Html("streaming-registered")
}

#[tokio::main]
async fn main() {
    let root_token = CancellationToken::new();
    let tracker = TaskTracker::new();
    
    let app = Router::new()
        .route("/stream", get(sse_handler))
        .layer(Extension(root_token.clone()))
        .layer(Extension(tracker.clone()));
        
    let listener = TcpListener::bind("0.0.0.0:3000").await.unwrap();
    let shutdown_token = root_token.clone();
    
    axum::serve(listener, app)
        .with_graceful_shutdown(async move {
            tokio::signal::ctrl_c().await.ok();
            shutdown_token.cancel();
        })
        .await
        .unwrap();
        
    tracker.close();
    tokio::select! {
        _ = tracker.wait() => {},
        _ = tokio::time::sleep(Duration::from_secs(10)) => {
            eprintln!("Shutdown deadline exceeded; forcing exit");
        }
    }
}
```

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 Hierarchical CancellationToken Drain Guardrail

Axum 0.8 Tokio Hierarchical CancellationToken Drain Guardrail defines an industrial-grade behavioral standard for backend engineering. Enforces strict parent-child CancellationToken hierarchies across Axum 0.8 Tower middleware pipelines and streaming handlers. Prevents orphaned background tasks, zombie streaming connections (SSE/WebSockets), and unbounded graceful shutdown delays by binding request life-cycles to Tokio TaskTrackers and scoped child tokens. 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 Tokio Tasks or Unbounded Stream Pollers Without Child Cancellation Tokens Tied to Server Shutdown Hooks 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 Tokio Tasks or Unbounded Stream Pollers Without Child Cancellation Tokens Tied to Server Shutdown HooksCritical
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 create a root `tokio_util

Engineers MUST ALWAYS create a root `tokio_util::sync::CancellationToken` at application bootstrap and derive scoped child tokens via `.child_token()` for sub-domains, background workers, and individual HTTP request lifecycles.

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

Engineers MUST NOT call `tokio::spawn` within Axum route handlers or Tower middleware without registering the `JoinHandle` into a managed `tokio_util::task::TaskTracker` bound to the server drain sequence.

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 inject the request-scoped `CancellationToken` into request extensions via middleware, allowing streaming responses (SSE, WebSockets) and long-running DB queries to abort immediately upon client disconnect or server shutdown.

Code SHOULD inject the request-scoped `CancellationToken` into request extensions via middleware, allowing streaming responses (SSE, WebSockets) and long-running DB queries to abort immediately upon client disconnect or server shutdown.

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 wire `axum

Services MUST wire `axum::serve(listener, router).with_graceful_shutdown(...)` to trigger root token cancellation followed by `tracker.close()` and `tracker.wait().await` with a strict bounded fallback timeout.

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 drop `CancellationToken` references or await streaming iterators without a `tokio

Components NEVER drop `CancellationToken` references or await streaming iterators without a `tokio::select!` branch watching `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.
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 Hierarchical CancellationToken Drain Guardrail critical for AI coding assistants?

Enforces strict parent-child CancellationToken hierarchies across Axum 0.8 Tower middleware pipelines and streaming handlers. Prevents orphaned background tasks, zombie streaming connections (SSE/WebSockets), and unbounded graceful shutdown delays by binding request life-cycles to Tokio TaskTrackers and scoped child tokens. 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 Tokio Tasks or Unbounded Stream Pollers Without Child Cancellation Tokens Tied to Server Shutdown Hooks) 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