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

Axum 0.8 Tower Cancellation Token Propagation & Zombie Transaction Guardrail

Enforces strict cooperative cancellation token propagation across Axum 0.8 Tower middleware, route handlers, and database adapters. Eliminates orphan compute, task leakage, and lingering zombie database transactions caused by abrupt client disconnections (HTTP/2 RST_STREAM, HTTP/1.1 socket drop).

Prohibited Anti-Pattern: Detached Background Spawning and Silent Drop Failures Causing Zombie Transactions and Connection Pool Starvation

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Axum 0.8 Tower Cancellation Token Propagation & Zombie Transaction Guardrail - Enforces strict cooperative cancellation token propagation across Axum 0.8 Tower middleware, route handlers, and database adapters. Eliminates orphan compute, task leakage, and lingering zombie database transactions caused by abrupt client disconnections (HTTP/2 RST_STREAM, HTTP/1.1 socket drop).
globs: src/**/*.rs, crates/**/*.rs
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/axum-tower-cancellation-token-propagation"
---

# Axum 0.8 Tower Cancellation Token Propagation & Zombie Transaction Guardrail

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Detached Background Spawning and Silent Drop Failures Causing Zombie Transactions and Connection Pool Starvation

## System Constraints
You are a Principal Rust Architect enforcing robust cancellation semantics in Axum 0.8 and Tower ecosystems. You mandate the use of `tokio_util::sync::CancellationToken` and RAII-bound drop guards across all middleware boundaries, preventing detached execution, task leaks, and zombie database transactions when clients disconnect.

## Strict Guidelines
- Engineers MUST ALWAYS inject a child `tokio_util::sync::CancellationToken` via an Axum middleware layer into request extensions at the boundary of incoming HTTP requests.
- Engineers MUST NOT invoke `tokio::spawn` within request lifecycles without binding spawned tasks to a child `CancellationToken` or registering them with a scoped `tokio_util::task::TaskTracker`.
- Handlers MUST pass the extracted `CancellationToken` down into long-running compute loops and I/O-bound database routines.
- Database operations involving multi-step transactions MUST race against `cancellation_token.cancelled()` or rely on an RAII drop guard to issue an explicit rollback when the handling future is dropped prematurely.
- Services MUST ensure that external HTTP/gRPC client calls initiated within request lifecycles are wrapped with `.abort_on_cancel()` or raced against the request's cancellation token.
- Components NEVER assume that dropping a future will automatically clean up external state if background tasks or uncommitted multi-statement transactions have already been dispatched.

## Bad vs Good Implementations
### Axum 0.8 Cancellation Token Middleware and Scoped Handler Execution

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: When an HTTP client aborts or disconnects prematurely, the detached `tokio::spawn` continues running indefinitely. It consumes expensive billing RPCs and database connections without any cooperative cancellation mechanism, leading to zombie transactions and connection pool starvation.
```rust
use axum::{extract::State, Json};
use sqlx::PgPool;

// ANTI-PATTERN: Client disconnect drops the handler future, but tokio::spawn
// runs detached. If a transaction was started, it can orphan work or cause
// resource leaks and pool contention without cancellation awareness.
#[axum::debug_handler]
pub async fn checkout_handler(
    State(pool): State<PgPool>,
    Json(payload): Json<CheckoutRequest>,
) -> Result<Json<Receipt>, AppError> {
    // Spawning fire-and-forget task with no cancellation token link
    tokio::spawn(async move {
        let mut tx = pool.begin().await.unwrap();
        heavy_billing_rpc(&payload).await.unwrap();
        sqlx::query("INSERT INTO orders ...")
            .execute(&mut *tx)
            .await
            .unwrap();
        tx.commit().await.unwrap();
    });

    Ok(Json(Receipt::accepted()))
}
```

