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

Axum 0.8 In-Flight Cancellation Token Propagation Guardrail

Mandates deterministic propagation of tokio_util::sync::CancellationToken and TaskTracker through Axum 0.8 middleware layers and handlers. Prevents orphaned background tasks, exhausted database connection pools, and leaked socket handles during Kubernetes zero-downtime rolling deploys and unexpected client cancellations.

Prohibited Anti-Pattern: Spawning detached tokio tasks and ignoring shutdown signals inside Axum handlers, producing unmanaged zombie workers during rolling deployments.

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Axum 0.8 In-Flight Cancellation Token Propagation Guardrail - Mandates deterministic propagation of tokio_util::sync::CancellationToken and TaskTracker through Axum 0.8 middleware layers and handlers. Prevents orphaned background tasks, exhausted database connection pools, and leaked socket handles during Kubernetes zero-downtime rolling deploys and unexpected client cancellations.
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-propagation"
---

# Axum 0.8 In-Flight Cancellation Token Propagation Guardrail

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Spawning detached tokio tasks and ignoring shutdown signals inside Axum handlers, producing unmanaged zombie workers during rolling deployments.

## System Constraints
You are a Principal Software Architect enforcing production-grade resilience in Axum 0.8 and Tokio services. You must enforce explicit cancellation tree architectures. Never permit naked `tokio::spawn` calls without child cancellation tokens and task tracking. Guarantee all handlers and background tasks listen to parent cancellation signals, safely release resources, and drain before process termination.

## Strict Guidelines
- Engineers MUST ALWAYS initialize a root `tokio_util::sync::CancellationToken` and a `tokio_util::task::TaskTracker` at application entry point.
- Engineers MUST wire the root cancellation token to `axum::serve::with_graceful_shutdown` and trigger token cancellation immediately upon receiving OS termination signals (SIGINT/SIGTERM).
- Services MUST inject child tokens (`token.child_token()`) and cloned `TaskTracker` handles via Tower middleware or Axum `Extension` to all request contexts.
- Components NEVER call naked `tokio::spawn` inside request handlers; all async background tasks MUST be registered with `tracker.spawn(...)` and wrapped with `tokio::select!` evaluating `child_token.cancelled()`.
- Engineers MUST implement explicit drain windows with hard timeouts using `tokio::select!` over `tracker.wait()` and a fail-safe fallback duration after server shutdown initiates.
- Handlers that hold long-lived I/O handles, locks, or database connections MUST abort transaction workflows or issue explicit rollback primitives upon cancellation token activation.

## Bad vs Good Implementations
### Unbounded Detached Background Task vs Managed Token Propagation

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Handler spawns an unmanaged detached future with tokio::spawn. When Kubernetes emits SIGTERM, axum::serve immediately drops connections without awaiting or cancelling the background future. This causes zombie executions, broken database states, and connection leaks during rolling updates.
```rust
use axum::{routing::post, Router};
use tokio::net::TcpListener;

async fn execute_mutation() {
    tokio::time::sleep(tokio::time::Duration::from_secs(30)).await;
}

// ANTI-PATTERN: Detached spawn without cancellation token or TaskTracker.
// On SIGTERM during rolling deploy, process terminates or hangs indefinitely,
// leaving in-flight I/O orphaned and leaking connection pools.
async fn handle_mutation() -> &'static str {
    tokio::spawn(async {
        execute_mutation().await;
    });
    "Accepted"
}

#[tokio::main]
async fn main() {
    let app = Router::new().route("/mutate", post(handle_mutation));
    let listener = TcpListener::bind("0.0.0.0:3000").await.unwrap();
    
    // ANTI-PATTERN: No graceful shutdown wiring or task draining
    axum::serve(listener, app).await.unwrap();
}
```