#### Production Standard (Correct)
> **Standard**: An explicit `CancellationToken` is registered in request extensions by a Tower middleware and guarded by an RAII `CancellationGuard`. If the client disconnects, hyper/Axum drops the request future, triggering the drop guard, firing the token, and immediately stopping all downstream futures and rolling back the database transaction.
```rust
use axum::{
    extract::{Extension, Request, State},
    middleware::Next,
    response::Response,
    Json,
};
use sqlx::PgPool;
use tokio_util::sync::CancellationToken;

/// RAII Guard that cancels the token on drop (e.g. client disconnect drops the future)
struct CancellationGuard(CancellationToken);

impl Drop for CancellationGuard {
    fn drop(&mut self) {
        self.0.cancel();
    }
}

/// Tower middleware injecting request-scoped cancellation tokens
pub async fn cancellation_layer(mut req: Request, next: Next) -> Response {
    let token = CancellationToken::new();
    req.extensions_mut().insert(token.clone());
    let _guard = CancellationGuard(token);

    next.run(req).await
}

/// Handler respecting cancellation token across async boundaries
#[axum::debug_handler]
pub async fn checkout_handler(
    State(pool): State<PgPool>,
    Extension(token): Extension<CancellationToken>,
    Json(payload): Json<CheckoutRequest>,
) -> Result<Json<Receipt>, AppError> {
    let child_token = token.child_token();

    // Race critical transaction work against cooperative cancellation
    tokio::select! {
        _ = child_token.cancelled() => {
            tracing::warn!("Client disconnected; aborting checkout transaction");
            Err(AppError::ClientClosedRequest)
        }
        res = execute_checkout_tx(&pool, &payload, child_token) => {
            res.map(Json)
        }
    }
}

async fn execute_checkout_tx(
    pool: &PgPool,
    payload: &CheckoutRequest,
    token: CancellationToken,
) -> Result<Receipt, AppError> {
    let mut tx = pool.begin().await?;

    // Pass token or check inside multi-step processes
    if token.is_cancelled() {
        tx.rollback().await?;
        return Err(AppError::ClientClosedRequest);
    }

    sqlx::query("INSERT INTO orders (id, user_id) VALUES ($1, $2)")
        .bind(payload.order_id)
        .bind(payload.user_id)
        .execute(&mut *tx)
        .await?;

    tx.commit().await?;
    Ok(Receipt::success(payload.order_id))
}
```

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 Tower Cancellation Token Propagation & Zombie Transaction Guardrail

Axum 0.8 Tower Cancellation Token Propagation & Zombie Transaction Guardrail defines an industrial-grade behavioral standard for backend engineering. Enforces strict cooperative cancellation token propagation across Axum 0.8 Tower middleware, route handlers, and database adapters. Eliminates orphan compute, task leakage, and lingering zombie database transactions caused by abrupt client disconnections (HTTP/2 RST_STREAM, HTTP/1.1 socket drop). 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 Background Spawning and Silent Drop Failures Causing Zombie Transactions and Connection Pool Starvation 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 Background Spawning and Silent Drop Failures Causing Zombie Transactions and Connection Pool StarvationCritical
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 inject a child `tokio_util

Engineers MUST ALWAYS inject a child `tokio_util::sync::CancellationToken` via an Axum middleware layer into request extensions at the boundary of incoming HTTP requests.

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` within request lifecycles without binding spawned tasks to a child `CancellationToken` or registering them with a scoped `tokio_util::task::TaskTracker`.

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

Handlers MUST pass the extracted `CancellationToken` down into long-running compute loops and I/O-bound database routines.

Handlers MUST pass the extracted `CancellationToken` down into long-running compute loops and I/O-bound database routines.

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

Database operations involving multi-step transactions MUST race against `cancellation_token.cancelled()` or rely on an RAII drop guard to issue an explicit rollback when the handling future is dropped prematurely.

Database operations involving multi-step transactions MUST race against `cancellation_token.cancelled()` or rely on an RAII drop guard to issue an explicit rollback when the handling future is dropped prematurely.

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

Services MUST ensure that external HTTP/gRPC client calls initiated within request lifecycles are wrapped with `.abort_on_cancel()` or raced against the request's cancellation token.

Services MUST ensure that external HTTP/gRPC client calls initiated within request lifecycles are wrapped with `.abort_on_cancel()` or raced against the request's cancellation 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.
6

Components NEVER assume that dropping a future will automatically clean up external state if background tasks or uncommitted multi-statement transactions have already been dispatched.

Components NEVER assume that dropping a future will automatically clean up external state if background tasks or uncommitted multi-statement transactions have already been dispatched.

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 Tower Cancellation Token Propagation & Zombie Transaction Guardrail critical for AI coding assistants?

Enforces strict cooperative cancellation token propagation across Axum 0.8 Tower middleware, route handlers, and database adapters. Eliminates orphan compute, task leakage, and lingering zombie database transactions caused by abrupt client disconnections (HTTP/2 RST_STREAM, HTTP/1.1 socket drop). 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 Background Spawning and Silent Drop Failures Causing Zombie Transactions and Connection Pool Starvation) 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