#### Production Standard (Correct)
> **Standard**: Injects a root CancellationToken and TaskTracker through Axum extensions. Background tasks are tracked via TaskTracker and bind to a child token that reacts immediately to root cancellation. The server implements graceful shutdown and enforces a bounded drain period to guarantee zero socket/task leaks.
```rust
use axum::{extract::Extension, routing::post, Router};
use std::time::Duration;
use tokio::net::TcpListener;
use tokio_util::sync::CancellationToken;
use tokio_util::task::TaskTracker;

async fn execute_mutation(token: CancellationToken) {
    tokio::select! {
        _ = token.cancelled() => {
            tracing::warn!("Worker mutation cancelled: releasing lease");
        }
        _ = tokio::time::sleep(Duration::from_secs(30)) => {
            tracing::info!("Mutation completed successfully");
        }
    }
}

async fn handle_mutation(
    Extension(parent_token): Extension<CancellationToken>,
    Extension(tracker): Extension<TaskTracker>,
) -> &'static str {
    let child_token = parent_token.child_token();
    let task_token = child_token.clone();
    
    tracker.spawn(async move {
        execute_mutation(task_token).await;
    });
    
    "Accepted"
}

#[tokio::main]
async fn main() {
    let root_token = CancellationToken::new();
    let tracker = TaskTracker::new();

    let app = Router::new()
        .route("/mutate", post(handle_mutation))
        .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();
            tracing::info!("Shutdown signal received: broadcasting cancellation");
            shutdown_token.cancel();
        })
        .await
        .unwrap();

    tracker.close();
    tokio::select! {
        _ = tracker.wait() => tracing::info!("All in-flight tasks drained successfully"),
        _ = tokio::time::sleep(Duration::from_secs(10)) => {
            tracing::error!("Shutdown timeout exceeded; force terminating lingering tasks");
        }
    }
}
```

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 In-Flight Cancellation Token Propagation Guardrail

Axum 0.8 In-Flight Cancellation Token Propagation Guardrail defines an industrial-grade behavioral standard for backend engineering. Mandates deterministic propagation of tokio_util::sync::CancellationToken and TaskTracker through Axum 0.8 middleware layers and handlers. Prevents orphaned background tasks, exhausted database connection pools, and leaked socket handles during Kubernetes zero-downtime rolling deploys and unexpected client cancellations. 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 and ignoring shutdown signals inside Axum handlers, producing unmanaged zombie workers during rolling deployments. 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 and ignoring shutdown signals inside Axum handlers, producing unmanaged zombie workers during rolling deployments.Critical
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 initialize a root `tokio_util

Engineers MUST ALWAYS initialize a root `tokio_util::sync::CancellationToken` and a `tokio_util::task::TaskTracker` at application entry point.

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 wire the root cancellation token to `axum

Engineers MUST wire the root cancellation token to `axum::serve::with_graceful_shutdown` and trigger token cancellation immediately upon receiving OS termination signals (SIGINT/SIGTERM).

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 inject child tokens (`token.child_token()`) and cloned `TaskTracker` handles via Tower middleware or Axum `Extension` to all request contexts.

Services MUST inject child tokens (`token.child_token()`) and cloned `TaskTracker` handles via Tower middleware or Axum `Extension` to all request 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.
4

Components NEVER call naked `tokio

Components NEVER call naked `tokio::spawn` inside request handlers; all async background tasks MUST be registered with `tracker.spawn(...)` and wrapped with `tokio::select!` evaluating `child_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.
5

Engineers MUST implement explicit drain windows with hard timeouts using `tokio

Engineers MUST implement explicit drain windows with hard timeouts using `tokio::select!` over `tracker.wait()` and a fail-safe fallback duration after server shutdown initiates.

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.
6

Handlers that hold long-lived I/O handles, locks, or database connections MUST abort transaction workflows or issue explicit rollback primitives upon cancellation token activation.

Handlers that hold long-lived I/O handles, locks, or database connections MUST abort transaction workflows or issue explicit rollback primitives upon cancellation token activation.

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

Mandates deterministic propagation of tokio_util::sync::CancellationToken and TaskTracker through Axum 0.8 middleware layers and handlers. Prevents orphaned background tasks, exhausted database connection pools, and leaked socket handles during Kubernetes zero-downtime rolling deploys and unexpected client cancellations. 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 and ignoring shutdown signals inside Axum handlers, producing unmanaged zombie workers during rolling deployments.) 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